waf_unit_test.py 9.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296
  1. #!/usr/bin/env python
  2. # encoding: utf-8
  3. # Carlos Rafael Giani, 2006
  4. # Thomas Nagy, 2010-2018 (ita)
  5. """
  6. Unit testing system for C/C++/D and interpreted languages 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. By passing --dump-test-scripts the build outputs corresponding python files
  28. (with extension _run.py) that are useful for debugging purposes.
  29. """
  30. import os, shlex, sys
  31. from waflib.TaskGen import feature, after_method, taskgen_method
  32. from waflib import Utils, Task, Logs, Options
  33. from waflib.Tools import ccroot
  34. testlock = Utils.threading.Lock()
  35. SCRIPT_TEMPLATE = """#! %(python)s
  36. import subprocess, sys
  37. cmd = %(cmd)r
  38. # if you want to debug with gdb:
  39. #cmd = ['gdb', '-args'] + cmd
  40. env = %(env)r
  41. status = subprocess.call(cmd, env=env, cwd=%(cwd)r, shell=isinstance(cmd, str))
  42. sys.exit(status)
  43. """
  44. @taskgen_method
  45. def handle_ut_cwd(self, key):
  46. """
  47. Task generator method, used internally to limit code duplication.
  48. This method may disappear anytime.
  49. """
  50. cwd = getattr(self, key, None)
  51. if cwd:
  52. if isinstance(cwd, str):
  53. # we want a Node instance
  54. if os.path.isabs(cwd):
  55. self.ut_cwd = self.bld.root.make_node(cwd)
  56. else:
  57. self.ut_cwd = self.path.make_node(cwd)
  58. @feature('test_scripts')
  59. def make_interpreted_test(self):
  60. """Create interpreted unit tests."""
  61. for x in ['test_scripts_source', 'test_scripts_template']:
  62. if not hasattr(self, x):
  63. Logs.warn('a test_scripts taskgen i missing %s' % x)
  64. return
  65. self.ut_run, lst = Task.compile_fun(self.test_scripts_template, shell=getattr(self, 'test_scripts_shell', False))
  66. script_nodes = self.to_nodes(self.test_scripts_source)
  67. for script_node in script_nodes:
  68. tsk = self.create_task('utest', [script_node])
  69. tsk.vars = lst + tsk.vars
  70. tsk.env['SCRIPT'] = script_node.path_from(tsk.get_cwd())
  71. self.handle_ut_cwd('test_scripts_cwd')
  72. env = getattr(self, 'test_scripts_env', None)
  73. if env:
  74. self.ut_env = env
  75. else:
  76. self.ut_env = dict(os.environ)
  77. paths = getattr(self, 'test_scripts_paths', {})
  78. for (k,v) in paths.items():
  79. p = self.ut_env.get(k, '').split(os.pathsep)
  80. if isinstance(v, str):
  81. v = v.split(os.pathsep)
  82. self.ut_env[k] = os.pathsep.join(p + v)
  83. @feature('test')
  84. @after_method('apply_link', 'process_use')
  85. def make_test(self):
  86. """Create the unit test task. There can be only one unit test task by task generator."""
  87. if not getattr(self, 'link_task', None):
  88. return
  89. tsk = self.create_task('utest', self.link_task.outputs)
  90. if getattr(self, 'ut_str', None):
  91. self.ut_run, lst = Task.compile_fun(self.ut_str, shell=getattr(self, 'ut_shell', False))
  92. tsk.vars = lst + tsk.vars
  93. self.handle_ut_cwd('ut_cwd')
  94. if not hasattr(self, 'ut_paths'):
  95. paths = []
  96. for x in self.tmp_use_sorted:
  97. try:
  98. y = self.bld.get_tgen_by_name(x).link_task
  99. except AttributeError:
  100. pass
  101. else:
  102. if not isinstance(y, ccroot.stlink_task):
  103. paths.append(y.outputs[0].parent.abspath())
  104. self.ut_paths = os.pathsep.join(paths) + os.pathsep
  105. if not hasattr(self, 'ut_env'):
  106. self.ut_env = dct = dict(os.environ)
  107. def add_path(var):
  108. dct[var] = self.ut_paths + dct.get(var,'')
  109. if Utils.is_win32:
  110. add_path('PATH')
  111. elif Utils.unversioned_sys_platform() == 'darwin':
  112. add_path('DYLD_LIBRARY_PATH')
  113. add_path('LD_LIBRARY_PATH')
  114. else:
  115. add_path('LD_LIBRARY_PATH')
  116. if not hasattr(self, 'ut_cmd'):
  117. self.ut_cmd = getattr(Options.options, 'testcmd', False)
  118. @taskgen_method
  119. def add_test_results(self, tup):
  120. """Override and return tup[1] to interrupt the build immediately if a test does not run"""
  121. Logs.debug("ut: %r", tup)
  122. try:
  123. self.utest_results.append(tup)
  124. except AttributeError:
  125. self.utest_results = [tup]
  126. try:
  127. self.bld.utest_results.append(tup)
  128. except AttributeError:
  129. self.bld.utest_results = [tup]
  130. @Task.deep_inputs
  131. class utest(Task.Task):
  132. """
  133. Execute a unit test
  134. """
  135. color = 'PINK'
  136. after = ['vnum', 'inst']
  137. vars = []
  138. def runnable_status(self):
  139. """
  140. Always execute the task if `waf --alltests` was used or no
  141. tests if ``waf --notests`` was used
  142. """
  143. if getattr(Options.options, 'no_tests', False):
  144. return Task.SKIP_ME
  145. ret = super(utest, self).runnable_status()
  146. if ret == Task.SKIP_ME:
  147. if getattr(Options.options, 'all_tests', False):
  148. return Task.RUN_ME
  149. return ret
  150. def get_test_env(self):
  151. """
  152. In general, tests may require any library built anywhere in the project.
  153. Override this method if fewer paths are needed
  154. """
  155. return self.generator.ut_env
  156. def post_run(self):
  157. super(utest, self).post_run()
  158. if getattr(Options.options, 'clear_failed_tests', False) and self.waf_unit_test_results[1]:
  159. self.generator.bld.task_sigs[self.uid()] = None
  160. def run(self):
  161. """
  162. Execute the test. The execution is always successful, and the results
  163. are stored on ``self.generator.bld.utest_results`` for postprocessing.
  164. Override ``add_test_results`` to interrupt the build
  165. """
  166. if hasattr(self.generator, 'ut_run'):
  167. return self.generator.ut_run(self)
  168. self.ut_exec = getattr(self.generator, 'ut_exec', [self.inputs[0].abspath()])
  169. ut_cmd = getattr(self.generator, 'ut_cmd', False)
  170. if ut_cmd:
  171. self.ut_exec = shlex.split(ut_cmd % ' '.join(self.ut_exec))
  172. return self.exec_command(self.ut_exec)
  173. def exec_command(self, cmd, **kw):
  174. Logs.debug('runner: %r', cmd)
  175. if getattr(Options.options, 'dump_test_scripts', False):
  176. script_code = SCRIPT_TEMPLATE % {
  177. 'python': sys.executable,
  178. 'env': self.get_test_env(),
  179. 'cwd': self.get_cwd().abspath(),
  180. 'cmd': cmd
  181. }
  182. script_file = self.inputs[0].abspath() + '_run.py'
  183. Utils.writef(script_file, script_code)
  184. os.chmod(script_file, Utils.O755)
  185. if Logs.verbose > 1:
  186. Logs.info('Test debug file written as %r' % script_file)
  187. proc = Utils.subprocess.Popen(cmd, cwd=self.get_cwd().abspath(), env=self.get_test_env(),
  188. stderr=Utils.subprocess.PIPE, stdout=Utils.subprocess.PIPE, shell=isinstance(cmd,str))
  189. (stdout, stderr) = proc.communicate()
  190. self.waf_unit_test_results = tup = (self.inputs[0].abspath(), proc.returncode, stdout, stderr)
  191. testlock.acquire()
  192. try:
  193. return self.generator.add_test_results(tup)
  194. finally:
  195. testlock.release()
  196. def get_cwd(self):
  197. return getattr(self.generator, 'ut_cwd', self.inputs[0].parent)
  198. def summary(bld):
  199. """
  200. Display an execution summary::
  201. def build(bld):
  202. bld(features='cxx cxxprogram test', source='main.c', target='app')
  203. from waflib.Tools import waf_unit_test
  204. bld.add_post_fun(waf_unit_test.summary)
  205. """
  206. lst = getattr(bld, 'utest_results', [])
  207. if lst:
  208. Logs.pprint('CYAN', 'execution summary')
  209. total = len(lst)
  210. tfail = len([x for x in lst if x[1]])
  211. Logs.pprint('GREEN', ' tests that pass %d/%d' % (total-tfail, total))
  212. for (f, code, out, err) in lst:
  213. if not code:
  214. Logs.pprint('GREEN', ' %s' % f)
  215. Logs.pprint('GREEN' if tfail == 0 else 'RED', ' tests that fail %d/%d' % (tfail, total))
  216. for (f, code, out, err) in lst:
  217. if code:
  218. Logs.pprint('RED', ' %s' % f)
  219. def set_exit_code(bld):
  220. """
  221. If any of the tests fail waf will exit with that exit code.
  222. This is useful if you have an automated build system which need
  223. to report on errors from the tests.
  224. You may use it like this:
  225. def build(bld):
  226. bld(features='cxx cxxprogram test', source='main.c', target='app')
  227. from waflib.Tools import waf_unit_test
  228. bld.add_post_fun(waf_unit_test.set_exit_code)
  229. """
  230. lst = getattr(bld, 'utest_results', [])
  231. for (f, code, out, err) in lst:
  232. if code:
  233. msg = []
  234. if out:
  235. msg.append('stdout:%s%s' % (os.linesep, out.decode('utf-8')))
  236. if err:
  237. msg.append('stderr:%s%s' % (os.linesep, err.decode('utf-8')))
  238. bld.fatal(os.linesep.join(msg))
  239. def options(opt):
  240. """
  241. Provide the ``--alltests``, ``--notests`` and ``--testcmd`` command-line options.
  242. """
  243. opt.add_option('--notests', action='store_true', default=False, help='Exec no unit tests', dest='no_tests')
  244. opt.add_option('--alltests', action='store_true', default=False, help='Exec all unit tests', dest='all_tests')
  245. opt.add_option('--clear-failed', action='store_true', default=False,
  246. help='Force failed unit tests to run again next time', dest='clear_failed_tests')
  247. opt.add_option('--testcmd', action='store', default=False, dest='testcmd',
  248. help='Run the unit tests using the test-cmd string example "--testcmd="valgrind --error-exitcode=1 %s" to run under valgrind')
  249. opt.add_option('--dump-test-scripts', action='store_true', default=False,
  250. help='Create python scripts to help debug tests', dest='dump_test_scripts')