jack2 codebase
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

202 lines
6.1KB

  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Carlos Rafael Giani, 2006
  4. # Thomas Nagy, 2010
  5. """
  6. Unit testing system for C/C++/D providing test execution:
  7. * in parallel, by using ``waf -j``
  8. * partial (only the tests that have changed) or full (by using ``waf --alltests``)
  9. The tests are declared by adding the **test** feature to programs::
  10. def options(opt):
  11. opt.load('compiler_cxx waf_unit_test')
  12. def configure(conf):
  13. conf.load('compiler_cxx waf_unit_test')
  14. def build(bld):
  15. bld(features='cxx cxxprogram test', source='main.cpp', target='app')
  16. # or
  17. bld.program(features='test', source='main2.cpp', target='app2')
  18. When the build is executed, the program 'test' will be built and executed without arguments.
  19. The success/failure is detected by looking at the return code. The status and the standard output/error
  20. are stored on the build context.
  21. The results can be displayed by registering a callback function. Here is how to call
  22. the predefined callback::
  23. def build(bld):
  24. bld(features='cxx cxxprogram test', source='main.c', target='app')
  25. from waflib.Tools import waf_unit_test
  26. bld.add_post_fun(waf_unit_test.summary)
  27. """
  28. import os
  29. from waflib.TaskGen import feature, after_method, taskgen_method
  30. from waflib import Utils, Task, Logs, Options
  31. testlock = Utils.threading.Lock()
  32. @feature('test')
  33. @after_method('apply_link')
  34. def make_test(self):
  35. """Create the unit test task. There can be only one unit test task by task generator."""
  36. if getattr(self, 'link_task', None):
  37. self.create_task('utest', self.link_task.outputs)
  38. @taskgen_method
  39. def add_test_results(self, tup):
  40. """Override and return tup[1] to interrupt the build immediately if a test does not run"""
  41. Logs.debug("ut: %r", tup)
  42. self.utest_result = tup
  43. try:
  44. self.bld.utest_results.append(tup)
  45. except AttributeError:
  46. self.bld.utest_results = [tup]
  47. class utest(Task.Task):
  48. """
  49. Execute a unit test
  50. """
  51. color = 'PINK'
  52. after = ['vnum', 'inst']
  53. vars = []
  54. def runnable_status(self):
  55. """
  56. Always execute the task if `waf --alltests` was used or no
  57. tests if ``waf --notests`` was used
  58. """
  59. if getattr(Options.options, 'no_tests', False):
  60. return Task.SKIP_ME
  61. ret = super(utest, self).runnable_status()
  62. if ret == Task.SKIP_ME:
  63. if getattr(Options.options, 'all_tests', False):
  64. return Task.RUN_ME
  65. return ret
  66. def add_path(self, dct, path, var):
  67. dct[var] = os.pathsep.join(Utils.to_list(path) + [os.environ.get(var, '')])
  68. def get_test_env(self):
  69. """
  70. In general, tests may require any library built anywhere in the project.
  71. Override this method if fewer paths are needed
  72. """
  73. try:
  74. fu = getattr(self.generator.bld, 'all_test_paths')
  75. except AttributeError:
  76. # this operation may be performed by at most #maxjobs
  77. fu = os.environ.copy()
  78. lst = []
  79. for g in self.generator.bld.groups:
  80. for tg in g:
  81. if getattr(tg, 'link_task', None):
  82. s = tg.link_task.outputs[0].parent.abspath()
  83. if s not in lst:
  84. lst.append(s)
  85. if Utils.is_win32:
  86. self.add_path(fu, lst, 'PATH')
  87. elif Utils.unversioned_sys_platform() == 'darwin':
  88. self.add_path(fu, lst, 'DYLD_LIBRARY_PATH')
  89. self.add_path(fu, lst, 'LD_LIBRARY_PATH')
  90. else:
  91. self.add_path(fu, lst, 'LD_LIBRARY_PATH')
  92. self.generator.bld.all_test_paths = fu
  93. return fu
  94. def run(self):
  95. """
  96. Execute the test. The execution is always successful, and the results
  97. are stored on ``self.generator.bld.utest_results`` for postprocessing.
  98. Override ``add_test_results`` to interrupt the build
  99. """
  100. filename = self.inputs[0].abspath()
  101. self.ut_exec = getattr(self.generator, 'ut_exec', [filename])
  102. if getattr(self.generator, 'ut_fun', None):
  103. self.generator.ut_fun(self)
  104. cwd = getattr(self.generator, 'ut_cwd', '') or self.inputs[0].parent.abspath()
  105. testcmd = getattr(self.generator, 'ut_cmd', False) or getattr(Options.options, 'testcmd', False)
  106. if testcmd:
  107. self.ut_exec = (testcmd % self.ut_exec[0]).split(' ')
  108. proc = Utils.subprocess.Popen(self.ut_exec, cwd=cwd, env=self.get_test_env(), stderr=Utils.subprocess.PIPE, stdout=Utils.subprocess.PIPE)
  109. (stdout, stderr) = proc.communicate()
  110. tup = (filename, proc.returncode, stdout, stderr)
  111. testlock.acquire()
  112. try:
  113. return self.generator.add_test_results(tup)
  114. finally:
  115. testlock.release()
  116. def summary(bld):
  117. """
  118. Display an execution summary::
  119. def build(bld):
  120. bld(features='cxx cxxprogram test', source='main.c', target='app')
  121. from waflib.Tools import waf_unit_test
  122. bld.add_post_fun(waf_unit_test.summary)
  123. """
  124. lst = getattr(bld, 'utest_results', [])
  125. if lst:
  126. Logs.pprint('CYAN', 'execution summary')
  127. total = len(lst)
  128. tfail = len([x for x in lst if x[1]])
  129. Logs.pprint('CYAN', ' tests that pass %d/%d' % (total-tfail, total))
  130. for (f, code, out, err) in lst:
  131. if not code:
  132. Logs.pprint('CYAN', ' %s' % f)
  133. Logs.pprint('CYAN', ' tests that fail %d/%d' % (tfail, total))
  134. for (f, code, out, err) in lst:
  135. if code:
  136. Logs.pprint('CYAN', ' %s' % f)
  137. def set_exit_code(bld):
  138. """
  139. If any of the tests fail waf will exit with that exit code.
  140. This is useful if you have an automated build system which need
  141. to report on errors from the tests.
  142. You may use it like this:
  143. def build(bld):
  144. bld(features='cxx cxxprogram test', source='main.c', target='app')
  145. from waflib.Tools import waf_unit_test
  146. bld.add_post_fun(waf_unit_test.set_exit_code)
  147. """
  148. lst = getattr(bld, 'utest_results', [])
  149. for (f, code, out, err) in lst:
  150. if code:
  151. msg = []
  152. if out:
  153. msg.append('stdout:%s%s' % (os.linesep, out.decode('utf-8')))
  154. if err:
  155. msg.append('stderr:%s%s' % (os.linesep, err.decode('utf-8')))
  156. bld.fatal(os.linesep.join(msg))
  157. def options(opt):
  158. """
  159. Provide the ``--alltests``, ``--notests`` and ``--testcmd`` command-line options.
  160. """
  161. opt.add_option('--notests', action='store_true', default=False, help='Exec no unit tests', dest='no_tests')
  162. opt.add_option('--alltests', action='store_true', default=False, help='Exec all unit tests', dest='all_tests')
  163. opt.add_option('--testcmd', action='store', default=False,
  164. help = 'Run the unit tests using the test-cmd string'
  165. ' example "--test-cmd="valgrind --error-exitcode=1'
  166. ' %s" to run under valgrind', dest='testcmd')