unit_tests.py 7.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. #!/usr/bin/env python3
  2. #
  3. # MMGen Wallet, a terminal-based cryptocurrency wallet
  4. # Copyright (C)2013-2024 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,asyncio
  22. try:
  23. from include.test_init import repo_root
  24. except ImportError:
  25. from test.include.test_init import repo_root
  26. # for the unit tests, violate MMGen Project best practices and allow use of the dev tools
  27. # in production code:
  28. if not os.getenv('MMGEN_DEVTOOLS'):
  29. from mmgen.devinit import init_dev
  30. init_dev()
  31. from mmgen.cfg import Config,gc
  32. from mmgen.color import gray, brown, orange, yellow, red
  33. from mmgen.util import msg, msg_r, gmsg, ymsg, Msg
  34. from test.include.common import set_globals,end_msg
  35. def die(ev,s):
  36. msg((red if ev > 1 else yellow)(s))
  37. sys.exit(ev)
  38. opts_data = {
  39. 'text': {
  40. 'desc': "Unit tests for the MMGen suite",
  41. 'usage':'[options] [test | test.subtest]...',
  42. 'options': """
  43. -h, --help Print this help message
  44. -a, --no-altcoin-deps Skip tests requiring altcoin daemons, libs or utils
  45. -A, --no-daemon-autostart Don't start and stop daemons automatically
  46. -D, --no-daemon-stop Don't stop auto-started daemons after running tests
  47. -f, --fast Speed up execution by reducing rounds on some tests
  48. -l, --list List available tests
  49. -L, --list-subtests List available tests and subtests
  50. -n, --names Print command names instead of descriptions
  51. -q, --quiet Produce quieter output
  52. -x, --exclude=T Exclude tests 'T' (comma-separated)
  53. -v, --verbose Produce more verbose output
  54. """,
  55. 'notes': """
  56. If no test is specified, all available tests are run
  57. """
  58. }
  59. }
  60. if os.path.islink(Config.test_datadir):
  61. os.unlink(Config.test_datadir)
  62. sys.argv.insert(1,'--skip-cfg-file')
  63. cfg = Config(opts_data=opts_data)
  64. if cfg.no_altcoin_deps:
  65. ymsg(f'{gc.prog_name}: skipping altcoin tests by user request')
  66. type(cfg)._reset_ok += ('use_internal_keccak_module','debug_addrlist')
  67. set_globals(cfg)
  68. file_pfx = 'ut_'
  69. tests_d = os.path.join(repo_root,'test','unit_tests_d')
  70. all_tests = sorted(fn[len(file_pfx):-len('.py')] for fn in os.listdir(tests_d) if fn.startswith(file_pfx))
  71. exclude = cfg.exclude.split(',') if cfg.exclude else []
  72. for e in exclude:
  73. if e not in all_tests:
  74. die(1,f'{e!r}: invalid parameter for --exclude (no such test)')
  75. start_time = int(time.time())
  76. if cfg.list:
  77. Msg(' '.join(all_tests))
  78. sys.exit(0)
  79. if cfg.list_subtests:
  80. def gen():
  81. for test in all_tests:
  82. mod = importlib.import_module(f'test.unit_tests_d.{file_pfx}{test}')
  83. if hasattr(mod,'unit_tests'):
  84. t = getattr(mod,'unit_tests')
  85. subtests = [k for k,v in t.__dict__.items() if type(v).__name__ == 'function' and k[0] != '_']
  86. yield fs.format( test, ' '.join(f'{subtest}' for subtest in subtests) )
  87. else:
  88. yield test
  89. fs = '{:%s} {}' % max(len(t) for t in all_tests)
  90. Msg( fs.format('TEST','SUBTESTS') + '\n' + '\n'.join(gen()) )
  91. sys.exit(0)
  92. class UnitTestHelpers:
  93. def __init__(self,subtest_name):
  94. self.subtest_name = subtest_name
  95. def skip_msg(self,desc):
  96. cfg._util.qmsg(gray(f'Skipping subtest {self.subtest_name.replace("_","-")!r} for {desc}'))
  97. def process_bad_data(self,data,pfx='bad '):
  98. if os.getenv('PYTHONOPTIMIZE'):
  99. ymsg('PYTHONOPTIMIZE set, skipping error handling tests')
  100. return
  101. import re
  102. desc_w = max(len(e[0]) for e in data)
  103. exc_w = max(len(e[1]) for e in data)
  104. m_exc = '{!r}: incorrect exception type (expected {!r})'
  105. m_err = '{!r}: incorrect error msg (should match {!r}'
  106. m_noraise = "\nillegal action '{}{}' failed to raise an exception (expected {!r})"
  107. for (desc,exc_chk,emsg_chk,func) in data:
  108. try:
  109. cfg._util.vmsg_r(' {}{:{w}}'.format(pfx, desc+':', w=desc_w+1))
  110. ret = func()
  111. if type(ret).__name__ == 'coroutine':
  112. asyncio.run(ret)
  113. except Exception as e:
  114. exc = type(e).__name__
  115. emsg = e.args[0]
  116. cfg._util.vmsg(f' {exc:{exc_w}} [{emsg}]')
  117. assert exc == exc_chk, m_exc.format(exc,exc_chk)
  118. assert re.search(emsg_chk,emsg), m_err.format(emsg,emsg_chk)
  119. else:
  120. die(4,m_noraise.format(pfx,desc,exc_chk))
  121. tests_seen = []
  122. def run_test(test,subtest=None):
  123. mod = importlib.import_module(f'test.unit_tests_d.{file_pfx}{test}')
  124. def run_subtest(t,subtest):
  125. subtest_disp = subtest.replace('_','-')
  126. msg(brown('Running unit subtest ') + orange(f'{test}.{subtest_disp}'))
  127. if getattr(t,'silence_output',False):
  128. t._silence()
  129. if hasattr(t,'_pre_subtest'):
  130. getattr(t,'_pre_subtest')(test,subtest,UnitTestHelpers(subtest))
  131. try:
  132. func = getattr(t,subtest.replace('-','_'))
  133. c = func.__code__
  134. do_desc = c.co_varnames[c.co_argcount-1] == 'desc'
  135. if do_desc:
  136. if cfg.verbose:
  137. msg(f'Testing {func.__defaults__[0]}')
  138. elif not cfg.quiet:
  139. msg_r(f'Testing {func.__defaults__[0]}...')
  140. ret = func(test, UnitTestHelpers(subtest))
  141. if type(ret).__name__ == 'coroutine':
  142. ret = asyncio.run(ret)
  143. if do_desc and not cfg.quiet:
  144. msg('OK\n' if cfg.verbose else 'OK')
  145. except:
  146. if getattr(t,'silence_output',False):
  147. t._end_silence()
  148. raise
  149. if hasattr(t,'_post_subtest'):
  150. getattr(t,'_post_subtest')(test,subtest,UnitTestHelpers(subtest))
  151. if getattr(t,'silence_output',False):
  152. t._end_silence()
  153. if not ret:
  154. die(4,f'Unit subtest {subtest_disp!r} failed')
  155. if test not in tests_seen:
  156. gmsg(f'Running unit test {test}')
  157. tests_seen.append(test)
  158. if cfg.no_altcoin_deps and getattr(mod,'altcoin_dep',None):
  159. cfg._util.qmsg(gray(f'Skipping unit test {test!r} [--no-altcoin-deps]'))
  160. return
  161. if hasattr(mod,'unit_tests'): # new class-based API
  162. t = getattr(mod,'unit_tests')()
  163. altcoin_deps = getattr(t,'altcoin_deps',())
  164. win_skip = getattr(t, 'win_skip', ())
  165. mac_skip = getattr(t, 'mac_skip', ())
  166. arm_skip = getattr(t, 'arm_skip', ())
  167. subtests = (
  168. [subtest] if subtest else
  169. [k for k,v in type(t).__dict__.items() if type(v).__name__ == 'function' and k[0] != '_']
  170. )
  171. if hasattr(t,'_pre'):
  172. t._pre()
  173. for _subtest in subtests:
  174. subtest_disp = _subtest.replace('_','-')
  175. if cfg.no_altcoin_deps and _subtest in altcoin_deps:
  176. cfg._util.qmsg(gray(f'Skipping unit subtest {subtest_disp!r} [--no-altcoin-deps]'))
  177. continue
  178. if sys.platform == 'win32' and _subtest in win_skip:
  179. cfg._util.qmsg(gray(f'Skipping unit subtest {subtest_disp!r} for Windows platform'))
  180. continue
  181. if sys.platform == 'darwin' and _subtest in mac_skip:
  182. cfg._util.qmsg(gray(f'Skipping unit subtest {subtest_disp!r} for macOS platform'))
  183. continue
  184. if platform.machine() == 'aarch64' and _subtest in arm_skip:
  185. cfg._util.qmsg(gray(f'Skipping unit subtest {subtest_disp!r} for ARM platform'))
  186. continue
  187. run_subtest(t, _subtest)
  188. if hasattr(t,'_post'):
  189. t._post()
  190. else:
  191. assert not subtest, f'{subtest!r}: subtests not supported for this unit test'
  192. if not mod.unit_test().run_test(test,UnitTestHelpers(test)):
  193. die(4,'Unit test {test!r} failed')
  194. def main():
  195. for test in (cfg._args or all_tests):
  196. if '.' in test:
  197. test,subtest = test.split('.')
  198. else:
  199. subtest = None
  200. if test not in all_tests:
  201. die(1,f'{test!r}: test not recognized')
  202. if test not in exclude:
  203. run_test(test,subtest=subtest)
  204. end_msg(int(time.time()) - start_time)
  205. from mmgen.main import launch
  206. launch(func=main)