waf_unit_test.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320
  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. self.env.append_value('UT_DEPS', ['%r%r' % (key, self.ut_env[key]) for key in self.ut_env])
  84. @feature('test')
  85. @after_method('apply_link', 'process_use')
  86. def make_test(self):
  87. """Create the unit test task. There can be only one unit test task by task generator."""
  88. if not getattr(self, 'link_task', None):
  89. return
  90. tsk = self.create_task('utest', self.link_task.outputs)
  91. if getattr(self, 'ut_str', None):
  92. self.ut_run, lst = Task.compile_fun(self.ut_str, shell=getattr(self, 'ut_shell', False))
  93. tsk.vars = tsk.vars + lst
  94. self.env.append_value('UT_DEPS', self.ut_str)
  95. self.handle_ut_cwd('ut_cwd')
  96. if not hasattr(self, 'ut_paths'):
  97. paths = []
  98. for x in self.tmp_use_sorted:
  99. try:
  100. y = self.bld.get_tgen_by_name(x).link_task
  101. except AttributeError:
  102. pass
  103. else:
  104. if not isinstance(y, ccroot.stlink_task):
  105. paths.append(y.outputs[0].parent.abspath())
  106. self.ut_paths = os.pathsep.join(paths) + os.pathsep
  107. if not hasattr(self, 'ut_env'):
  108. self.ut_env = dct = dict(os.environ)
  109. def add_path(var):
  110. dct[var] = self.ut_paths + dct.get(var,'')
  111. if Utils.is_win32:
  112. add_path('PATH')
  113. elif Utils.unversioned_sys_platform() == 'darwin':
  114. add_path('DYLD_LIBRARY_PATH')
  115. add_path('LD_LIBRARY_PATH')
  116. else:
  117. add_path('LD_LIBRARY_PATH')
  118. if not hasattr(self, 'ut_cmd'):
  119. self.ut_cmd = getattr(Options.options, 'testcmd', False)
  120. self.env.append_value('UT_DEPS', str(self.ut_cmd))
  121. self.env.append_value('UT_DEPS', self.ut_paths)
  122. self.env.append_value('UT_DEPS', ['%r%r' % (key, self.ut_env[key]) for key in self.ut_env])
  123. @taskgen_method
  124. def add_test_results(self, tup):
  125. """Override and return tup[1] to interrupt the build immediately if a test does not run"""
  126. Logs.debug("ut: %r", tup)
  127. try:
  128. self.utest_results.append(tup)
  129. except AttributeError:
  130. self.utest_results = [tup]
  131. try:
  132. self.bld.utest_results.append(tup)
  133. except AttributeError:
  134. self.bld.utest_results = [tup]
  135. class test_result(object):
  136. def __init__(self, test_path, exit_code, out, err, task):
  137. self.task = task
  138. self.generator = task.generator
  139. self.out = out
  140. self.err = err
  141. self.exit_code = exit_code
  142. self.test_path = test_path
  143. def __iter__(self):
  144. yield self.test_path
  145. yield self.exit_code
  146. yield self.out
  147. yield self.err
  148. def __getitem__(self, idx):
  149. return list(self)[idx]
  150. @Task.deep_inputs
  151. class utest(Task.Task):
  152. """
  153. Execute a unit test
  154. """
  155. color = 'PINK'
  156. after = ['vnum', 'inst']
  157. vars = ['UT_DEPS']
  158. def runnable_status(self):
  159. """
  160. Always execute the task if `waf --alltests` was used or no
  161. tests if ``waf --notests`` was used
  162. """
  163. if getattr(Options.options, 'no_tests', False):
  164. return Task.SKIP_ME
  165. ret = super(utest, self).runnable_status()
  166. if ret == Task.SKIP_ME:
  167. if getattr(Options.options, 'all_tests', False):
  168. return Task.RUN_ME
  169. return ret
  170. def get_test_env(self):
  171. """
  172. In general, tests may require any library built anywhere in the project.
  173. Override this method if fewer paths are needed
  174. """
  175. return self.generator.ut_env
  176. def post_run(self):
  177. super(utest, self).post_run()
  178. if getattr(Options.options, 'clear_failed_tests', False) and self.waf_unit_test_results[1]:
  179. self.generator.bld.task_sigs[self.uid()] = None
  180. def run(self):
  181. """
  182. Execute the test. The execution is always successful, and the results
  183. are stored on ``self.generator.bld.utest_results`` for postprocessing.
  184. Override ``add_test_results`` to interrupt the build
  185. """
  186. if hasattr(self.generator, 'ut_run'):
  187. return self.generator.ut_run(self)
  188. self.ut_exec = getattr(self.generator, 'ut_exec', [self.inputs[0].abspath()])
  189. ut_cmd = getattr(self.generator, 'ut_cmd', False)
  190. if ut_cmd:
  191. self.ut_exec = shlex.split(ut_cmd % Utils.shell_escape(self.ut_exec))
  192. return self.exec_command(self.ut_exec)
  193. def exec_command(self, cmd, **kw):
  194. self.generator.bld.log_command(cmd, kw)
  195. if getattr(Options.options, 'dump_test_scripts', False):
  196. script_code = SCRIPT_TEMPLATE % {
  197. 'python': sys.executable,
  198. 'env': self.get_test_env(),
  199. 'cwd': self.get_cwd().abspath(),
  200. 'cmd': cmd
  201. }
  202. script_file = self.inputs[0].abspath() + '_run.py'
  203. Utils.writef(script_file, script_code, encoding='utf-8')
  204. os.chmod(script_file, Utils.O755)
  205. if Logs.verbose > 1:
  206. Logs.info('Test debug file written as %r' % script_file)
  207. proc = Utils.subprocess.Popen(cmd, cwd=self.get_cwd().abspath(), env=self.get_test_env(),
  208. stderr=Utils.subprocess.PIPE, stdout=Utils.subprocess.PIPE, shell=isinstance(cmd,str))
  209. (stdout, stderr) = proc.communicate()
  210. self.waf_unit_test_results = tup = test_result(self.inputs[0].abspath(), proc.returncode, stdout, stderr, self)
  211. testlock.acquire()
  212. try:
  213. return self.generator.add_test_results(tup)
  214. finally:
  215. testlock.release()
  216. def get_cwd(self):
  217. return getattr(self.generator, 'ut_cwd', self.inputs[0].parent)
  218. def summary(bld):
  219. """
  220. Display an execution summary::
  221. def build(bld):
  222. bld(features='cxx cxxprogram test', source='main.c', target='app')
  223. from waflib.Tools import waf_unit_test
  224. bld.add_post_fun(waf_unit_test.summary)
  225. """
  226. lst = getattr(bld, 'utest_results', [])
  227. if lst:
  228. Logs.pprint('CYAN', 'execution summary')
  229. total = len(lst)
  230. tfail = len([x for x in lst if x[1]])
  231. Logs.pprint('GREEN', ' tests that pass %d/%d' % (total-tfail, total))
  232. for result in lst:
  233. if not result.exit_code:
  234. Logs.pprint('GREEN', ' %s' % result.test_path)
  235. Logs.pprint('GREEN' if tfail == 0 else 'RED', ' tests that fail %d/%d' % (tfail, total))
  236. for result in lst:
  237. if result.exit_code:
  238. Logs.pprint('RED', ' %s' % result.test_path)
  239. def set_exit_code(bld):
  240. """
  241. If any of the tests fail waf will exit with that exit code.
  242. This is useful if you have an automated build system which need
  243. to report on errors from the tests.
  244. You may use it like this:
  245. def build(bld):
  246. bld(features='cxx cxxprogram test', source='main.c', target='app')
  247. from waflib.Tools import waf_unit_test
  248. bld.add_post_fun(waf_unit_test.set_exit_code)
  249. """
  250. lst = getattr(bld, 'utest_results', [])
  251. for result in lst:
  252. if result.exit_code:
  253. msg = []
  254. if result.out:
  255. msg.append('stdout:%s%s' % (os.linesep, result.out.decode('utf-8')))
  256. if result.err:
  257. msg.append('stderr:%s%s' % (os.linesep, result.err.decode('utf-8')))
  258. bld.fatal(os.linesep.join(msg))
  259. def options(opt):
  260. """
  261. Provide the ``--alltests``, ``--notests`` and ``--testcmd`` command-line options.
  262. """
  263. opt.add_option('--notests', action='store_true', default=False, help='Exec no unit tests', dest='no_tests')
  264. opt.add_option('--alltests', action='store_true', default=False, help='Exec all unit tests', dest='all_tests')
  265. opt.add_option('--clear-failed', action='store_true', default=False,
  266. help='Force failed unit tests to run again next time', dest='clear_failed_tests')
  267. opt.add_option('--testcmd', action='store', default=False, dest='testcmd',
  268. help='Run the unit tests using the test-cmd string example "--testcmd="valgrind --error-exitcode=1 %s" to run under valgrind')
  269. opt.add_option('--dump-test-scripts', action='store_true', default=False,
  270. help='Create python scripts to help debug tests', dest='dump_test_scripts')