unit_tests.py 3.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2020 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
  22. from include.tests_header import repo_root
  23. from mmgen.common import *
  24. opts_data = {
  25. 'text': {
  26. 'desc': "Unit tests for the MMGen suite",
  27. 'usage':'[options] [tests | test [subtest]]',
  28. 'options': """
  29. -h, --help Print this help message
  30. -A, --no-daemon-autostart Don't start and stop daemons automatically
  31. -D, --no-daemon-stop Don't stop auto-started daemons after running tests
  32. -f, --fast Speed up execution by reducing rounds on some tests
  33. -l, --list List available tests
  34. -n, --names Print command names instead of descriptions
  35. -q, --quiet Produce quieter output
  36. -v, --verbose Produce more verbose output
  37. """,
  38. 'notes': """
  39. If no test is specified, all available tests are run
  40. """
  41. }
  42. }
  43. sys.argv.insert(1,'--skip-cfg-file')
  44. cmd_args = opts.init(opts_data)
  45. def exit_msg():
  46. t = int(time.time()) - start_time
  47. gmsg('All requested tests finished OK, elapsed time: {:02}:{:02}'.format(t//60,t%60))
  48. all_tests = [fn[3:-3] for fn in os.listdir(os.path.join(repo_root,'test','unit_tests_d')) if fn[:3] == 'ut_']
  49. start_time = int(time.time())
  50. if opt.list:
  51. Die(0,' '.join(all_tests))
  52. class UnitTestHelpers(object):
  53. @classmethod
  54. def process_bad_data(cls,data):
  55. import re
  56. desc_w = max(len(e[0]) for e in data)
  57. exc_w = max(len(e[1]) for e in data)
  58. m_exc = '{!r}: incorrect exception type (expected {!r})'
  59. m_err = '{!r}: incorrect error msg (should match {!r}'
  60. m_noraise = "\nillegal action 'bad {}' failed to raise exception {!r}"
  61. for (desc,exc_chk,emsg_chk,func) in data:
  62. try:
  63. vmsg_r(' bad {:{w}}'.format(desc+':',w=desc_w+1))
  64. func()
  65. except Exception as e:
  66. exc = type(e).__name__
  67. emsg = e.args[0]
  68. vmsg(' {:{w}} [{}]'.format(exc,emsg,w=exc_w))
  69. assert exc == exc_chk, m_exc.format(exc,exc_chk)
  70. assert re.search(emsg_chk,emsg), m_err.format(emsg,emsg_chk)
  71. else:
  72. rdie(3,m_noraise.format(desc,exc_chk))
  73. def run_test(test,subtest=None):
  74. modname = 'test.unit_tests_d.ut_{}'.format(test)
  75. mod = importlib.import_module(modname)
  76. def run_subtest(subtest):
  77. gmsg(f'Running unit subtest {test}.{subtest}')
  78. t = getattr(mod,'unit_tests')()
  79. if not getattr(t,subtest)(test,UnitTestHelpers):
  80. rdie(1,f'Unit subtest {subtest!r} failed')
  81. pass
  82. if subtest:
  83. run_subtest(subtest)
  84. else:
  85. gmsg(f'Running unit test {test}')
  86. if hasattr(mod,'unit_tests'):
  87. t = getattr(mod,'unit_tests')
  88. subtests = [k for k,v in t.__dict__.items() if type(v).__name__ == 'function']
  89. for subtest in subtests:
  90. run_subtest(subtest)
  91. else:
  92. if not mod.unit_test().run_test(test,UnitTestHelpers):
  93. rdie(1,'Unit test {test!r} failed')
  94. try:
  95. import importlib
  96. if len(cmd_args) == 2 and cmd_args[0] in all_tests and cmd_args[1] not in all_tests:
  97. run_test(*cmd_args) # assume 2nd arg is subtest
  98. else:
  99. for test in cmd_args:
  100. if test not in all_tests:
  101. die(1,f'{test!r}: test not recognized')
  102. for test in (cmd_args or all_tests):
  103. run_test(test)
  104. exit_msg()
  105. except KeyboardInterrupt:
  106. die(1,green('\nExiting at user request'))