TestCmd.py 51 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597
  1. """
  2. TestCmd.py: a testing framework for commands and scripts.
  3. The TestCmd module provides a framework for portable automated testing
  4. of executable commands and scripts (in any language, not just Python),
  5. especially commands and scripts that require file system interaction.
  6. In addition to running tests and evaluating conditions, the TestCmd
  7. module manages and cleans up one or more temporary workspace
  8. directories, and provides methods for creating files and directories in
  9. those workspace directories from in-line data, here-documents), allowing
  10. tests to be completely self-contained.
  11. A TestCmd environment object is created via the usual invocation:
  12. import TestCmd
  13. test = TestCmd.TestCmd()
  14. There are a bunch of keyword arguments available at instantiation:
  15. test = TestCmd.TestCmd(description = 'string',
  16. program = 'program_or_script_to_test',
  17. interpreter = 'script_interpreter',
  18. workdir = 'prefix',
  19. subdir = 'subdir',
  20. verbose = Boolean,
  21. match = default_match_function,
  22. diff = default_diff_function,
  23. combine = Boolean)
  24. There are a bunch of methods that let you do different things:
  25. test.verbose_set(1)
  26. test.description_set('string')
  27. test.program_set('program_or_script_to_test')
  28. test.interpreter_set('script_interpreter')
  29. test.interpreter_set(['script_interpreter', 'arg'])
  30. test.workdir_set('prefix')
  31. test.workdir_set('')
  32. test.workpath('file')
  33. test.workpath('subdir', 'file')
  34. test.subdir('subdir', ...)
  35. test.rmdir('subdir', ...)
  36. test.write('file', "contents\n")
  37. test.write(['subdir', 'file'], "contents\n")
  38. test.read('file')
  39. test.read(['subdir', 'file'])
  40. test.read('file', mode)
  41. test.read(['subdir', 'file'], mode)
  42. test.writable('dir', 1)
  43. test.writable('dir', None)
  44. test.preserve(condition, ...)
  45. test.cleanup(condition)
  46. test.command_args(program = 'program_or_script_to_run',
  47. interpreter = 'script_interpreter',
  48. arguments = 'arguments to pass to program')
  49. test.run(program = 'program_or_script_to_run',
  50. interpreter = 'script_interpreter',
  51. arguments = 'arguments to pass to program',
  52. chdir = 'directory_to_chdir_to',
  53. stdin = 'input to feed to the program\n')
  54. universal_newlines = True)
  55. p = test.start(program = 'program_or_script_to_run',
  56. interpreter = 'script_interpreter',
  57. arguments = 'arguments to pass to program',
  58. universal_newlines = None)
  59. test.finish(self, p)
  60. test.pass_test()
  61. test.pass_test(condition)
  62. test.pass_test(condition, function)
  63. test.fail_test()
  64. test.fail_test(condition)
  65. test.fail_test(condition, function)
  66. test.fail_test(condition, function, skip)
  67. test.no_result()
  68. test.no_result(condition)
  69. test.no_result(condition, function)
  70. test.no_result(condition, function, skip)
  71. test.stdout()
  72. test.stdout(run)
  73. test.stderr()
  74. test.stderr(run)
  75. test.symlink(target, link)
  76. test.banner(string)
  77. test.banner(string, width)
  78. test.diff(actual, expected)
  79. test.match(actual, expected)
  80. test.match_exact("actual 1\nactual 2\n", "expected 1\nexpected 2\n")
  81. test.match_exact(["actual 1\n", "actual 2\n"],
  82. ["expected 1\n", "expected 2\n"])
  83. test.match_re("actual 1\nactual 2\n", regex_string)
  84. test.match_re(["actual 1\n", "actual 2\n"], list_of_regexes)
  85. test.match_re_dotall("actual 1\nactual 2\n", regex_string)
  86. test.match_re_dotall(["actual 1\n", "actual 2\n"], list_of_regexes)
  87. test.tempdir()
  88. test.tempdir('temporary-directory')
  89. test.sleep()
  90. test.sleep(seconds)
  91. test.where_is('foo')
  92. test.where_is('foo', 'PATH1:PATH2')
  93. test.where_is('foo', 'PATH1;PATH2', '.suffix3;.suffix4')
  94. test.unlink('file')
  95. test.unlink('subdir', 'file')
  96. The TestCmd module provides pass_test(), fail_test(), and no_result()
  97. unbound functions that report test results for use with the Aegis change
  98. management system. These methods terminate the test immediately,
  99. reporting PASSED, FAILED, or NO RESULT respectively, and exiting with
  100. status 0 (success), 1 or 2 respectively. This allows for a distinction
  101. between an actual failed test and a test that could not be properly
  102. evaluated because of an external condition (such as a full file system
  103. or incorrect permissions).
  104. import TestCmd
  105. TestCmd.pass_test()
  106. TestCmd.pass_test(condition)
  107. TestCmd.pass_test(condition, function)
  108. TestCmd.fail_test()
  109. TestCmd.fail_test(condition)
  110. TestCmd.fail_test(condition, function)
  111. TestCmd.fail_test(condition, function, skip)
  112. TestCmd.no_result()
  113. TestCmd.no_result(condition)
  114. TestCmd.no_result(condition, function)
  115. TestCmd.no_result(condition, function, skip)
  116. The TestCmd module also provides unbound functions that handle matching
  117. in the same way as the match_*() methods described above.
  118. import TestCmd
  119. test = TestCmd.TestCmd(match = TestCmd.match_exact)
  120. test = TestCmd.TestCmd(match = TestCmd.match_re)
  121. test = TestCmd.TestCmd(match = TestCmd.match_re_dotall)
  122. The TestCmd module provides unbound functions that can be used for the
  123. "diff" argument to TestCmd.TestCmd instantiation:
  124. import TestCmd
  125. test = TestCmd.TestCmd(match = TestCmd.match_re,
  126. diff = TestCmd.diff_re)
  127. test = TestCmd.TestCmd(diff = TestCmd.simple_diff)
  128. The "diff" argument can also be used with standard difflib functions:
  129. import difflib
  130. test = TestCmd.TestCmd(diff = difflib.context_diff)
  131. test = TestCmd.TestCmd(diff = difflib.unified_diff)
  132. Lastly, the where_is() method also exists in an unbound function
  133. version.
  134. import TestCmd
  135. TestCmd.where_is('foo')
  136. TestCmd.where_is('foo', 'PATH1:PATH2')
  137. TestCmd.where_is('foo', 'PATH1;PATH2', '.suffix3;.suffix4')
  138. """
  139. # Copyright 2000-2010 Steven Knight
  140. # This module is free software, and you may redistribute it and/or modify
  141. # it under the same terms as Python itself, so long as this copyright message
  142. # and disclaimer are retained in their original form.
  143. #
  144. # IN NO EVENT SHALL THE AUTHOR BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
  145. # SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE USE OF
  146. # THIS CODE, EVEN IF THE AUTHOR HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH
  147. # DAMAGE.
  148. #
  149. # THE AUTHOR SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT
  150. # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A
  151. # PARTICULAR PURPOSE. THE CODE PROVIDED HEREUNDER IS ON AN "AS IS" BASIS,
  152. # AND THERE IS NO OBLIGATION WHATSOEVER TO PROVIDE MAINTENANCE,
  153. # SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
  154. __author__ = "Steven Knight <knight at baldmt dot com>"
  155. __revision__ = "TestCmd.py 0.37.D001 2010/01/11 16:55:50 knight"
  156. __version__ = "0.37"
  157. import errno
  158. import os
  159. import os.path
  160. import re
  161. import shutil
  162. import stat
  163. import string
  164. import sys
  165. import tempfile
  166. import time
  167. import traceback
  168. import types
  169. import UserList
  170. __all__ = [
  171. 'diff_re',
  172. 'fail_test',
  173. 'no_result',
  174. 'pass_test',
  175. 'match_exact',
  176. 'match_re',
  177. 'match_re_dotall',
  178. 'python_executable',
  179. 'TestCmd'
  180. ]
  181. try:
  182. import difflib
  183. except ImportError:
  184. __all__.append('simple_diff')
  185. def is_List(e):
  186. return type(e) is types.ListType \
  187. or isinstance(e, UserList.UserList)
  188. try:
  189. from UserString import UserString
  190. except ImportError:
  191. class UserString:
  192. pass
  193. if hasattr(types, 'UnicodeType'):
  194. def is_String(e):
  195. return type(e) is types.StringType \
  196. or type(e) is types.UnicodeType \
  197. or isinstance(e, UserString)
  198. else:
  199. def is_String(e):
  200. return type(e) is types.StringType or isinstance(e, UserString)
  201. tempfile.template = 'testcmd.'
  202. if os.name in ('posix', 'nt'):
  203. tempfile.template = 'testcmd.' + str(os.getpid()) + '.'
  204. else:
  205. tempfile.template = 'testcmd.'
  206. re_space = re.compile('\s')
  207. _Cleanup = []
  208. _chain_to_exitfunc = None
  209. def _clean():
  210. global _Cleanup
  211. cleanlist = filter(None, _Cleanup)
  212. del _Cleanup[:]
  213. cleanlist.reverse()
  214. for test in cleanlist:
  215. test.cleanup()
  216. if _chain_to_exitfunc:
  217. _chain_to_exitfunc()
  218. try:
  219. import atexit
  220. except ImportError:
  221. # TODO(1.5): atexit requires python 2.0, so chain sys.exitfunc
  222. try:
  223. _chain_to_exitfunc = sys.exitfunc
  224. except AttributeError:
  225. pass
  226. sys.exitfunc = _clean
  227. else:
  228. atexit.register(_clean)
  229. try:
  230. zip
  231. except NameError:
  232. def zip(*lists):
  233. result = []
  234. for i in xrange(min(map(len, lists))):
  235. result.append(tuple(map(lambda l, i=i: l[i], lists)))
  236. return result
  237. class Collector:
  238. def __init__(self, top):
  239. self.entries = [top]
  240. def __call__(self, arg, dirname, names):
  241. pathjoin = lambda n, d=dirname: os.path.join(d, n)
  242. self.entries.extend(map(pathjoin, names))
  243. def _caller(tblist, skip):
  244. string = ""
  245. arr = []
  246. for file, line, name, text in tblist:
  247. if file[-10:] == "TestCmd.py":
  248. break
  249. arr = [(file, line, name, text)] + arr
  250. atfrom = "at"
  251. for file, line, name, text in arr[skip:]:
  252. if name in ("?", "<module>"):
  253. name = ""
  254. else:
  255. name = " (" + name + ")"
  256. string = string + ("%s line %d of %s%s\n" % (atfrom, line, file, name))
  257. atfrom = "\tfrom"
  258. return string
  259. def fail_test(self = None, condition = 1, function = None, skip = 0):
  260. """Cause the test to fail.
  261. By default, the fail_test() method reports that the test FAILED
  262. and exits with a status of 1. If a condition argument is supplied,
  263. the test fails only if the condition is true.
  264. """
  265. if not condition:
  266. return
  267. if not function is None:
  268. function()
  269. of = ""
  270. desc = ""
  271. sep = " "
  272. if not self is None:
  273. if self.program:
  274. of = " of " + self.program
  275. sep = "\n\t"
  276. if self.description:
  277. desc = " [" + self.description + "]"
  278. sep = "\n\t"
  279. at = _caller(traceback.extract_stack(), skip)
  280. sys.stderr.write("FAILED test" + of + desc + sep + at)
  281. sys.exit(1)
  282. def no_result(self = None, condition = 1, function = None, skip = 0):
  283. """Causes a test to exit with no valid result.
  284. By default, the no_result() method reports NO RESULT for the test
  285. and exits with a status of 2. If a condition argument is supplied,
  286. the test fails only if the condition is true.
  287. """
  288. if not condition:
  289. return
  290. if not function is None:
  291. function()
  292. of = ""
  293. desc = ""
  294. sep = " "
  295. if not self is None:
  296. if self.program:
  297. of = " of " + self.program
  298. sep = "\n\t"
  299. if self.description:
  300. desc = " [" + self.description + "]"
  301. sep = "\n\t"
  302. if os.environ.get('TESTCMD_DEBUG_SKIPS'):
  303. at = _caller(traceback.extract_stack(), skip)
  304. sys.stderr.write("NO RESULT for test" + of + desc + sep + at)
  305. else:
  306. sys.stderr.write("NO RESULT\n")
  307. sys.exit(2)
  308. def pass_test(self = None, condition = 1, function = None):
  309. """Causes a test to pass.
  310. By default, the pass_test() method reports PASSED for the test
  311. and exits with a status of 0. If a condition argument is supplied,
  312. the test passes only if the condition is true.
  313. """
  314. if not condition:
  315. return
  316. if not function is None:
  317. function()
  318. sys.stderr.write("PASSED\n")
  319. sys.exit(0)
  320. def match_exact(lines = None, matches = None):
  321. """
  322. """
  323. if not is_List(lines):
  324. lines = string.split(lines, "\n")
  325. if not is_List(matches):
  326. matches = string.split(matches, "\n")
  327. if len(lines) != len(matches):
  328. return
  329. for i in range(len(lines)):
  330. if lines[i] != matches[i]:
  331. return
  332. return 1
  333. def match_re(lines = None, res = None):
  334. """
  335. """
  336. if not is_List(lines):
  337. lines = string.split(lines, "\n")
  338. if not is_List(res):
  339. res = string.split(res, "\n")
  340. if len(lines) != len(res):
  341. return
  342. for i in range(len(lines)):
  343. s = "^" + res[i] + "$"
  344. try:
  345. expr = re.compile(s)
  346. except re.error, e:
  347. msg = "Regular expression error in %s: %s"
  348. raise re.error, msg % (repr(s), e[0])
  349. if not expr.search(lines[i]):
  350. return
  351. return 1
  352. def match_re_dotall(lines = None, res = None):
  353. """
  354. """
  355. if not type(lines) is type(""):
  356. lines = string.join(lines, "\n")
  357. if not type(res) is type(""):
  358. res = string.join(res, "\n")
  359. s = "^" + res + "$"
  360. try:
  361. expr = re.compile(s, re.DOTALL)
  362. except re.error, e:
  363. msg = "Regular expression error in %s: %s"
  364. raise re.error, msg % (repr(s), e[0])
  365. if expr.match(lines):
  366. return 1
  367. try:
  368. import difflib
  369. except ImportError:
  370. pass
  371. else:
  372. def simple_diff(a, b, fromfile='', tofile='',
  373. fromfiledate='', tofiledate='', n=3, lineterm='\n'):
  374. """
  375. A function with the same calling signature as difflib.context_diff
  376. (diff -c) and difflib.unified_diff (diff -u) but which prints
  377. output like the simple, unadorned 'diff" command.
  378. """
  379. sm = difflib.SequenceMatcher(None, a, b)
  380. def comma(x1, x2):
  381. return x1+1 == x2 and str(x2) or '%s,%s' % (x1+1, x2)
  382. result = []
  383. for op, a1, a2, b1, b2 in sm.get_opcodes():
  384. if op == 'delete':
  385. result.append("%sd%d" % (comma(a1, a2), b1))
  386. result.extend(map(lambda l: '< ' + l, a[a1:a2]))
  387. elif op == 'insert':
  388. result.append("%da%s" % (a1, comma(b1, b2)))
  389. result.extend(map(lambda l: '> ' + l, b[b1:b2]))
  390. elif op == 'replace':
  391. result.append("%sc%s" % (comma(a1, a2), comma(b1, b2)))
  392. result.extend(map(lambda l: '< ' + l, a[a1:a2]))
  393. result.append('---')
  394. result.extend(map(lambda l: '> ' + l, b[b1:b2]))
  395. return result
  396. def diff_re(a, b, fromfile='', tofile='',
  397. fromfiledate='', tofiledate='', n=3, lineterm='\n'):
  398. """
  399. A simple "diff" of two sets of lines when the expected lines
  400. are regular expressions. This is a really dumb thing that
  401. just compares each line in turn, so it doesn't look for
  402. chunks of matching lines and the like--but at least it lets
  403. you know exactly which line first didn't compare correctl...
  404. """
  405. result = []
  406. diff = len(a) - len(b)
  407. if diff < 0:
  408. a = a + ['']*(-diff)
  409. elif diff > 0:
  410. b = b + ['']*diff
  411. i = 0
  412. for aline, bline in zip(a, b):
  413. s = "^" + aline + "$"
  414. try:
  415. expr = re.compile(s)
  416. except re.error, e:
  417. msg = "Regular expression error in %s: %s"
  418. raise re.error, msg % (repr(s), e[0])
  419. if not expr.search(bline):
  420. result.append("%sc%s" % (i+1, i+1))
  421. result.append('< ' + repr(a[i]))
  422. result.append('---')
  423. result.append('> ' + repr(b[i]))
  424. i = i+1
  425. return result
  426. if os.name == 'java':
  427. python_executable = os.path.join(sys.prefix, 'jython')
  428. else:
  429. python_executable = sys.executable
  430. if sys.platform == 'win32':
  431. default_sleep_seconds = 2
  432. def where_is(file, path=None, pathext=None):
  433. if path is None:
  434. path = os.environ['PATH']
  435. if is_String(path):
  436. path = string.split(path, os.pathsep)
  437. if pathext is None:
  438. pathext = os.environ['PATHEXT']
  439. if is_String(pathext):
  440. pathext = string.split(pathext, os.pathsep)
  441. for ext in pathext:
  442. if string.lower(ext) == string.lower(file[-len(ext):]):
  443. pathext = ['']
  444. break
  445. for dir in path:
  446. f = os.path.join(dir, file)
  447. for ext in pathext:
  448. fext = f + ext
  449. if os.path.isfile(fext):
  450. return fext
  451. return None
  452. else:
  453. def where_is(file, path=None, pathext=None):
  454. if path is None:
  455. path = os.environ['PATH']
  456. if is_String(path):
  457. path = string.split(path, os.pathsep)
  458. for dir in path:
  459. f = os.path.join(dir, file)
  460. if os.path.isfile(f):
  461. try:
  462. st = os.stat(f)
  463. except OSError:
  464. continue
  465. if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
  466. return f
  467. return None
  468. default_sleep_seconds = 1
  469. try:
  470. import subprocess
  471. except ImportError:
  472. # The subprocess module doesn't exist in this version of Python,
  473. # so we're going to cobble up something that looks just enough
  474. # like its API for our purposes below.
  475. import new
  476. subprocess = new.module('subprocess')
  477. subprocess.PIPE = 'PIPE'
  478. subprocess.STDOUT = 'STDOUT'
  479. subprocess.mswindows = (sys.platform == 'win32')
  480. try:
  481. import popen2
  482. popen2.Popen3
  483. except AttributeError:
  484. class Popen3:
  485. universal_newlines = 1
  486. def __init__(self, command, **kw):
  487. if sys.platform == 'win32' and command[0] == '"':
  488. command = '"' + command + '"'
  489. (stdin, stdout, stderr) = os.popen3(' ' + command)
  490. self.stdin = stdin
  491. self.stdout = stdout
  492. self.stderr = stderr
  493. def close_output(self):
  494. self.stdout.close()
  495. self.resultcode = self.stderr.close()
  496. def wait(self):
  497. resultcode = self.resultcode
  498. if os.WIFEXITED(resultcode):
  499. return os.WEXITSTATUS(resultcode)
  500. elif os.WIFSIGNALED(resultcode):
  501. return os.WTERMSIG(resultcode)
  502. else:
  503. return None
  504. else:
  505. try:
  506. popen2.Popen4
  507. except AttributeError:
  508. # A cribbed Popen4 class, with some retrofitted code from
  509. # the Python 1.5 Popen3 class methods to do certain things
  510. # by hand.
  511. class Popen4(popen2.Popen3):
  512. childerr = None
  513. def __init__(self, cmd, bufsize=-1):
  514. p2cread, p2cwrite = os.pipe()
  515. c2pread, c2pwrite = os.pipe()
  516. self.pid = os.fork()
  517. if self.pid == 0:
  518. # Child
  519. os.dup2(p2cread, 0)
  520. os.dup2(c2pwrite, 1)
  521. os.dup2(c2pwrite, 2)
  522. for i in range(3, popen2.MAXFD):
  523. try:
  524. os.close(i)
  525. except: pass
  526. try:
  527. os.execvp(cmd[0], cmd)
  528. finally:
  529. os._exit(1)
  530. # Shouldn't come here, I guess
  531. os._exit(1)
  532. os.close(p2cread)
  533. self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
  534. os.close(c2pwrite)
  535. self.fromchild = os.fdopen(c2pread, 'r', bufsize)
  536. popen2._active.append(self)
  537. popen2.Popen4 = Popen4
  538. class Popen3(popen2.Popen3, popen2.Popen4):
  539. universal_newlines = 1
  540. def __init__(self, command, **kw):
  541. if kw.get('stderr') == 'STDOUT':
  542. apply(popen2.Popen4.__init__, (self, command, 1))
  543. else:
  544. apply(popen2.Popen3.__init__, (self, command, 1))
  545. self.stdin = self.tochild
  546. self.stdout = self.fromchild
  547. self.stderr = self.childerr
  548. def wait(self, *args, **kw):
  549. resultcode = apply(popen2.Popen3.wait, (self,)+args, kw)
  550. if os.WIFEXITED(resultcode):
  551. return os.WEXITSTATUS(resultcode)
  552. elif os.WIFSIGNALED(resultcode):
  553. return os.WTERMSIG(resultcode)
  554. else:
  555. return None
  556. subprocess.Popen = Popen3
  557. # From Josiah Carlson,
  558. # ASPN : Python Cookbook : Module to allow Asynchronous subprocess use on Windows and Posix platforms
  559. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554
  560. PIPE = subprocess.PIPE
  561. if subprocess.mswindows:
  562. from win32file import ReadFile, WriteFile
  563. from win32pipe import PeekNamedPipe
  564. import msvcrt
  565. else:
  566. import select
  567. import fcntl
  568. try: fcntl.F_GETFL
  569. except AttributeError: fcntl.F_GETFL = 3
  570. try: fcntl.F_SETFL
  571. except AttributeError: fcntl.F_SETFL = 4
  572. class Popen(subprocess.Popen):
  573. def recv(self, maxsize=None):
  574. return self._recv('stdout', maxsize)
  575. def recv_err(self, maxsize=None):
  576. return self._recv('stderr', maxsize)
  577. def send_recv(self, input='', maxsize=None):
  578. return self.send(input), self.recv(maxsize), self.recv_err(maxsize)
  579. def get_conn_maxsize(self, which, maxsize):
  580. if maxsize is None:
  581. maxsize = 1024
  582. elif maxsize < 1:
  583. maxsize = 1
  584. return getattr(self, which), maxsize
  585. def _close(self, which):
  586. getattr(self, which).close()
  587. setattr(self, which, None)
  588. if subprocess.mswindows:
  589. def send(self, input):
  590. if not self.stdin:
  591. return None
  592. try:
  593. x = msvcrt.get_osfhandle(self.stdin.fileno())
  594. (errCode, written) = WriteFile(x, input)
  595. except ValueError:
  596. return self._close('stdin')
  597. except (subprocess.pywintypes.error, Exception), why:
  598. if why[0] in (109, errno.ESHUTDOWN):
  599. return self._close('stdin')
  600. raise
  601. return written
  602. def _recv(self, which, maxsize):
  603. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  604. if conn is None:
  605. return None
  606. try:
  607. x = msvcrt.get_osfhandle(conn.fileno())
  608. (read, nAvail, nMessage) = PeekNamedPipe(x, 0)
  609. if maxsize < nAvail:
  610. nAvail = maxsize
  611. if nAvail > 0:
  612. (errCode, read) = ReadFile(x, nAvail, None)
  613. except ValueError:
  614. return self._close(which)
  615. except (subprocess.pywintypes.error, Exception), why:
  616. if why[0] in (109, errno.ESHUTDOWN):
  617. return self._close(which)
  618. raise
  619. #if self.universal_newlines:
  620. # read = self._translate_newlines(read)
  621. return read
  622. else:
  623. def send(self, input):
  624. if not self.stdin:
  625. return None
  626. if not select.select([], [self.stdin], [], 0)[1]:
  627. return 0
  628. try:
  629. written = os.write(self.stdin.fileno(), input)
  630. except OSError, why:
  631. if why[0] == errno.EPIPE: #broken pipe
  632. return self._close('stdin')
  633. raise
  634. return written
  635. def _recv(self, which, maxsize):
  636. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  637. if conn is None:
  638. return None
  639. try:
  640. flags = fcntl.fcntl(conn, fcntl.F_GETFL)
  641. except TypeError:
  642. flags = None
  643. else:
  644. if not conn.closed:
  645. fcntl.fcntl(conn, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  646. try:
  647. if not select.select([conn], [], [], 0)[0]:
  648. return ''
  649. r = conn.read(maxsize)
  650. if not r:
  651. return self._close(which)
  652. #if self.universal_newlines:
  653. # r = self._translate_newlines(r)
  654. return r
  655. finally:
  656. if not conn.closed and not flags is None:
  657. fcntl.fcntl(conn, fcntl.F_SETFL, flags)
  658. disconnect_message = "Other end disconnected!"
  659. def recv_some(p, t=.1, e=1, tr=5, stderr=0):
  660. if tr < 1:
  661. tr = 1
  662. x = time.time()+t
  663. y = []
  664. r = ''
  665. pr = p.recv
  666. if stderr:
  667. pr = p.recv_err
  668. while time.time() < x or r:
  669. r = pr()
  670. if r is None:
  671. if e:
  672. raise Exception(disconnect_message)
  673. else:
  674. break
  675. elif r:
  676. y.append(r)
  677. else:
  678. time.sleep(max((x-time.time())/tr, 0))
  679. return ''.join(y)
  680. # TODO(3.0: rewrite to use memoryview()
  681. def send_all(p, data):
  682. while len(data):
  683. sent = p.send(data)
  684. if sent is None:
  685. raise Exception(disconnect_message)
  686. data = buffer(data, sent)
  687. try:
  688. object
  689. except NameError:
  690. class object:
  691. pass
  692. class TestCmd(object):
  693. """Class TestCmd
  694. """
  695. def __init__(self, description = None,
  696. program = None,
  697. interpreter = None,
  698. workdir = None,
  699. subdir = None,
  700. verbose = None,
  701. match = None,
  702. diff = None,
  703. combine = 0,
  704. universal_newlines = 1):
  705. self._cwd = os.getcwd()
  706. self.description_set(description)
  707. self.program_set(program)
  708. self.interpreter_set(interpreter)
  709. if verbose is None:
  710. try:
  711. verbose = max( 0, int(os.environ.get('TESTCMD_VERBOSE', 0)) )
  712. except ValueError:
  713. verbose = 0
  714. self.verbose_set(verbose)
  715. self.combine = combine
  716. self.universal_newlines = universal_newlines
  717. if match is not None:
  718. self.match_function = match
  719. else:
  720. self.match_function = match_re
  721. if diff is not None:
  722. self.diff_function = diff
  723. else:
  724. try:
  725. difflib
  726. except NameError:
  727. pass
  728. else:
  729. self.diff_function = simple_diff
  730. #self.diff_function = difflib.context_diff
  731. #self.diff_function = difflib.unified_diff
  732. self._dirlist = []
  733. self._preserve = {'pass_test': 0, 'fail_test': 0, 'no_result': 0}
  734. if os.environ.has_key('PRESERVE') and not os.environ['PRESERVE'] is '':
  735. self._preserve['pass_test'] = os.environ['PRESERVE']
  736. self._preserve['fail_test'] = os.environ['PRESERVE']
  737. self._preserve['no_result'] = os.environ['PRESERVE']
  738. else:
  739. try:
  740. self._preserve['pass_test'] = os.environ['PRESERVE_PASS']
  741. except KeyError:
  742. pass
  743. try:
  744. self._preserve['fail_test'] = os.environ['PRESERVE_FAIL']
  745. except KeyError:
  746. pass
  747. try:
  748. self._preserve['no_result'] = os.environ['PRESERVE_NO_RESULT']
  749. except KeyError:
  750. pass
  751. self._stdout = []
  752. self._stderr = []
  753. self.status = None
  754. self.condition = 'no_result'
  755. self.workdir_set(workdir)
  756. self.subdir(subdir)
  757. def __del__(self):
  758. self.cleanup()
  759. def __repr__(self):
  760. return "%x" % id(self)
  761. banner_char = '='
  762. banner_width = 80
  763. def banner(self, s, width=None):
  764. if width is None:
  765. width = self.banner_width
  766. return s + self.banner_char * (width - len(s))
  767. if os.name == 'posix':
  768. def escape(self, arg):
  769. "escape shell special characters"
  770. slash = '\\'
  771. special = '"$'
  772. arg = string.replace(arg, slash, slash+slash)
  773. for c in special:
  774. arg = string.replace(arg, c, slash+c)
  775. if re_space.search(arg):
  776. arg = '"' + arg + '"'
  777. return arg
  778. else:
  779. # Windows does not allow special characters in file names
  780. # anyway, so no need for an escape function, we will just quote
  781. # the arg.
  782. def escape(self, arg):
  783. if re_space.search(arg):
  784. arg = '"' + arg + '"'
  785. return arg
  786. def canonicalize(self, path):
  787. if is_List(path):
  788. path = apply(os.path.join, tuple(path))
  789. if not os.path.isabs(path):
  790. path = os.path.join(self.workdir, path)
  791. return path
  792. def chmod(self, path, mode):
  793. """Changes permissions on the specified file or directory
  794. path name."""
  795. path = self.canonicalize(path)
  796. os.chmod(path, mode)
  797. def cleanup(self, condition = None):
  798. """Removes any temporary working directories for the specified
  799. TestCmd environment. If the environment variable PRESERVE was
  800. set when the TestCmd environment was created, temporary working
  801. directories are not removed. If any of the environment variables
  802. PRESERVE_PASS, PRESERVE_FAIL, or PRESERVE_NO_RESULT were set
  803. when the TestCmd environment was created, then temporary working
  804. directories are not removed if the test passed, failed, or had
  805. no result, respectively. Temporary working directories are also
  806. preserved for conditions specified via the preserve method.
  807. Typically, this method is not called directly, but is used when
  808. the script exits to clean up temporary working directories as
  809. appropriate for the exit status.
  810. """
  811. if not self._dirlist:
  812. return
  813. os.chdir(self._cwd)
  814. self.workdir = None
  815. if condition is None:
  816. condition = self.condition
  817. if self._preserve[condition]:
  818. for dir in self._dirlist:
  819. print "Preserved directory", dir
  820. else:
  821. list = self._dirlist[:]
  822. list.reverse()
  823. for dir in list:
  824. self.writable(dir, 1)
  825. shutil.rmtree(dir, ignore_errors = 1)
  826. self._dirlist = []
  827. try:
  828. global _Cleanup
  829. _Cleanup.remove(self)
  830. except (AttributeError, ValueError):
  831. pass
  832. def command_args(self, program = None,
  833. interpreter = None,
  834. arguments = None):
  835. if program:
  836. if type(program) == type('') and not os.path.isabs(program):
  837. program = os.path.join(self._cwd, program)
  838. else:
  839. program = self.program
  840. if not interpreter:
  841. interpreter = self.interpreter
  842. if not type(program) in [type([]), type(())]:
  843. program = [program]
  844. cmd = list(program)
  845. if interpreter:
  846. if not type(interpreter) in [type([]), type(())]:
  847. interpreter = [interpreter]
  848. cmd = list(interpreter) + cmd
  849. if arguments:
  850. if type(arguments) == type(''):
  851. arguments = string.split(arguments)
  852. cmd.extend(arguments)
  853. return cmd
  854. def description_set(self, description):
  855. """Set the description of the functionality being tested.
  856. """
  857. self.description = description
  858. try:
  859. difflib
  860. except NameError:
  861. def diff(self, a, b, name, *args, **kw):
  862. print self.banner('Expected %s' % name)
  863. print a
  864. print self.banner('Actual %s' % name)
  865. print b
  866. else:
  867. def diff(self, a, b, name, *args, **kw):
  868. print self.banner(name)
  869. args = (a.splitlines(), b.splitlines()) + args
  870. lines = apply(self.diff_function, args, kw)
  871. for l in lines:
  872. print l
  873. def fail_test(self, condition = 1, function = None, skip = 0):
  874. """Cause the test to fail.
  875. """
  876. if not condition:
  877. return
  878. self.condition = 'fail_test'
  879. fail_test(self = self,
  880. condition = condition,
  881. function = function,
  882. skip = skip)
  883. def interpreter_set(self, interpreter):
  884. """Set the program to be used to interpret the program
  885. under test as a script.
  886. """
  887. self.interpreter = interpreter
  888. def match(self, lines, matches):
  889. """Compare actual and expected file contents.
  890. """
  891. return self.match_function(lines, matches)
  892. def match_exact(self, lines, matches):
  893. """Compare actual and expected file contents.
  894. """
  895. return match_exact(lines, matches)
  896. def match_re(self, lines, res):
  897. """Compare actual and expected file contents.
  898. """
  899. return match_re(lines, res)
  900. def match_re_dotall(self, lines, res):
  901. """Compare actual and expected file contents.
  902. """
  903. return match_re_dotall(lines, res)
  904. def no_result(self, condition = 1, function = None, skip = 0):
  905. """Report that the test could not be run.
  906. """
  907. if not condition:
  908. return
  909. self.condition = 'no_result'
  910. no_result(self = self,
  911. condition = condition,
  912. function = function,
  913. skip = skip)
  914. def pass_test(self, condition = 1, function = None):
  915. """Cause the test to pass.
  916. """
  917. if not condition:
  918. return
  919. self.condition = 'pass_test'
  920. pass_test(self = self, condition = condition, function = function)
  921. def preserve(self, *conditions):
  922. """Arrange for the temporary working directories for the
  923. specified TestCmd environment to be preserved for one or more
  924. conditions. If no conditions are specified, arranges for
  925. the temporary working directories to be preserved for all
  926. conditions.
  927. """
  928. if conditions is ():
  929. conditions = ('pass_test', 'fail_test', 'no_result')
  930. for cond in conditions:
  931. self._preserve[cond] = 1
  932. def program_set(self, program):
  933. """Set the executable program or script to be tested.
  934. """
  935. if program and not os.path.isabs(program):
  936. program = os.path.join(self._cwd, program)
  937. self.program = program
  938. def read(self, file, mode = 'rb'):
  939. """Reads and returns the contents of the specified file name.
  940. The file name may be a list, in which case the elements are
  941. concatenated with the os.path.join() method. The file is
  942. assumed to be under the temporary working directory unless it
  943. is an absolute path name. The I/O mode for the file may
  944. be specified; it must begin with an 'r'. The default is
  945. 'rb' (binary read).
  946. """
  947. file = self.canonicalize(file)
  948. if mode[0] != 'r':
  949. raise ValueError, "mode must begin with 'r'"
  950. with open(file, mode) as f:
  951. result = f.read()
  952. return result
  953. def rmdir(self, dir):
  954. """Removes the specified dir name.
  955. The dir name may be a list, in which case the elements are
  956. concatenated with the os.path.join() method. The dir is
  957. assumed to be under the temporary working directory unless it
  958. is an absolute path name.
  959. The dir must be empty.
  960. """
  961. dir = self.canonicalize(dir)
  962. os.rmdir(dir)
  963. def start(self, program = None,
  964. interpreter = None,
  965. arguments = None,
  966. universal_newlines = None,
  967. **kw):
  968. """
  969. Starts a program or script for the test environment.
  970. The specified program will have the original directory
  971. prepended unless it is enclosed in a [list].
  972. """
  973. cmd = self.command_args(program, interpreter, arguments)
  974. cmd_string = string.join(map(self.escape, cmd), ' ')
  975. if self.verbose:
  976. sys.stderr.write(cmd_string + "\n")
  977. if universal_newlines is None:
  978. universal_newlines = self.universal_newlines
  979. # On Windows, if we make stdin a pipe when we plan to send
  980. # no input, and the test program exits before
  981. # Popen calls msvcrt.open_osfhandle, that call will fail.
  982. # So don't use a pipe for stdin if we don't need one.
  983. stdin = kw.get('stdin', None)
  984. if stdin is not None:
  985. stdin = subprocess.PIPE
  986. combine = kw.get('combine', self.combine)
  987. if combine:
  988. stderr_value = subprocess.STDOUT
  989. else:
  990. stderr_value = subprocess.PIPE
  991. return Popen(cmd,
  992. stdin=stdin,
  993. stdout=subprocess.PIPE,
  994. stderr=stderr_value,
  995. universal_newlines=universal_newlines)
  996. def finish(self, popen, **kw):
  997. """
  998. Finishes and waits for the process being run under control of
  999. the specified popen argument, recording the exit status,
  1000. standard output and error output.
  1001. """
  1002. popen.stdin.close()
  1003. self.status = popen.wait()
  1004. if not self.status:
  1005. self.status = 0
  1006. self._stdout.append(popen.stdout.read())
  1007. if popen.stderr:
  1008. stderr = popen.stderr.read()
  1009. else:
  1010. stderr = ''
  1011. self._stderr.append(stderr)
  1012. def run(self, program = None,
  1013. interpreter = None,
  1014. arguments = None,
  1015. chdir = None,
  1016. stdin = None,
  1017. universal_newlines = None):
  1018. """Runs a test of the program or script for the test
  1019. environment. Standard output and error output are saved for
  1020. future retrieval via the stdout() and stderr() methods.
  1021. The specified program will have the original directory
  1022. prepended unless it is enclosed in a [list].
  1023. """
  1024. if chdir:
  1025. oldcwd = os.getcwd()
  1026. if not os.path.isabs(chdir):
  1027. chdir = os.path.join(self.workpath(chdir))
  1028. if self.verbose:
  1029. sys.stderr.write("chdir(" + chdir + ")\n")
  1030. os.chdir(chdir)
  1031. p = self.start(program,
  1032. interpreter,
  1033. arguments,
  1034. universal_newlines,
  1035. stdin=stdin)
  1036. if stdin:
  1037. if is_List(stdin):
  1038. for line in stdin:
  1039. p.stdin.write(line)
  1040. else:
  1041. p.stdin.write(stdin)
  1042. p.stdin.close()
  1043. out = p.stdout.read()
  1044. if p.stderr is None:
  1045. err = ''
  1046. else:
  1047. err = p.stderr.read()
  1048. try:
  1049. close_output = p.close_output
  1050. except AttributeError:
  1051. p.stdout.close()
  1052. if not p.stderr is None:
  1053. p.stderr.close()
  1054. else:
  1055. close_output()
  1056. self._stdout.append(out)
  1057. self._stderr.append(err)
  1058. self.status = p.wait()
  1059. if not self.status:
  1060. self.status = 0
  1061. if chdir:
  1062. os.chdir(oldcwd)
  1063. if self.verbose >= 2:
  1064. write = sys.stdout.write
  1065. write('============ STATUS: %d\n' % self.status)
  1066. out = self.stdout()
  1067. if out or self.verbose >= 3:
  1068. write('============ BEGIN STDOUT (len=%d):\n' % len(out))
  1069. write(out)
  1070. write('============ END STDOUT\n')
  1071. err = self.stderr()
  1072. if err or self.verbose >= 3:
  1073. write('============ BEGIN STDERR (len=%d)\n' % len(err))
  1074. write(err)
  1075. write('============ END STDERR\n')
  1076. def sleep(self, seconds = default_sleep_seconds):
  1077. """Sleeps at least the specified number of seconds. If no
  1078. number is specified, sleeps at least the minimum number of
  1079. seconds necessary to advance file time stamps on the current
  1080. system. Sleeping more seconds is all right.
  1081. """
  1082. time.sleep(seconds)
  1083. def stderr(self, run = None):
  1084. """Returns the error output from the specified run number.
  1085. If there is no specified run number, then returns the error
  1086. output of the last run. If the run number is less than zero,
  1087. then returns the error output from that many runs back from the
  1088. current run.
  1089. """
  1090. if not run:
  1091. run = len(self._stderr)
  1092. elif run < 0:
  1093. run = len(self._stderr) + run
  1094. run = run - 1
  1095. return self._stderr[run]
  1096. def stdout(self, run = None):
  1097. """Returns the standard output from the specified run number.
  1098. If there is no specified run number, then returns the standard
  1099. output of the last run. If the run number is less than zero,
  1100. then returns the standard output from that many runs back from
  1101. the current run.
  1102. """
  1103. if not run:
  1104. run = len(self._stdout)
  1105. elif run < 0:
  1106. run = len(self._stdout) + run
  1107. run = run - 1
  1108. return self._stdout[run]
  1109. def subdir(self, *subdirs):
  1110. """Create new subdirectories under the temporary working
  1111. directory, one for each argument. An argument may be a list,
  1112. in which case the list elements are concatenated using the
  1113. os.path.join() method. Subdirectories multiple levels deep
  1114. must be created using a separate argument for each level:
  1115. test.subdir('sub', ['sub', 'dir'], ['sub', 'dir', 'ectory'])
  1116. Returns the number of subdirectories actually created.
  1117. """
  1118. count = 0
  1119. for sub in subdirs:
  1120. if sub is None:
  1121. continue
  1122. if is_List(sub):
  1123. sub = apply(os.path.join, tuple(sub))
  1124. new = os.path.join(self.workdir, sub)
  1125. try:
  1126. os.mkdir(new)
  1127. except OSError:
  1128. pass
  1129. else:
  1130. count = count + 1
  1131. return count
  1132. def symlink(self, target, link):
  1133. """Creates a symlink to the specified target.
  1134. The link name may be a list, in which case the elements are
  1135. concatenated with the os.path.join() method. The link is
  1136. assumed to be under the temporary working directory unless it
  1137. is an absolute path name. The target is *not* assumed to be
  1138. under the temporary working directory.
  1139. """
  1140. link = self.canonicalize(link)
  1141. os.symlink(target, link)
  1142. def tempdir(self, path=None):
  1143. """Creates a temporary directory.
  1144. A unique directory name is generated if no path name is specified.
  1145. The directory is created, and will be removed when the TestCmd
  1146. object is destroyed.
  1147. """
  1148. if path is None:
  1149. try:
  1150. path = tempfile.mktemp(prefix=tempfile.template)
  1151. except TypeError:
  1152. path = tempfile.mktemp()
  1153. os.mkdir(path)
  1154. # Symlinks in the path will report things
  1155. # differently from os.getcwd(), so chdir there
  1156. # and back to fetch the canonical path.
  1157. cwd = os.getcwd()
  1158. try:
  1159. os.chdir(path)
  1160. path = os.getcwd()
  1161. finally:
  1162. os.chdir(cwd)
  1163. # Uppercase the drive letter since the case of drive
  1164. # letters is pretty much random on win32:
  1165. drive,rest = os.path.splitdrive(path)
  1166. if drive:
  1167. path = string.upper(drive) + rest
  1168. #
  1169. self._dirlist.append(path)
  1170. global _Cleanup
  1171. try:
  1172. _Cleanup.index(self)
  1173. except ValueError:
  1174. _Cleanup.append(self)
  1175. return path
  1176. def touch(self, path, mtime=None):
  1177. """Updates the modification time on the specified file or
  1178. directory path name. The default is to update to the
  1179. current time if no explicit modification time is specified.
  1180. """
  1181. path = self.canonicalize(path)
  1182. atime = os.path.getatime(path)
  1183. if mtime is None:
  1184. mtime = time.time()
  1185. os.utime(path, (atime, mtime))
  1186. def unlink(self, file):
  1187. """Unlinks the specified file name.
  1188. The file name may be a list, in which case the elements are
  1189. concatenated with the os.path.join() method. The file is
  1190. assumed to be under the temporary working directory unless it
  1191. is an absolute path name.
  1192. """
  1193. file = self.canonicalize(file)
  1194. os.unlink(file)
  1195. def verbose_set(self, verbose):
  1196. """Set the verbose level.
  1197. """
  1198. self.verbose = verbose
  1199. def where_is(self, file, path=None, pathext=None):
  1200. """Find an executable file.
  1201. """
  1202. if is_List(file):
  1203. file = apply(os.path.join, tuple(file))
  1204. if not os.path.isabs(file):
  1205. file = where_is(file, path, pathext)
  1206. return file
  1207. def workdir_set(self, path):
  1208. """Creates a temporary working directory with the specified
  1209. path name. If the path is a null string (''), a unique
  1210. directory name is created.
  1211. """
  1212. if (path != None):
  1213. if path == '':
  1214. path = None
  1215. path = self.tempdir(path)
  1216. self.workdir = path
  1217. def workpath(self, *args):
  1218. """Returns the absolute path name to a subdirectory or file
  1219. within the current temporary working directory. Concatenates
  1220. the temporary working directory name with the specified
  1221. arguments using the os.path.join() method.
  1222. """
  1223. return apply(os.path.join, (self.workdir,) + tuple(args))
  1224. def readable(self, top, read=1):
  1225. """Make the specified directory tree readable (read == 1)
  1226. or not (read == None).
  1227. This method has no effect on Windows systems, which use a
  1228. completely different mechanism to control file readability.
  1229. """
  1230. if sys.platform == 'win32':
  1231. return
  1232. if read:
  1233. def do_chmod(fname):
  1234. try: st = os.stat(fname)
  1235. except OSError: pass
  1236. else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]|stat.S_IREAD))
  1237. else:
  1238. def do_chmod(fname):
  1239. try: st = os.stat(fname)
  1240. except OSError: pass
  1241. else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]&~stat.S_IREAD))
  1242. if os.path.isfile(top):
  1243. # If it's a file, that's easy, just chmod it.
  1244. do_chmod(top)
  1245. elif read:
  1246. # It's a directory and we're trying to turn on read
  1247. # permission, so it's also pretty easy, just chmod the
  1248. # directory and then chmod every entry on our walk down the
  1249. # tree. Because os.path.walk() is top-down, we'll enable
  1250. # read permission on any directories that have it disabled
  1251. # before os.path.walk() tries to list their contents.
  1252. do_chmod(top)
  1253. def chmod_entries(arg, dirname, names, do_chmod=do_chmod):
  1254. for n in names:
  1255. do_chmod(os.path.join(dirname, n))
  1256. os.path.walk(top, chmod_entries, None)
  1257. else:
  1258. # It's a directory and we're trying to turn off read
  1259. # permission, which means we have to chmod the directoreis
  1260. # in the tree bottom-up, lest disabling read permission from
  1261. # the top down get in the way of being able to get at lower
  1262. # parts of the tree. But os.path.walk() visits things top
  1263. # down, so we just use an object to collect a list of all
  1264. # of the entries in the tree, reverse the list, and then
  1265. # chmod the reversed (bottom-up) list.
  1266. col = Collector(top)
  1267. os.path.walk(top, col, None)
  1268. col.entries.reverse()
  1269. for d in col.entries: do_chmod(d)
  1270. def writable(self, top, write=1):
  1271. """Make the specified directory tree writable (write == 1)
  1272. or not (write == None).
  1273. """
  1274. if sys.platform == 'win32':
  1275. if write:
  1276. def do_chmod(fname):
  1277. try: os.chmod(fname, stat.S_IWRITE)
  1278. except OSError: pass
  1279. else:
  1280. def do_chmod(fname):
  1281. try: os.chmod(fname, stat.S_IREAD)
  1282. except OSError: pass
  1283. else:
  1284. if write:
  1285. def do_chmod(fname):
  1286. try: st = os.stat(fname)
  1287. except OSError: pass
  1288. else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]|0200))
  1289. else:
  1290. def do_chmod(fname):
  1291. try: st = os.stat(fname)
  1292. except OSError: pass
  1293. else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]&~0200))
  1294. if os.path.isfile(top):
  1295. do_chmod(top)
  1296. else:
  1297. col = Collector(top)
  1298. os.path.walk(top, col, None)
  1299. for d in col.entries: do_chmod(d)
  1300. def executable(self, top, execute=1):
  1301. """Make the specified directory tree executable (execute == 1)
  1302. or not (execute == None).
  1303. This method has no effect on Windows systems, which use a
  1304. completely different mechanism to control file executability.
  1305. """
  1306. if sys.platform == 'win32':
  1307. return
  1308. if execute:
  1309. def do_chmod(fname):
  1310. try: st = os.stat(fname)
  1311. except OSError: pass
  1312. else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]|stat.S_IEXEC))
  1313. else:
  1314. def do_chmod(fname):
  1315. try: st = os.stat(fname)
  1316. except OSError: pass
  1317. else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]&~stat.S_IEXEC))
  1318. if os.path.isfile(top):
  1319. # If it's a file, that's easy, just chmod it.
  1320. do_chmod(top)
  1321. elif execute:
  1322. # It's a directory and we're trying to turn on execute
  1323. # permission, so it's also pretty easy, just chmod the
  1324. # directory and then chmod every entry on our walk down the
  1325. # tree. Because os.path.walk() is top-down, we'll enable
  1326. # execute permission on any directories that have it disabled
  1327. # before os.path.walk() tries to list their contents.
  1328. do_chmod(top)
  1329. def chmod_entries(arg, dirname, names, do_chmod=do_chmod):
  1330. for n in names:
  1331. do_chmod(os.path.join(dirname, n))
  1332. os.path.walk(top, chmod_entries, None)
  1333. else:
  1334. # It's a directory and we're trying to turn off execute
  1335. # permission, which means we have to chmod the directories
  1336. # in the tree bottom-up, lest disabling execute permission from
  1337. # the top down get in the way of being able to get at lower
  1338. # parts of the tree. But os.path.walk() visits things top
  1339. # down, so we just use an object to collect a list of all
  1340. # of the entries in the tree, reverse the list, and then
  1341. # chmod the reversed (bottom-up) list.
  1342. col = Collector(top)
  1343. os.path.walk(top, col, None)
  1344. col.entries.reverse()
  1345. for d in col.entries: do_chmod(d)
  1346. def write(self, file, content, mode = 'wb'):
  1347. """Writes the specified content text (second argument) to the
  1348. specified file name (first argument). The file name may be
  1349. a list, in which case the elements are concatenated with the
  1350. os.path.join() method. The file is created under the temporary
  1351. working directory. Any subdirectories in the path must already
  1352. exist. The I/O mode for the file may be specified; it must
  1353. begin with a 'w'. The default is 'wb' (binary write).
  1354. """
  1355. file = self.canonicalize(file)
  1356. if mode[0] != 'w':
  1357. raise ValueError, "mode must begin with 'w'"
  1358. with open(file, mode) as f:
  1359. f.write(content)
  1360. # Local Variables:
  1361. # tab-width:4
  1362. # indent-tabs-mode:nil
  1363. # End:
  1364. # vim: set expandtab tabstop=4 shiftwidth=4: