TestCmd.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  1. """
  2. TestCmd.py: a testing framework for commands and scripts.
  3. The TestCmd module provides a framework for portable automated testing of
  4. executable commands and scripts (in any language, not just Python), especially
  5. commands and scripts that require file system interaction.
  6. In addition to running tests and evaluating conditions, the TestCmd module
  7. manages and cleans up one or more temporary workspace directories, and provides
  8. methods for creating files and directories in those workspace directories from
  9. in-line data, here-documents), allowing tests to be completely self-contained.
  10. A TestCmd environment object is created via the usual invocation:
  11. test = TestCmd()
  12. The TestCmd module provides pass_test(), fail_test(), and no_result() unbound
  13. methods that report test results for use with the Aegis change management
  14. system. These methods terminate the test immediately, reporting PASSED, FAILED
  15. or NO RESULT respectively and exiting with status 0 (success), 1 or 2
  16. respectively. This allows for a distinction between an actual failed test and a
  17. test that could not be properly evaluated because of an external condition (such
  18. as a full file system or incorrect permissions).
  19. """
  20. # Copyright 2000 Steven Knight
  21. # This module is free software, and you may redistribute it and/or modify
  22. # it under the same terms as Python itself, so long as this copyright message
  23. # and disclaimer are retained in their original form.
  24. #
  25. # IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
  26. # SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
  27. # THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
  28. # DAMAGE.
  29. #
  30. # THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
  31. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  32. # PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
  33. # AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
  34. # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  35. # Copyright 2002-2003 Vladimir Prus.
  36. # Copyright 2002-2003 Dave Abrahams.
  37. # Copyright 2006 Rene Rivera.
  38. # Distributed under the Boost Software License, Version 1.0.
  39. # (See accompanying file LICENSE.txt or copy at
  40. # https://www.bfgroup.xyz/b2/LICENSE.txt)
  41. from __future__ import print_function
  42. __author__ = "Steven Knight <knight@baldmt.com>"
  43. __revision__ = "TestCmd.py 0.D002 2001/08/31 14:56:12 software"
  44. __version__ = "0.02"
  45. from types import *
  46. import os
  47. import os.path
  48. import re
  49. import shutil
  50. import stat
  51. import subprocess
  52. import sys
  53. import tempfile
  54. import traceback
  55. tempfile.template = 'testcmd.'
  56. _Cleanup = []
  57. def _clean():
  58. global _Cleanup
  59. list = _Cleanup[:]
  60. _Cleanup = []
  61. list.reverse()
  62. for test in list:
  63. test.cleanup()
  64. sys.exitfunc = _clean
  65. def caller(tblist, skip):
  66. string = ""
  67. arr = []
  68. for file, line, name, text in tblist:
  69. if file[-10:] == "TestCmd.py":
  70. break
  71. arr = [(file, line, name, text)] + arr
  72. atfrom = "at"
  73. for file, line, name, text in arr[skip:]:
  74. if name == "?":
  75. name = ""
  76. else:
  77. name = " (" + name + ")"
  78. string = string + ("%s line %d of %s%s\n" % (atfrom, line, file, name))
  79. atfrom = "\tfrom"
  80. return string
  81. def fail_test(self=None, condition=True, function=None, skip=0):
  82. """Cause the test to fail.
  83. By default, the fail_test() method reports that the test FAILED and exits
  84. with a status of 1. If a condition argument is supplied, the test fails
  85. only if the condition is true.
  86. """
  87. if not condition:
  88. return
  89. if not function is None:
  90. function()
  91. of = ""
  92. desc = ""
  93. sep = " "
  94. if not self is None:
  95. if self.program:
  96. of = " of " + " ".join(self.program)
  97. sep = "\n\t"
  98. if self.description:
  99. desc = " [" + self.description + "]"
  100. sep = "\n\t"
  101. at = caller(traceback.extract_stack(), skip)
  102. sys.stderr.write("FAILED test" + of + desc + sep + at + """
  103. in directory: """ + os.getcwd() )
  104. sys.exit(1)
  105. def no_result(self=None, condition=True, function=None, skip=0):
  106. """Causes a test to exit with no valid result.
  107. By default, the no_result() method reports NO RESULT for the test and
  108. exits with a status of 2. If a condition argument is supplied, the test
  109. fails only if the condition is true.
  110. """
  111. if not condition:
  112. return
  113. if not function is None:
  114. function()
  115. of = ""
  116. desc = ""
  117. sep = " "
  118. if not self is None:
  119. if self.program:
  120. of = " of " + self.program
  121. sep = "\n\t"
  122. if self.description:
  123. desc = " [" + self.description + "]"
  124. sep = "\n\t"
  125. at = caller(traceback.extract_stack(), skip)
  126. sys.stderr.write("NO RESULT for test" + of + desc + sep + at)
  127. sys.exit(2)
  128. def pass_test(self=None, condition=True, function=None):
  129. """Causes a test to pass.
  130. By default, the pass_test() method reports PASSED for the test and exits
  131. with a status of 0. If a condition argument is supplied, the test passes
  132. only if the condition is true.
  133. """
  134. if not condition:
  135. return
  136. if not function is None:
  137. function()
  138. sys.stderr.write("PASSED\n")
  139. sys.exit(0)
  140. class MatchError(object):
  141. def __init__(self, message):
  142. self.message = message
  143. def __nonzero__(self):
  144. return False
  145. def __bool__(self):
  146. return False
  147. def match_exact(lines=None, matches=None):
  148. """
  149. Returns whether the given lists or strings containing lines separated
  150. using newline characters contain exactly the same data.
  151. """
  152. if not type(lines) is list:
  153. lines = lines.split("\n")
  154. if not type(matches) is list:
  155. matches = matches.split("\n")
  156. if len(lines) != len(matches):
  157. return
  158. for i in range(len(lines)):
  159. if lines[i] != matches[i]:
  160. return MatchError("Mismatch at line %d\n- %s\n+ %s\n" %
  161. (i+1, matches[i], lines[i]))
  162. if len(lines) < len(matches):
  163. return MatchError("Missing lines at line %d\n- %s" %
  164. (len(lines), "\n- ".join(matches[len(lines):])))
  165. if len(lines) > len(matches):
  166. return MatchError("Extra lines at line %d\n+ %s" %
  167. (len(matches), "\n+ ".join(lines[len(matches):])))
  168. return 1
  169. def match_re(lines=None, res=None):
  170. """
  171. Given lists or strings contain lines separated using newline characters.
  172. This function matches those lines one by one, interpreting the lines in the
  173. res parameter as regular expressions.
  174. """
  175. if not type(lines) is list:
  176. lines = lines.split("\n")
  177. if not type(res) is list:
  178. res = res.split("\n")
  179. for i in range(min(len(lines), len(res))):
  180. if not re.compile("^" + res[i] + "$").search(lines[i]):
  181. return MatchError("Mismatch at line %d\n- %s\n+ %s\n" %
  182. (i+1, res[i], lines[i]))
  183. if len(lines) < len(res):
  184. return MatchError("Missing lines at line %d\n- %s" %
  185. (len(lines), "\n- ".join(res[len(lines):])))
  186. if len(lines) > len(res):
  187. return MatchError("Extra lines at line %d\n+ %s" %
  188. (len(res), "\n+ ".join(lines[len(res):])))
  189. return 1
  190. class TestCmd:
  191. def __init__(self, description=None, program=None, workdir=None,
  192. subdir=None, verbose=False, match=None, inpath=None):
  193. self._cwd = os.getcwd()
  194. self.description_set(description)
  195. self.program_set(program, inpath)
  196. self.verbose_set(verbose)
  197. if match is None:
  198. self.match_func = match_re
  199. else:
  200. self.match_func = match
  201. self._dirlist = []
  202. self._preserve = {'pass_test': 0, 'fail_test': 0, 'no_result': 0}
  203. env = os.environ.get('PRESERVE')
  204. if env:
  205. self._preserve['pass_test'] = env
  206. self._preserve['fail_test'] = env
  207. self._preserve['no_result'] = env
  208. else:
  209. env = os.environ.get('PRESERVE_PASS')
  210. if env is not None:
  211. self._preserve['pass_test'] = env
  212. env = os.environ.get('PRESERVE_FAIL')
  213. if env is not None:
  214. self._preserve['fail_test'] = env
  215. env = os.environ.get('PRESERVE_PASS')
  216. if env is not None:
  217. self._preserve['PRESERVE_NO_RESULT'] = env
  218. self._stdout = []
  219. self._stderr = []
  220. self.status = None
  221. self.condition = 'no_result'
  222. self.workdir_set(workdir)
  223. self.subdir(subdir)
  224. def __del__(self):
  225. self.cleanup()
  226. def __repr__(self):
  227. return "%x" % id(self)
  228. def cleanup(self, condition=None):
  229. """
  230. Removes any temporary working directories for the specified TestCmd
  231. environment. If the environment variable PRESERVE was set when the
  232. TestCmd environment was created, temporary working directories are not
  233. removed. If any of the environment variables PRESERVE_PASS,
  234. PRESERVE_FAIL or PRESERVE_NO_RESULT were set when the TestCmd
  235. environment was created, then temporary working directories are not
  236. removed if the test passed, failed or had no result, respectively.
  237. Temporary working directories are also preserved for conditions
  238. specified via the preserve method.
  239. Typically, this method is not called directly, but is used when the
  240. script exits to clean up temporary working directories as appropriate
  241. for the exit status.
  242. """
  243. if not self._dirlist:
  244. return
  245. if condition is None:
  246. condition = self.condition
  247. if self._preserve[condition]:
  248. for dir in self._dirlist:
  249. print("Preserved directory %s" % dir)
  250. else:
  251. list = self._dirlist[:]
  252. list.reverse()
  253. for dir in list:
  254. self.writable(dir, 1)
  255. shutil.rmtree(dir, ignore_errors=1)
  256. self._dirlist = []
  257. self.workdir = None
  258. os.chdir(self._cwd)
  259. try:
  260. global _Cleanup
  261. _Cleanup.remove(self)
  262. except (AttributeError, ValueError):
  263. pass
  264. def description_set(self, description):
  265. """Set the description of the functionality being tested."""
  266. self.description = description
  267. def fail_test(self, condition=True, function=None, skip=0):
  268. """Cause the test to fail."""
  269. if not condition:
  270. return
  271. self.condition = 'fail_test'
  272. fail_test(self = self,
  273. condition = condition,
  274. function = function,
  275. skip = skip)
  276. def match(self, lines, matches):
  277. """Compare actual and expected file contents."""
  278. return self.match_func(lines, matches)
  279. def match_exact(self, lines, matches):
  280. """Compare actual and expected file content exactly."""
  281. return match_exact(lines, matches)
  282. def match_re(self, lines, res):
  283. """Compare file content with a regular expression."""
  284. return match_re(lines, res)
  285. def no_result(self, condition=True, function=None, skip=0):
  286. """Report that the test could not be run."""
  287. if not condition:
  288. return
  289. self.condition = 'no_result'
  290. no_result(self = self,
  291. condition = condition,
  292. function = function,
  293. skip = skip)
  294. def pass_test(self, condition=True, function=None):
  295. """Cause the test to pass."""
  296. if not condition:
  297. return
  298. self.condition = 'pass_test'
  299. pass_test(self, condition, function)
  300. def preserve(self, *conditions):
  301. """
  302. Arrange for the temporary working directories for the specified
  303. TestCmd environment to be preserved for one or more conditions. If no
  304. conditions are specified, arranges for the temporary working
  305. directories to be preserved for all conditions.
  306. """
  307. if conditions == ():
  308. conditions = ('pass_test', 'fail_test', 'no_result')
  309. for cond in conditions:
  310. self._preserve[cond] = 1
  311. def program_set(self, program, inpath):
  312. """Set the executable program or script to be tested."""
  313. if not inpath and program and not os.path.isabs(program[0]):
  314. program[0] = os.path.join(self._cwd, program[0])
  315. self.program = program
  316. def read(self, file, mode='rb'):
  317. """
  318. Reads and returns the contents of the specified file name. The file
  319. name may be a list, in which case the elements are concatenated with
  320. the os.path.join() method. The file is assumed to be under the
  321. temporary working directory unless it is an absolute path name. The I/O
  322. mode for the file may be specified and must begin with an 'r'. The
  323. default is 'rb' (binary read).
  324. """
  325. if type(file) is list:
  326. file = os.path.join(*file)
  327. if not os.path.isabs(file):
  328. file = os.path.join(self.workdir, file)
  329. if mode[0] != 'r':
  330. raise ValueError("mode must begin with 'r'")
  331. return open(file, mode).read()
  332. def run(self, program=None, arguments=None, chdir=None, stdin=None,
  333. universal_newlines=True):
  334. """
  335. Runs a test of the program or script for the test environment.
  336. Standard output and error output are saved for future retrieval via the
  337. stdout() and stderr() methods.
  338. 'universal_newlines' parameter controls how the child process
  339. input/output streams are opened as defined for the same named Python
  340. subprocess.POpen constructor parameter.
  341. """
  342. if chdir:
  343. if not os.path.isabs(chdir):
  344. chdir = os.path.join(self.workpath(chdir))
  345. if self.verbose:
  346. sys.stderr.write("chdir(" + chdir + ")\n")
  347. else:
  348. chdir = self.workdir
  349. cmd = []
  350. if program and program[0]:
  351. if program[0] != self.program[0] and not os.path.isabs(program[0]):
  352. program[0] = os.path.join(self._cwd, program[0])
  353. cmd += program
  354. else:
  355. cmd += self.program
  356. if arguments:
  357. cmd += arguments.split(" ")
  358. if self.verbose:
  359. sys.stderr.write("run(" + " ".join(cmd) + ")\n")
  360. p = subprocess.Popen(cmd, stdin=subprocess.PIPE,
  361. stdout=subprocess.PIPE, stderr=subprocess.PIPE, cwd=chdir,
  362. universal_newlines=universal_newlines)
  363. if stdin:
  364. if type(stdin) is list:
  365. stdin = "".join(stdin)
  366. out, err = p.communicate(stdin)
  367. if not type(out) is str:
  368. out = out.decode()
  369. if not type(err) is str:
  370. err = err.decode()
  371. self._stdout.append(out)
  372. self._stderr.append(err)
  373. self.status = p.returncode
  374. if self.verbose:
  375. sys.stdout.write(self._stdout[-1])
  376. sys.stderr.write(self._stderr[-1])
  377. def stderr(self, run=None):
  378. """
  379. Returns the error output from the specified run number. If there is
  380. no specified run number, then returns the error output of the last run.
  381. If the run number is less than zero, then returns the error output from
  382. that many runs back from the current run.
  383. """
  384. if not run:
  385. run = len(self._stderr)
  386. elif run < 0:
  387. run = len(self._stderr) + run
  388. run -= 1
  389. if run < 0:
  390. return ''
  391. return self._stderr[run]
  392. def stdout(self, run=None):
  393. """
  394. Returns the standard output from the specified run number. If there
  395. is no specified run number, then returns the standard output of the
  396. last run. If the run number is less than zero, then returns the
  397. standard output from that many runs back from the current run.
  398. """
  399. if not run:
  400. run = len(self._stdout)
  401. elif run < 0:
  402. run = len(self._stdout) + run
  403. run -= 1
  404. if run < 0:
  405. return ''
  406. return self._stdout[run]
  407. def subdir(self, *subdirs):
  408. """
  409. Create new subdirectories under the temporary working directory, one
  410. for each argument. An argument may be a list, in which case the list
  411. elements are concatenated using the os.path.join() method.
  412. Subdirectories multiple levels deep must be created using a separate
  413. argument for each level:
  414. test.subdir('sub', ['sub', 'dir'], ['sub', 'dir', 'ectory'])
  415. Returns the number of subdirectories actually created.
  416. """
  417. count = 0
  418. for sub in subdirs:
  419. if sub is None:
  420. continue
  421. if type(sub) is list:
  422. sub = os.path.join(*tuple(sub))
  423. new = os.path.join(self.workdir, sub)
  424. try:
  425. os.mkdir(new)
  426. except:
  427. pass
  428. else:
  429. count += 1
  430. return count
  431. def unlink(self, file):
  432. """
  433. Unlinks the specified file name. The file name may be a list, in
  434. which case the elements are concatenated using the os.path.join()
  435. method. The file is assumed to be under the temporary working directory
  436. unless it is an absolute path name.
  437. """
  438. if type(file) is list:
  439. file = os.path.join(*tuple(file))
  440. if not os.path.isabs(file):
  441. file = os.path.join(self.workdir, file)
  442. os.unlink(file)
  443. def verbose_set(self, verbose):
  444. """Set the verbose level."""
  445. self.verbose = verbose
  446. def workdir_set(self, path):
  447. """
  448. Creates a temporary working directory with the specified path name.
  449. If the path is a null string (''), a unique directory name is created.
  450. """
  451. if os.path.isabs(path):
  452. self.workdir = path
  453. else:
  454. if path != None:
  455. if path == '':
  456. path = tempfile.mktemp()
  457. if path != None:
  458. os.mkdir(path)
  459. self._dirlist.append(path)
  460. global _Cleanup
  461. try:
  462. _Cleanup.index(self)
  463. except ValueError:
  464. _Cleanup.append(self)
  465. # We would like to set self.workdir like this:
  466. # self.workdir = path
  467. # But symlinks in the path will report things differently from
  468. # os.getcwd(), so chdir there and back to fetch the canonical
  469. # path.
  470. cwd = os.getcwd()
  471. os.chdir(path)
  472. self.workdir = os.getcwd()
  473. os.chdir(cwd)
  474. else:
  475. self.workdir = None
  476. def workpath(self, *args):
  477. """
  478. Returns the absolute path name to a subdirectory or file within the
  479. current temporary working directory. Concatenates the temporary working
  480. directory name with the specified arguments using os.path.join().
  481. """
  482. return os.path.join(self.workdir, *tuple(args))
  483. def writable(self, top, write):
  484. """
  485. Make the specified directory tree writable (write == 1) or not
  486. (write == None).
  487. """
  488. def _walk_chmod(arg, dirname, names):
  489. st = os.stat(dirname)
  490. os.chmod(dirname, arg(st[stat.ST_MODE]))
  491. for name in names:
  492. fullname = os.path.join(dirname, name)
  493. st = os.stat(fullname)
  494. os.chmod(fullname, arg(st[stat.ST_MODE]))
  495. _mode_writable = lambda mode: stat.S_IMODE(mode|0o200)
  496. _mode_non_writable = lambda mode: stat.S_IMODE(mode&~0o200)
  497. if write:
  498. f = _mode_writable
  499. else:
  500. f = _mode_non_writable
  501. try:
  502. for root, _, files in os.walk(top):
  503. _walk_chmod(f, root, files)
  504. except:
  505. pass # Ignore any problems changing modes.
  506. def write(self, file, content, mode='wb'):
  507. """
  508. Writes the specified content text (second argument) to the specified
  509. file name (first argument). The file name may be a list, in which case
  510. the elements are concatenated using the os.path.join() method. The file
  511. is created under the temporary working directory. Any subdirectories in
  512. the path must already exist. The I/O mode for the file may be specified
  513. and must begin with a 'w'. The default is 'wb' (binary write).
  514. """
  515. if type(file) is list:
  516. file = os.path.join(*tuple(file))
  517. if not os.path.isabs(file):
  518. file = os.path.join(self.workdir, file)
  519. if mode[0] != 'w':
  520. raise ValueError("mode must begin with 'w'")
  521. open(file, mode).write(content)