TestCommon.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570
  1. """
  2. TestCommon.py: a testing framework for commands and scripts
  3. with commonly useful error handling
  4. The TestCommon module provides a simple, high-level interface for writing
  5. tests of executable commands and scripts, especially commands and scripts
  6. that interact with the file system. All methods throw exceptions and
  7. exit on failure, with useful error messages. This makes a number of
  8. explicit checks unnecessary, making the test scripts themselves simpler
  9. to write and easier to read.
  10. The TestCommon class is a subclass of the TestCmd class. In essence,
  11. TestCommon is a wrapper that handles common TestCmd error conditions in
  12. useful ways. You can use TestCommon directly, or subclass it for your
  13. program and add additional (or override) methods to tailor it to your
  14. program's specific needs. Alternatively, the TestCommon class serves
  15. as a useful example of how to define your own TestCmd subclass.
  16. As a subclass of TestCmd, TestCommon provides access to all of the
  17. variables and methods from the TestCmd module. Consequently, you can
  18. use any variable or method documented in the TestCmd module without
  19. having to explicitly import TestCmd.
  20. A TestCommon environment object is created via the usual invocation:
  21. import TestCommon
  22. test = TestCommon.TestCommon()
  23. You can use all of the TestCmd keyword arguments when instantiating a
  24. TestCommon object; see the TestCmd documentation for details.
  25. Here is an overview of the methods and keyword arguments that are
  26. provided by the TestCommon class:
  27. test.must_be_writable('file1', ['file2', ...])
  28. test.must_contain('file', 'required text\n')
  29. test.must_contain_all_lines(output, lines, ['title', find])
  30. test.must_contain_any_line(output, lines, ['title', find])
  31. test.must_exist('file1', ['file2', ...])
  32. test.must_match('file', "expected contents\n")
  33. test.must_not_be_writable('file1', ['file2', ...])
  34. test.must_not_contain('file', 'banned text\n')
  35. test.must_not_contain_any_line(output, lines, ['title', find])
  36. test.must_not_exist('file1', ['file2', ...])
  37. test.run(options = "options to be prepended to arguments",
  38. stdout = "expected standard output from the program",
  39. stderr = "expected error output from the program",
  40. status = expected_status,
  41. match = match_function)
  42. The TestCommon module also provides the following variables
  43. TestCommon.python_executable
  44. TestCommon.exe_suffix
  45. TestCommon.obj_suffix
  46. TestCommon.shobj_prefix
  47. TestCommon.shobj_suffix
  48. TestCommon.lib_prefix
  49. TestCommon.lib_suffix
  50. TestCommon.dll_prefix
  51. TestCommon.dll_suffix
  52. """
  53. # Copyright 2000-2010 Steven Knight
  54. # This module is free software, and you may redistribute it and/or modify
  55. # it under the same terms as Python itself, so long as this copyright message
  56. # and disclaimer are retained in their original form.
  57. #
  58. # IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
  59. # SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
  60. # THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
  61. # DAMAGE.
  62. #
  63. # THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
  64. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  65. # PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
  66. # AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
  67. # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  68. __author__ = "Steven Knight <knight at baldmt dot com>"
  69. __revision__ = "TestCommon.py 0.37.D001 2010/01/11 16:55:50 knight"
  70. __version__ = "0.37"
  71. import copy
  72. import os
  73. import os.path
  74. import stat
  75. import string
  76. import sys
  77. import types
  78. import UserList
  79. from TestCmd import *
  80. from TestCmd import __all__
  81. __all__.extend([ 'TestCommon',
  82. 'exe_suffix',
  83. 'obj_suffix',
  84. 'shobj_prefix',
  85. 'shobj_suffix',
  86. 'lib_prefix',
  87. 'lib_suffix',
  88. 'dll_prefix',
  89. 'dll_suffix',
  90. ])
  91. # Variables that describe the prefixes and suffixes on this system.
  92. if sys.platform == 'win32':
  93. exe_suffix = '.exe'
  94. obj_suffix = '.obj'
  95. shobj_suffix = '.obj'
  96. shobj_prefix = ''
  97. lib_prefix = ''
  98. lib_suffix = '.lib'
  99. dll_prefix = ''
  100. dll_suffix = '.dll'
  101. elif sys.platform == 'cygwin':
  102. exe_suffix = '.exe'
  103. obj_suffix = '.o'
  104. shobj_suffix = '.os'
  105. shobj_prefix = ''
  106. lib_prefix = 'lib'
  107. lib_suffix = '.a'
  108. dll_prefix = ''
  109. dll_suffix = '.dll'
  110. elif string.find(sys.platform, 'irix') != -1:
  111. exe_suffix = ''
  112. obj_suffix = '.o'
  113. shobj_suffix = '.o'
  114. shobj_prefix = ''
  115. lib_prefix = 'lib'
  116. lib_suffix = '.a'
  117. dll_prefix = 'lib'
  118. dll_suffix = '.so'
  119. elif string.find(sys.platform, 'darwin') != -1:
  120. exe_suffix = ''
  121. obj_suffix = '.o'
  122. shobj_suffix = '.os'
  123. shobj_prefix = ''
  124. lib_prefix = 'lib'
  125. lib_suffix = '.a'
  126. dll_prefix = 'lib'
  127. dll_suffix = '.dylib'
  128. elif string.find(sys.platform, 'sunos') != -1:
  129. exe_suffix = ''
  130. obj_suffix = '.o'
  131. shobj_suffix = '.os'
  132. shobj_prefix = 'so_'
  133. lib_prefix = 'lib'
  134. lib_suffix = '.a'
  135. dll_prefix = 'lib'
  136. dll_suffix = '.dylib'
  137. else:
  138. exe_suffix = ''
  139. obj_suffix = '.o'
  140. shobj_suffix = '.os'
  141. shobj_prefix = ''
  142. lib_prefix = 'lib'
  143. lib_suffix = '.a'
  144. dll_prefix = 'lib'
  145. dll_suffix = '.so'
  146. def is_List(e):
  147. return type(e) is types.ListType \
  148. or isinstance(e, UserList.UserList)
  149. def is_writable(f):
  150. mode = os.stat(f)[stat.ST_MODE]
  151. return mode & stat.S_IWUSR
  152. def separate_files(flist):
  153. existing = []
  154. missing = []
  155. for f in flist:
  156. if os.path.exists(f):
  157. existing.append(f)
  158. else:
  159. missing.append(f)
  160. return existing, missing
  161. def _failed(self, status = 0):
  162. if self.status is None or status is None:
  163. return None
  164. try:
  165. return _status(self) not in status
  166. except TypeError:
  167. # status wasn't an iterable
  168. return _status(self) != status
  169. def _status(self):
  170. return self.status
  171. class TestCommon(TestCmd):
  172. # Additional methods from the Perl Test::Cmd::Common module
  173. # that we may wish to add in the future:
  174. #
  175. # $test->subdir('subdir', ...);
  176. #
  177. # $test->copy('src_file', 'dst_file');
  178. def __init__(self, **kw):
  179. """Initialize a new TestCommon instance. This involves just
  180. calling the base class initialization, and then changing directory
  181. to the workdir.
  182. """
  183. apply(TestCmd.__init__, [self], kw)
  184. os.chdir(self.workdir)
  185. def must_be_writable(self, *files):
  186. """Ensures that the specified file(s) exist and are writable.
  187. An individual file can be specified as a list of directory names,
  188. in which case the pathname will be constructed by concatenating
  189. them. Exits FAILED if any of the files does not exist or is
  190. not writable.
  191. """
  192. files = map(lambda x: is_List(x) and apply(os.path.join, x) or x, files)
  193. existing, missing = separate_files(files)
  194. unwritable = filter(lambda x, iw=is_writable: not iw(x), existing)
  195. if missing:
  196. print "Missing files: `%s'" % string.join(missing, "', `")
  197. if unwritable:
  198. print "Unwritable files: `%s'" % string.join(unwritable, "', `")
  199. self.fail_test(missing + unwritable)
  200. def must_contain(self, file, required, mode = 'rb'):
  201. """Ensures that the specified file contains the required text.
  202. """
  203. file_contents = self.read(file, mode)
  204. contains = (string.find(file_contents, required) != -1)
  205. if not contains:
  206. print "File `%s' does not contain required string." % file
  207. print self.banner('Required string ')
  208. print required
  209. print self.banner('%s contents ' % file)
  210. print file_contents
  211. self.fail_test(not contains)
  212. def must_contain_all_lines(self, output, lines, title=None, find=None):
  213. """Ensures that the specified output string (first argument)
  214. contains all of the specified lines (second argument).
  215. An optional third argument can be used to describe the type
  216. of output being searched, and only shows up in failure output.
  217. An optional fourth argument can be used to supply a different
  218. function, of the form "find(line, output), to use when searching
  219. for lines in the output.
  220. """
  221. if find is None:
  222. find = lambda o, l: string.find(o, l) != -1
  223. missing = []
  224. for line in lines:
  225. if not find(output, line):
  226. missing.append(line)
  227. if missing:
  228. if title is None:
  229. title = 'output'
  230. sys.stdout.write("Missing expected lines from %s:\n" % title)
  231. for line in missing:
  232. sys.stdout.write(' ' + repr(line) + '\n')
  233. sys.stdout.write(self.banner(title + ' '))
  234. sys.stdout.write(output)
  235. self.fail_test()
  236. def must_contain_any_line(self, output, lines, title=None, find=None):
  237. """Ensures that the specified output string (first argument)
  238. contains at least one of the specified lines (second argument).
  239. An optional third argument can be used to describe the type
  240. of output being searched, and only shows up in failure output.
  241. An optional fourth argument can be used to supply a different
  242. function, of the form "find(line, output), to use when searching
  243. for lines in the output.
  244. """
  245. if find is None:
  246. find = lambda o, l: string.find(o, l) != -1
  247. for line in lines:
  248. if find(output, line):
  249. return
  250. if title is None:
  251. title = 'output'
  252. sys.stdout.write("Missing any expected line from %s:\n" % title)
  253. for line in lines:
  254. sys.stdout.write(' ' + repr(line) + '\n')
  255. sys.stdout.write(self.banner(title + ' '))
  256. sys.stdout.write(output)
  257. self.fail_test()
  258. def must_contain_lines(self, lines, output, title=None):
  259. # Deprecated; retain for backwards compatibility.
  260. return self.must_contain_all_lines(output, lines, title)
  261. def must_exist(self, *files):
  262. """Ensures that the specified file(s) must exist. An individual
  263. file be specified as a list of directory names, in which case the
  264. pathname will be constructed by concatenating them. Exits FAILED
  265. if any of the files does not exist.
  266. """
  267. files = map(lambda x: is_List(x) and apply(os.path.join, x) or x, files)
  268. missing = filter(lambda x: not os.path.exists(x), files)
  269. if missing:
  270. print "Missing files: `%s'" % string.join(missing, "', `")
  271. self.fail_test(missing)
  272. def must_match(self, file, expect, mode = 'rb'):
  273. """Matches the contents of the specified file (first argument)
  274. against the expected contents (second argument). The expected
  275. contents are a list of lines or a string which will be split
  276. on newlines.
  277. """
  278. file_contents = self.read(file, mode)
  279. try:
  280. self.fail_test(not self.match(file_contents, expect))
  281. except KeyboardInterrupt:
  282. raise
  283. except:
  284. print "Unexpected contents of `%s'" % file
  285. self.diff(expect, file_contents, 'contents ')
  286. raise
  287. def must_not_contain(self, file, banned, mode = 'rb'):
  288. """Ensures that the specified file doesn't contain the banned text.
  289. """
  290. file_contents = self.read(file, mode)
  291. contains = (string.find(file_contents, banned) != -1)
  292. if contains:
  293. print "File `%s' contains banned string." % file
  294. print self.banner('Banned string ')
  295. print banned
  296. print self.banner('%s contents ' % file)
  297. print file_contents
  298. self.fail_test(contains)
  299. def must_not_contain_any_line(self, output, lines, title=None, find=None):
  300. """Ensures that the specified output string (first argument)
  301. does not contain any of the specified lines (second argument).
  302. An optional third argument can be used to describe the type
  303. of output being searched, and only shows up in failure output.
  304. An optional fourth argument can be used to supply a different
  305. function, of the form "find(line, output), to use when searching
  306. for lines in the output.
  307. """
  308. if find is None:
  309. find = lambda o, l: string.find(o, l) != -1
  310. unexpected = []
  311. for line in lines:
  312. if find(output, line):
  313. unexpected.append(line)
  314. if unexpected:
  315. if title is None:
  316. title = 'output'
  317. sys.stdout.write("Unexpected lines in %s:\n" % title)
  318. for line in unexpected:
  319. sys.stdout.write(' ' + repr(line) + '\n')
  320. sys.stdout.write(self.banner(title + ' '))
  321. sys.stdout.write(output)
  322. self.fail_test()
  323. def must_not_contain_lines(self, lines, output, title=None):
  324. return self.must_not_contain_any_line(output, lines, title)
  325. def must_not_exist(self, *files):
  326. """Ensures that the specified file(s) must not exist.
  327. An individual file be specified as a list of directory names, in
  328. which case the pathname will be constructed by concatenating them.
  329. Exits FAILED if any of the files exists.
  330. """
  331. files = map(lambda x: is_List(x) and apply(os.path.join, x) or x, files)
  332. existing = filter(os.path.exists, files)
  333. if existing:
  334. print "Unexpected files exist: `%s'" % string.join(existing, "', `")
  335. self.fail_test(existing)
  336. def must_not_be_writable(self, *files):
  337. """Ensures that the specified file(s) exist and are not writable.
  338. An individual file can be specified as a list of directory names,
  339. in which case the pathname will be constructed by concatenating
  340. them. Exits FAILED if any of the files does not exist or is
  341. writable.
  342. """
  343. files = map(lambda x: is_List(x) and apply(os.path.join, x) or x, files)
  344. existing, missing = separate_files(files)
  345. writable = filter(is_writable, existing)
  346. if missing:
  347. print "Missing files: `%s'" % string.join(missing, "', `")
  348. if writable:
  349. print "Writable files: `%s'" % string.join(writable, "', `")
  350. self.fail_test(missing + writable)
  351. def _complete(self, actual_stdout, expected_stdout,
  352. actual_stderr, expected_stderr, status, match):
  353. """
  354. Post-processes running a subcommand, checking for failure
  355. status and displaying output appropriately.
  356. """
  357. if _failed(self, status):
  358. expect = ''
  359. if status != 0:
  360. expect = " (expected %s)" % str(status)
  361. print "%s returned %s%s" % (self.program, str(_status(self)), expect)
  362. print self.banner('STDOUT ')
  363. print actual_stdout
  364. print self.banner('STDERR ')
  365. print actual_stderr
  366. self.fail_test()
  367. if not expected_stdout is None and not match(actual_stdout, expected_stdout):
  368. self.diff(expected_stdout, actual_stdout, 'STDOUT ')
  369. if actual_stderr:
  370. print self.banner('STDERR ')
  371. print actual_stderr
  372. self.fail_test()
  373. if not expected_stderr is None and not match(actual_stderr, expected_stderr):
  374. print self.banner('STDOUT ')
  375. print actual_stdout
  376. self.diff(expected_stderr, actual_stderr, 'STDERR ')
  377. self.fail_test()
  378. def start(self, program = None,
  379. interpreter = None,
  380. arguments = None,
  381. universal_newlines = None,
  382. **kw):
  383. """
  384. Starts a program or script for the test environment.
  385. This handles the "options" keyword argument and exceptions.
  386. """
  387. options = kw.pop('options', None)
  388. if options:
  389. if arguments is None:
  390. arguments = options
  391. else:
  392. arguments = options + " " + arguments
  393. try:
  394. return apply(TestCmd.start,
  395. (self, program, interpreter, arguments, universal_newlines),
  396. kw)
  397. except KeyboardInterrupt:
  398. raise
  399. except Exception, e:
  400. print self.banner('STDOUT ')
  401. try:
  402. print self.stdout()
  403. except IndexError:
  404. pass
  405. print self.banner('STDERR ')
  406. try:
  407. print self.stderr()
  408. except IndexError:
  409. pass
  410. cmd_args = self.command_args(program, interpreter, arguments)
  411. sys.stderr.write('Exception trying to execute: %s\n' % cmd_args)
  412. raise e
  413. def finish(self, popen, stdout = None, stderr = '', status = 0, **kw):
  414. """
  415. Finishes and waits for the process being run under control of
  416. the specified popen argument. Additional arguments are similar
  417. to those of the run() method:
  418. stdout The expected standard output from
  419. the command. A value of None means
  420. don't test standard output.
  421. stderr The expected error output from
  422. the command. A value of None means
  423. don't test error output.
  424. status The expected exit status from the
  425. command. A value of None means don't
  426. test exit status.
  427. """
  428. apply(TestCmd.finish, (self, popen,), kw)
  429. match = kw.get('match', self.match)
  430. self._complete(self.stdout(), stdout,
  431. self.stderr(), stderr, status, match)
  432. def run(self, options = None, arguments = None,
  433. stdout = None, stderr = '', status = 0, **kw):
  434. """Runs the program under test, checking that the test succeeded.
  435. The arguments are the same as the base TestCmd.run() method,
  436. with the addition of:
  437. options Extra options that get appended to the beginning
  438. of the arguments.
  439. stdout The expected standard output from
  440. the command. A value of None means
  441. don't test standard output.
  442. stderr The expected error output from
  443. the command. A value of None means
  444. don't test error output.
  445. status The expected exit status from the
  446. command. A value of None means don't
  447. test exit status.
  448. By default, this expects a successful exit (status = 0), does
  449. not test standard output (stdout = None), and expects that error
  450. output is empty (stderr = "").
  451. """
  452. if options:
  453. if arguments is None:
  454. arguments = options
  455. else:
  456. arguments = options + " " + arguments
  457. kw['arguments'] = arguments
  458. match = kw.pop('match', self.match)
  459. apply(TestCmd.run, [self], kw)
  460. self._complete(self.stdout(), stdout,
  461. self.stderr(), stderr, status, match)
  462. def skip_test(self, message="Skipping test.\n"):
  463. """Skips a test.
  464. Proper test-skipping behavior is dependent on the external
  465. TESTCOMMON_PASS_SKIPS environment variable. If set, we treat
  466. the skip as a PASS (exit 0), and otherwise treat it as NO RESULT.
  467. In either case, we print the specified message as an indication
  468. that the substance of the test was skipped.
  469. (This was originally added to support development under Aegis.
  470. Technically, skipping a test is a NO RESULT, but Aegis would
  471. treat that as a test failure and prevent the change from going to
  472. the next step. Since we ddn't want to force anyone using Aegis
  473. to have to install absolutely every tool used by the tests, we
  474. would actually report to Aegis that a skipped test has PASSED
  475. so that the workflow isn't held up.)
  476. """
  477. if message:
  478. sys.stdout.write(message)
  479. sys.stdout.flush()
  480. pass_skips = os.environ.get('TESTCOMMON_PASS_SKIPS')
  481. if pass_skips in [None, 0, '0']:
  482. # skip=1 means skip this function when showing where this
  483. # result came from. They only care about the line where the
  484. # script called test.skip_test(), not the line number where
  485. # we call test.no_result().
  486. self.no_result(skip=1)
  487. else:
  488. # We're under the development directory for this change,
  489. # so this is an Aegis invocation; pass the test (exit 0).
  490. self.pass_test()
  491. # Local Variables:
  492. # tab-width:4
  493. # indent-tabs-mode:nil
  494. # End:
  495. # vim: set expandtab tabstop=4 shiftwidth=4: