PageRenderTime 98ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/media/webrtc/trunk/tools/gyp/test/lib/TestCmd.py

https://bitbucket.org/halwine/releases-mozilla-inbound
Python | 1594 lines | 1473 code | 37 blank | 84 comment | 66 complexity | 24754198589b8e4a564d5ed0c8e3a47c MD5 | raw file
Possible License(s): AGPL-1.0, JSON, 0BSD, BSD-2-Clause, GPL-2.0, Apache-2.0, LGPL-2.1, LGPL-3.0, MIT, MPL-2.0-no-copyleft-exception, MPL-2.0, BSD-3-Clause

Large files files are truncated, but you can click here to view the full file

  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. at = _caller(traceback.extract_stack(), skip)
  303. sys.stderr.write("NO RESULT for test" + of + desc + sep + at)
  304. sys.exit(2)
  305. def pass_test(self = None, condition = 1, function = None):
  306. """Causes a test to pass.
  307. By default, the pass_test() method reports PASSED for the test
  308. and exits with a status of 0. If a condition argument is supplied,
  309. the test passes only if the condition is true.
  310. """
  311. if not condition:
  312. return
  313. if not function is None:
  314. function()
  315. sys.stderr.write("PASSED\n")
  316. sys.exit(0)
  317. def match_exact(lines = None, matches = None):
  318. """
  319. """
  320. if not is_List(lines):
  321. lines = string.split(lines, "\n")
  322. if not is_List(matches):
  323. matches = string.split(matches, "\n")
  324. if len(lines) != len(matches):
  325. return
  326. for i in range(len(lines)):
  327. if lines[i] != matches[i]:
  328. return
  329. return 1
  330. def match_re(lines = None, res = None):
  331. """
  332. """
  333. if not is_List(lines):
  334. lines = string.split(lines, "\n")
  335. if not is_List(res):
  336. res = string.split(res, "\n")
  337. if len(lines) != len(res):
  338. return
  339. for i in range(len(lines)):
  340. s = "^" + res[i] + "$"
  341. try:
  342. expr = re.compile(s)
  343. except re.error, e:
  344. msg = "Regular expression error in %s: %s"
  345. raise re.error, msg % (repr(s), e[0])
  346. if not expr.search(lines[i]):
  347. return
  348. return 1
  349. def match_re_dotall(lines = None, res = None):
  350. """
  351. """
  352. if not type(lines) is type(""):
  353. lines = string.join(lines, "\n")
  354. if not type(res) is type(""):
  355. res = string.join(res, "\n")
  356. s = "^" + res + "$"
  357. try:
  358. expr = re.compile(s, re.DOTALL)
  359. except re.error, e:
  360. msg = "Regular expression error in %s: %s"
  361. raise re.error, msg % (repr(s), e[0])
  362. if expr.match(lines):
  363. return 1
  364. try:
  365. import difflib
  366. except ImportError:
  367. pass
  368. else:
  369. def simple_diff(a, b, fromfile='', tofile='',
  370. fromfiledate='', tofiledate='', n=3, lineterm='\n'):
  371. """
  372. A function with the same calling signature as difflib.context_diff
  373. (diff -c) and difflib.unified_diff (diff -u) but which prints
  374. output like the simple, unadorned 'diff" command.
  375. """
  376. sm = difflib.SequenceMatcher(None, a, b)
  377. def comma(x1, x2):
  378. return x1+1 == x2 and str(x2) or '%s,%s' % (x1+1, x2)
  379. result = []
  380. for op, a1, a2, b1, b2 in sm.get_opcodes():
  381. if op == 'delete':
  382. result.append("%sd%d" % (comma(a1, a2), b1))
  383. result.extend(map(lambda l: '< ' + l, a[a1:a2]))
  384. elif op == 'insert':
  385. result.append("%da%s" % (a1, comma(b1, b2)))
  386. result.extend(map(lambda l: '> ' + l, b[b1:b2]))
  387. elif op == 'replace':
  388. result.append("%sc%s" % (comma(a1, a2), comma(b1, b2)))
  389. result.extend(map(lambda l: '< ' + l, a[a1:a2]))
  390. result.append('---')
  391. result.extend(map(lambda l: '> ' + l, b[b1:b2]))
  392. return result
  393. def diff_re(a, b, fromfile='', tofile='',
  394. fromfiledate='', tofiledate='', n=3, lineterm='\n'):
  395. """
  396. A simple "diff" of two sets of lines when the expected lines
  397. are regular expressions. This is a really dumb thing that
  398. just compares each line in turn, so it doesn't look for
  399. chunks of matching lines and the like--but at least it lets
  400. you know exactly which line first didn't compare correctl...
  401. """
  402. result = []
  403. diff = len(a) - len(b)
  404. if diff < 0:
  405. a = a + ['']*(-diff)
  406. elif diff > 0:
  407. b = b + ['']*diff
  408. i = 0
  409. for aline, bline in zip(a, b):
  410. s = "^" + aline + "$"
  411. try:
  412. expr = re.compile(s)
  413. except re.error, e:
  414. msg = "Regular expression error in %s: %s"
  415. raise re.error, msg % (repr(s), e[0])
  416. if not expr.search(bline):
  417. result.append("%sc%s" % (i+1, i+1))
  418. result.append('< ' + repr(a[i]))
  419. result.append('---')
  420. result.append('> ' + repr(b[i]))
  421. i = i+1
  422. return result
  423. if os.name == 'java':
  424. python_executable = os.path.join(sys.prefix, 'jython')
  425. else:
  426. python_executable = sys.executable
  427. if sys.platform == 'win32':
  428. default_sleep_seconds = 2
  429. def where_is(file, path=None, pathext=None):
  430. if path is None:
  431. path = os.environ['PATH']
  432. if is_String(path):
  433. path = string.split(path, os.pathsep)
  434. if pathext is None:
  435. pathext = os.environ['PATHEXT']
  436. if is_String(pathext):
  437. pathext = string.split(pathext, os.pathsep)
  438. for ext in pathext:
  439. if string.lower(ext) == string.lower(file[-len(ext):]):
  440. pathext = ['']
  441. break
  442. for dir in path:
  443. f = os.path.join(dir, file)
  444. for ext in pathext:
  445. fext = f + ext
  446. if os.path.isfile(fext):
  447. return fext
  448. return None
  449. else:
  450. def where_is(file, path=None, pathext=None):
  451. if path is None:
  452. path = os.environ['PATH']
  453. if is_String(path):
  454. path = string.split(path, os.pathsep)
  455. for dir in path:
  456. f = os.path.join(dir, file)
  457. if os.path.isfile(f):
  458. try:
  459. st = os.stat(f)
  460. except OSError:
  461. continue
  462. if stat.S_IMODE(st[stat.ST_MODE]) & 0111:
  463. return f
  464. return None
  465. default_sleep_seconds = 1
  466. try:
  467. import subprocess
  468. except ImportError:
  469. # The subprocess module doesn't exist in this version of Python,
  470. # so we're going to cobble up something that looks just enough
  471. # like its API for our purposes below.
  472. import new
  473. subprocess = new.module('subprocess')
  474. subprocess.PIPE = 'PIPE'
  475. subprocess.STDOUT = 'STDOUT'
  476. subprocess.mswindows = (sys.platform == 'win32')
  477. try:
  478. import popen2
  479. popen2.Popen3
  480. except AttributeError:
  481. class Popen3:
  482. universal_newlines = 1
  483. def __init__(self, command, **kw):
  484. if sys.platform == 'win32' and command[0] == '"':
  485. command = '"' + command + '"'
  486. (stdin, stdout, stderr) = os.popen3(' ' + command)
  487. self.stdin = stdin
  488. self.stdout = stdout
  489. self.stderr = stderr
  490. def close_output(self):
  491. self.stdout.close()
  492. self.resultcode = self.stderr.close()
  493. def wait(self):
  494. resultcode = self.resultcode
  495. if os.WIFEXITED(resultcode):
  496. return os.WEXITSTATUS(resultcode)
  497. elif os.WIFSIGNALED(resultcode):
  498. return os.WTERMSIG(resultcode)
  499. else:
  500. return None
  501. else:
  502. try:
  503. popen2.Popen4
  504. except AttributeError:
  505. # A cribbed Popen4 class, with some retrofitted code from
  506. # the Python 1.5 Popen3 class methods to do certain things
  507. # by hand.
  508. class Popen4(popen2.Popen3):
  509. childerr = None
  510. def __init__(self, cmd, bufsize=-1):
  511. p2cread, p2cwrite = os.pipe()
  512. c2pread, c2pwrite = os.pipe()
  513. self.pid = os.fork()
  514. if self.pid == 0:
  515. # Child
  516. os.dup2(p2cread, 0)
  517. os.dup2(c2pwrite, 1)
  518. os.dup2(c2pwrite, 2)
  519. for i in range(3, popen2.MAXFD):
  520. try:
  521. os.close(i)
  522. except: pass
  523. try:
  524. os.execvp(cmd[0], cmd)
  525. finally:
  526. os._exit(1)
  527. # Shouldn't come here, I guess
  528. os._exit(1)
  529. os.close(p2cread)
  530. self.tochild = os.fdopen(p2cwrite, 'w', bufsize)
  531. os.close(c2pwrite)
  532. self.fromchild = os.fdopen(c2pread, 'r', bufsize)
  533. popen2._active.append(self)
  534. popen2.Popen4 = Popen4
  535. class Popen3(popen2.Popen3, popen2.Popen4):
  536. universal_newlines = 1
  537. def __init__(self, command, **kw):
  538. if kw.get('stderr') == 'STDOUT':
  539. apply(popen2.Popen4.__init__, (self, command, 1))
  540. else:
  541. apply(popen2.Popen3.__init__, (self, command, 1))
  542. self.stdin = self.tochild
  543. self.stdout = self.fromchild
  544. self.stderr = self.childerr
  545. def wait(self, *args, **kw):
  546. resultcode = apply(popen2.Popen3.wait, (self,)+args, kw)
  547. if os.WIFEXITED(resultcode):
  548. return os.WEXITSTATUS(resultcode)
  549. elif os.WIFSIGNALED(resultcode):
  550. return os.WTERMSIG(resultcode)
  551. else:
  552. return None
  553. subprocess.Popen = Popen3
  554. # From Josiah Carlson,
  555. # ASPN : Python Cookbook : Module to allow Asynchronous subprocess use on Windows and Posix platforms
  556. # http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/440554
  557. PIPE = subprocess.PIPE
  558. if subprocess.mswindows:
  559. from win32file import ReadFile, WriteFile
  560. from win32pipe import PeekNamedPipe
  561. import msvcrt
  562. else:
  563. import select
  564. import fcntl
  565. try: fcntl.F_GETFL
  566. except AttributeError: fcntl.F_GETFL = 3
  567. try: fcntl.F_SETFL
  568. except AttributeError: fcntl.F_SETFL = 4
  569. class Popen(subprocess.Popen):
  570. def recv(self, maxsize=None):
  571. return self._recv('stdout', maxsize)
  572. def recv_err(self, maxsize=None):
  573. return self._recv('stderr', maxsize)
  574. def send_recv(self, input='', maxsize=None):
  575. return self.send(input), self.recv(maxsize), self.recv_err(maxsize)
  576. def get_conn_maxsize(self, which, maxsize):
  577. if maxsize is None:
  578. maxsize = 1024
  579. elif maxsize < 1:
  580. maxsize = 1
  581. return getattr(self, which), maxsize
  582. def _close(self, which):
  583. getattr(self, which).close()
  584. setattr(self, which, None)
  585. if subprocess.mswindows:
  586. def send(self, input):
  587. if not self.stdin:
  588. return None
  589. try:
  590. x = msvcrt.get_osfhandle(self.stdin.fileno())
  591. (errCode, written) = WriteFile(x, input)
  592. except ValueError:
  593. return self._close('stdin')
  594. except (subprocess.pywintypes.error, Exception), why:
  595. if why[0] in (109, errno.ESHUTDOWN):
  596. return self._close('stdin')
  597. raise
  598. return written
  599. def _recv(self, which, maxsize):
  600. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  601. if conn is None:
  602. return None
  603. try:
  604. x = msvcrt.get_osfhandle(conn.fileno())
  605. (read, nAvail, nMessage) = PeekNamedPipe(x, 0)
  606. if maxsize < nAvail:
  607. nAvail = maxsize
  608. if nAvail > 0:
  609. (errCode, read) = ReadFile(x, nAvail, None)
  610. except ValueError:
  611. return self._close(which)
  612. except (subprocess.pywintypes.error, Exception), why:
  613. if why[0] in (109, errno.ESHUTDOWN):
  614. return self._close(which)
  615. raise
  616. #if self.universal_newlines:
  617. # read = self._translate_newlines(read)
  618. return read
  619. else:
  620. def send(self, input):
  621. if not self.stdin:
  622. return None
  623. if not select.select([], [self.stdin], [], 0)[1]:
  624. return 0
  625. try:
  626. written = os.write(self.stdin.fileno(), input)
  627. except OSError, why:
  628. if why[0] == errno.EPIPE: #broken pipe
  629. return self._close('stdin')
  630. raise
  631. return written
  632. def _recv(self, which, maxsize):
  633. conn, maxsize = self.get_conn_maxsize(which, maxsize)
  634. if conn is None:
  635. return None
  636. try:
  637. flags = fcntl.fcntl(conn, fcntl.F_GETFL)
  638. except TypeError:
  639. flags = None
  640. else:
  641. if not conn.closed:
  642. fcntl.fcntl(conn, fcntl.F_SETFL, flags| os.O_NONBLOCK)
  643. try:
  644. if not select.select([conn], [], [], 0)[0]:
  645. return ''
  646. r = conn.read(maxsize)
  647. if not r:
  648. return self._close(which)
  649. #if self.universal_newlines:
  650. # r = self._translate_newlines(r)
  651. return r
  652. finally:
  653. if not conn.closed and not flags is None:
  654. fcntl.fcntl(conn, fcntl.F_SETFL, flags)
  655. disconnect_message = "Other end disconnected!"
  656. def recv_some(p, t=.1, e=1, tr=5, stderr=0):
  657. if tr < 1:
  658. tr = 1
  659. x = time.time()+t
  660. y = []
  661. r = ''
  662. pr = p.recv
  663. if stderr:
  664. pr = p.recv_err
  665. while time.time() < x or r:
  666. r = pr()
  667. if r is None:
  668. if e:
  669. raise Exception(disconnect_message)
  670. else:
  671. break
  672. elif r:
  673. y.append(r)
  674. else:
  675. time.sleep(max((x-time.time())/tr, 0))
  676. return ''.join(y)
  677. # TODO(3.0: rewrite to use memoryview()
  678. def send_all(p, data):
  679. while len(data):
  680. sent = p.send(data)
  681. if sent is None:
  682. raise Exception(disconnect_message)
  683. data = buffer(data, sent)
  684. try:
  685. object
  686. except NameError:
  687. class object:
  688. pass
  689. class TestCmd(object):
  690. """Class TestCmd
  691. """
  692. def __init__(self, description = None,
  693. program = None,
  694. interpreter = None,
  695. workdir = None,
  696. subdir = None,
  697. verbose = None,
  698. match = None,
  699. diff = None,
  700. combine = 0,
  701. universal_newlines = 1):
  702. self._cwd = os.getcwd()
  703. self.description_set(description)
  704. self.program_set(program)
  705. self.interpreter_set(interpreter)
  706. if verbose is None:
  707. try:
  708. verbose = max( 0, int(os.environ.get('TESTCMD_VERBOSE', 0)) )
  709. except ValueError:
  710. verbose = 0
  711. self.verbose_set(verbose)
  712. self.combine = combine
  713. self.universal_newlines = universal_newlines
  714. if match is not None:
  715. self.match_function = match
  716. else:
  717. self.match_function = match_re
  718. if diff is not None:
  719. self.diff_function = diff
  720. else:
  721. try:
  722. difflib
  723. except NameError:
  724. pass
  725. else:
  726. self.diff_function = simple_diff
  727. #self.diff_function = difflib.context_diff
  728. #self.diff_function = difflib.unified_diff
  729. self._dirlist = []
  730. self._preserve = {'pass_test': 0, 'fail_test': 0, 'no_result': 0}
  731. if os.environ.has_key('PRESERVE') and not os.environ['PRESERVE'] is '':
  732. self._preserve['pass_test'] = os.environ['PRESERVE']
  733. self._preserve['fail_test'] = os.environ['PRESERVE']
  734. self._preserve['no_result'] = os.environ['PRESERVE']
  735. else:
  736. try:
  737. self._preserve['pass_test'] = os.environ['PRESERVE_PASS']
  738. except KeyError:
  739. pass
  740. try:
  741. self._preserve['fail_test'] = os.environ['PRESERVE_FAIL']
  742. except KeyError:
  743. pass
  744. try:
  745. self._preserve['no_result'] = os.environ['PRESERVE_NO_RESULT']
  746. except KeyError:
  747. pass
  748. self._stdout = []
  749. self._stderr = []
  750. self.status = None
  751. self.condition = 'no_result'
  752. self.workdir_set(workdir)
  753. self.subdir(subdir)
  754. def __del__(self):
  755. self.cleanup()
  756. def __repr__(self):
  757. return "%x" % id(self)
  758. banner_char = '='
  759. banner_width = 80
  760. def banner(self, s, width=None):
  761. if width is None:
  762. width = self.banner_width
  763. return s + self.banner_char * (width - len(s))
  764. if os.name == 'posix':
  765. def escape(self, arg):
  766. "escape shell special characters"
  767. slash = '\\'
  768. special = '"$'
  769. arg = string.replace(arg, slash, slash+slash)
  770. for c in special:
  771. arg = string.replace(arg, c, slash+c)
  772. if re_space.search(arg):
  773. arg = '"' + arg + '"'
  774. return arg
  775. else:
  776. # Windows does not allow special characters in file names
  777. # anyway, so no need for an escape function, we will just quote
  778. # the arg.
  779. def escape(self, arg):
  780. if re_space.search(arg):
  781. arg = '"' + arg + '"'
  782. return arg
  783. def canonicalize(self, path):
  784. if is_List(path):
  785. path = apply(os.path.join, tuple(path))
  786. if not os.path.isabs(path):
  787. path = os.path.join(self.workdir, path)
  788. return path
  789. def chmod(self, path, mode):
  790. """Changes permissions on the specified file or directory
  791. path name."""
  792. path = self.canonicalize(path)
  793. os.chmod(path, mode)
  794. def cleanup(self, condition = None):
  795. """Removes any temporary working directories for the specified
  796. TestCmd environment. If the environment variable PRESERVE was
  797. set when the TestCmd environment was created, temporary working
  798. directories are not removed. If any of the environment variables
  799. PRESERVE_PASS, PRESERVE_FAIL, or PRESERVE_NO_RESULT were set
  800. when the TestCmd environment was created, then temporary working
  801. directories are not removed if the test passed, failed, or had
  802. no result, respectively. Temporary working directories are also
  803. preserved for conditions specified via the preserve method.
  804. Typically, this method is not called directly, but is used when
  805. the script exits to clean up temporary working directories as
  806. appropriate for the exit status.
  807. """
  808. if not self._dirlist:
  809. return
  810. os.chdir(self._cwd)
  811. self.workdir = None
  812. if condition is None:
  813. condition = self.condition
  814. if self._preserve[condition]:
  815. for dir in self._dirlist:
  816. print "Preserved directory", dir
  817. else:
  818. list = self._dirlist[:]
  819. list.reverse()
  820. for dir in list:
  821. self.writable(dir, 1)
  822. shutil.rmtree(dir, ignore_errors = 1)
  823. self._dirlist = []
  824. try:
  825. global _Cleanup
  826. _Cleanup.remove(self)
  827. except (AttributeError, ValueError):
  828. pass
  829. def command_args(self, program = None,
  830. interpreter = None,
  831. arguments = None):
  832. if program:
  833. if type(program) == type('') and not os.path.isabs(program):
  834. program = os.path.join(self._cwd, program)
  835. else:
  836. program = self.program
  837. if not interpreter:
  838. interpreter = self.interpreter
  839. if not type(program) in [type([]), type(())]:
  840. program = [program]
  841. cmd = list(program)
  842. if interpreter:
  843. if not type(interpreter) in [type([]), type(())]:
  844. interpreter = [interpreter]
  845. cmd = list(interpreter) + cmd
  846. if arguments:
  847. if type(arguments) == type(''):
  848. arguments = string.split(arguments)
  849. cmd.extend(arguments)
  850. return cmd
  851. def description_set(self, description):
  852. """Set the description of the functionality being tested.
  853. """
  854. self.description = description
  855. try:
  856. difflib
  857. except NameError:
  858. def diff(self, a, b, name, *args, **kw):
  859. print self.banner('Expected %s' % name)
  860. print a
  861. print self.banner('Actual %s' % name)
  862. print b
  863. else:
  864. def diff(self, a, b, name, *args, **kw):
  865. print self.banner(name)
  866. args = (a.splitlines(), b.splitlines()) + args
  867. lines = apply(self.diff_function, args, kw)
  868. for l in lines:
  869. print l
  870. def fail_test(self, condition = 1, function = None, skip = 0):
  871. """Cause the test to fail.
  872. """
  873. if not condition:
  874. return
  875. self.condition = 'fail_test'
  876. fail_test(self = self,
  877. condition = condition,
  878. function = function,
  879. skip = skip)
  880. def interpreter_set(self, interpreter):
  881. """Set the program to be used to interpret the program
  882. under test as a script.
  883. """
  884. self.interpreter = interpreter
  885. def match(self, lines, matches):
  886. """Compare actual and expected file contents.
  887. """
  888. return self.match_function(lines, matches)
  889. def match_exact(self, lines, matches):
  890. """Compare actual and expected file contents.
  891. """
  892. return match_exact(lines, matches)
  893. def match_re(self, lines, res):
  894. """Compare actual and expected file contents.
  895. """
  896. return match_re(lines, res)
  897. def match_re_dotall(self, lines, res):
  898. """Compare actual and expected file contents.
  899. """
  900. return match_re_dotall(lines, res)
  901. def no_result(self, condition = 1, function = None, skip = 0):
  902. """Report that the test could not be run.
  903. """
  904. if not condition:
  905. return
  906. self.condition = 'no_result'
  907. no_result(self = self,
  908. condition = condition,
  909. function = function,
  910. skip = skip)
  911. def pass_test(self, condition = 1, function = None):
  912. """Cause the test to pass.
  913. """
  914. if not condition:
  915. return
  916. self.condition = 'pass_test'
  917. pass_test(self = self, condition = condition, function = function)
  918. def preserve(self, *conditions):
  919. """Arrange for the temporary working directories for the
  920. specified TestCmd environment to be preserved for one or more
  921. conditions. If no conditions are specified, arranges for
  922. the temporary working directories to be preserved for all
  923. conditions.
  924. """
  925. if conditions is ():
  926. conditions = ('pass_test', 'fail_test', 'no_result')
  927. for cond in conditions:
  928. self._preserve[cond] = 1
  929. def program_set(self, program):
  930. """Set the executable program or script to be tested.
  931. """
  932. if program and not os.path.isabs(program):
  933. program = os.path.join(self._cwd, program)
  934. self.program = program
  935. def read(self, file, mode = 'rb'):
  936. """Reads and returns the contents of the specified file name.
  937. The file name may be a list, in which case the elements are
  938. concatenated with the os.path.join() method. The file is
  939. assumed to be under the temporary working directory unless it
  940. is an absolute path name. The I/O mode for the file may
  941. be specified; it must begin with an 'r'. The default is
  942. 'rb' (binary read).
  943. """
  944. file = self.canonicalize(file)
  945. if mode[0] != 'r':
  946. raise ValueError, "mode must begin with 'r'"
  947. with open(file, mode) as f:
  948. result = f.read()
  949. return result
  950. def rmdir(self, dir):
  951. """Removes the specified dir name.
  952. The dir name may be a list, in which case the elements are
  953. concatenated with the os.path.join() method. The dir is
  954. assumed to be under the temporary working directory unless it
  955. is an absolute path name.
  956. The dir must be empty.
  957. """
  958. dir = self.canonicalize(dir)
  959. os.rmdir(dir)
  960. def start(self, program = None,
  961. interpreter = None,
  962. arguments = None,
  963. universal_newlines = None,
  964. **kw):
  965. """
  966. Starts a program or script for the test environment.
  967. The specified program will have the original directory
  968. prepended unless it is enclosed in a [list].
  969. """
  970. cmd = self.command_args(program, interpreter, arguments)
  971. cmd_string = string.join(map(self.escape, cmd), ' ')
  972. if self.verbose:
  973. sys.stderr.write(cmd_string + "\n")
  974. if universal_newlines is None:
  975. universal_newlines = self.universal_newlines
  976. # On Windows, if we make stdin a pipe when we plan to send
  977. # no input, and the test program exits before
  978. # Popen calls msvcrt.open_osfhandle, that call will fail.
  979. # So don't use a pipe for stdin if we don't need one.
  980. stdin = kw.get('stdin', None)
  981. if stdin is not None:
  982. stdin = subprocess.PIPE
  983. combine = kw.get('combine', self.combine)
  984. if combine:
  985. stderr_value = subprocess.STDOUT
  986. else:
  987. stderr_value = subprocess.PIPE
  988. return Popen(cmd,
  989. stdin=stdin,
  990. stdout=subprocess.PIPE,
  991. stderr=stderr_value,
  992. universal_newlines=universal_newlines)
  993. def finish(self, popen, **kw):
  994. """
  995. Finishes and waits for the process being run under control of
  996. the specified popen argument, recording the exit status,
  997. standard output and error output.
  998. """
  999. popen.stdin.close()
  1000. self.status = popen.wait()
  1001. if not self.status:
  1002. self.status = 0
  1003. self._stdout.append(popen.stdout.read())
  1004. if popen.stderr:
  1005. stderr = popen.stderr.read()
  1006. else:
  1007. stderr = ''
  1008. self._stderr.append(stderr)
  1009. def run(self, program = None,
  1010. interpreter = None,
  1011. arguments = None,
  1012. chdir = None,
  1013. stdin = None,
  1014. universal_newlines = None):
  1015. """Runs a test of the program or script for the test
  1016. environment. Standard output and error output are saved for
  1017. future retrieval via the stdout() and stderr() methods.
  1018. The specified program will have the original directory
  1019. prepended unless it is enclosed in a [list].
  1020. """
  1021. if chdir:
  1022. oldcwd = os.getcwd()
  1023. if not os.path.isabs(chdir):
  1024. chdir = os.path.join(self.workpath(chdir))
  1025. if self.verbose:
  1026. sys.stderr.write("chdir(" + chdir + ")\n")
  1027. os.chdir(chdir)
  1028. p = self.start(program,
  1029. interpreter,
  1030. arguments,
  1031. universal_newlines,
  1032. stdin=stdin)
  1033. if stdin:
  1034. if is_List(stdin):
  1035. for line in stdin:
  1036. p.stdin.write(line)
  1037. else:
  1038. p.stdin.write(stdin)
  1039. p.stdin.close()
  1040. out = p.stdout.read()
  1041. if p.stderr is None:
  1042. err = ''
  1043. else:
  1044. err = p.stderr.read()
  1045. try:
  1046. close_output = p.close_output
  1047. except AttributeError:
  1048. p.stdout.close()
  1049. if not p.stderr is None:
  1050. p.stderr.close()
  1051. else:
  1052. close_output()
  1053. self._stdout.append(out)
  1054. self._stderr.append(err)
  1055. self.status = p.wait()
  1056. if not self.status:
  1057. self.status = 0
  1058. if chdir:
  1059. os.chdir(oldcwd)
  1060. if self.verbose >= 2:
  1061. write = sys.stdout.write
  1062. write('============ STATUS: %d\n' % self.status)
  1063. out = self.stdout()
  1064. if out or self.verbose >= 3:
  1065. write('============ BEGIN STDOUT (len=%d):\n' % len(out))
  1066. write(out)
  1067. write('============ END STDOUT\n')
  1068. err = self.stderr()
  1069. if err or self.verbose >= 3:
  1070. write('============ BEGIN STDERR (len=%d)\n' % len(err))
  1071. write(err)
  1072. write('============ END STDERR\n')
  1073. def sleep(self, seconds = default_sleep_seconds):
  1074. """Sleeps at least the specified number of seconds. If no
  1075. number is specified, sleeps at least the minimum number of
  1076. seconds necessary to advance file time stamps on the current
  1077. system. Sleeping more seconds is all right.
  1078. """
  1079. time.sleep(seconds)
  1080. def stderr(self, run = None):
  1081. """Returns the error output from the specified run number.
  1082. If there is no specified run number, then returns the error
  1083. output of the last run. If the run number is less than zero,
  1084. then returns the error output from that many runs back from the
  1085. current run.
  1086. """
  1087. if not run:
  1088. run = len(self._stderr)
  1089. elif run < 0:
  1090. run = len(self._stderr) + run
  1091. run = run - 1
  1092. return self._stderr[run]
  1093. def stdout(self, run = None):
  1094. """Returns the standard output from the specified run number.
  1095. If there is no specified run number, then returns the standard
  1096. output of the last run. If the run number is less than zero,
  1097. then returns the standard output from that many runs back from
  1098. the current run.
  1099. """
  1100. if not run:
  1101. run = len(self._stdout)
  1102. elif run < 0:
  1103. run = len(self._stdout) + run
  1104. run = run - 1
  1105. return self._stdout[run]
  1106. def subdir(self, *subdirs):
  1107. """Create new subdirectories under the temporary working
  1108. directory, one for each argument. An argument may be a list,
  1109. in which case the list elements are concatenated using the
  1110. os.path.join() method. Subdirectories multiple levels deep
  1111. must be created using a separate argument for each level:
  1112. test.subdir('sub', ['sub', 'dir'], ['sub', 'dir', 'ectory'])
  1113. Returns the number of subdirectories actually created.
  1114. """
  1115. count = 0
  1116. for sub in subdirs:
  1117. if sub is None:
  1118. continue
  1119. if is_List(sub):
  1120. sub = apply(os.path.join, tuple(sub))
  1121. new = os.path.join(self.workdir, sub)
  1122. try:
  1123. os.mkdir(new)
  1124. except OSError:
  1125. pass
  1126. else:
  1127. count = count + 1
  1128. return count
  1129. def symlink(self, target, link):
  1130. """Creates a symlink to the specified target.
  1131. The link name may be a list, in which case the elements are
  1132. concatenated with the os.path.join() method. The link is
  1133. assumed to be under the temporary working directory unless it
  1134. is an absolute path name. The target is *not* assumed to be
  1135. under the temporary working directory.
  1136. """
  1137. link = self.canonicalize(link)
  1138. os.symlink(target, link)
  1139. def tempdir(self, path=None):
  1140. """Creates a temporary directory.
  1141. A unique directory name is generated if no path name is specified.
  1142. The directory is created, and will be removed when the TestCmd
  1143. object is destroyed.
  1144. """
  1145. if path is None:
  1146. try:
  1147. path = tempfile.mktemp(prefix=tempfile.template)
  1148. except TypeError:
  1149. path = tempfile.mktemp()
  1150. os.mkdir(path)
  1151. # Symlinks in the path will report things
  1152. # differently from os.getcwd(), so chdir there
  1153. # and back to fetch the canonical path.
  1154. cwd = os.getcwd()
  1155. try:
  1156. os.chdir(path)
  1157. path = os.getcwd()
  1158. finally:
  1159. os.chdir(cwd)
  1160. # Uppercase the drive letter since the case of drive
  1161. # letters is pretty much random on win32:
  1162. drive,rest = os.path.splitdrive(path)
  1163. if drive:
  1164. path = string.upper(drive) + rest
  1165. #
  1166. self._dirlist.append(path)
  1167. global _Cleanup
  1168. try:
  1169. _Cleanup.index(self)
  1170. except ValueError:
  1171. _Cleanup.append(self)
  1172. return path
  1173. def touch(self, path, mtime=None):
  1174. """Updates the modification time on the specified file or
  1175. directory path name. The default is to update to the
  1176. current time if no explicit modification time is specified.
  1177. """
  1178. path = self.canonicalize(path)
  1179. atime = os.path.getatime(path)
  1180. if mtime is None:
  1181. mtime = time.time()
  1182. os.utime(path, (atime, mtime))
  1183. def unlink(self, file):
  1184. """Unlinks the specified file name.
  1185. The file name may be a list, in which case the elements are
  1186. concatenated with the os.path.join() method. The file is
  1187. assumed to be under the temporary working directory unless it
  1188. is an absolute path name.
  1189. """
  1190. file = self.canonicalize(file)
  1191. os.unlink(file)
  1192. def verbose_set(self, verbose):
  1193. """Set the verbose level.
  1194. """
  1195. self.verbose = verbose
  1196. def where_is(self, file, path=None, pathext=None):
  1197. """Find an executable file.
  1198. """
  1199. if is_List(file):
  1200. file = apply(os.path.join, tuple(file))
  1201. if not os.path.isabs(file):
  1202. file = where_is(file, path, pathext)
  1203. return file
  1204. def workdir_set(self, path):
  1205. """Creates a temporary working directory with the specified
  1206. path name. If the path is a null string (''), a unique
  1207. directory name is created.
  1208. """
  1209. if (path != None):
  1210. if path == '':
  1211. path = None
  1212. path = self.tempdir(path)
  1213. self.workdir = path
  1214. def workpath(self, *args):
  1215. """Returns the absolute path name to a subdirectory or file
  1216. within the current temporary working directory. Concatenates
  1217. the temporary working directory name with the specified
  1218. arguments using the os.path.join() method.
  1219. """
  1220. return apply(os.path.join, (self.workdir,) + tuple(args))
  1221. def readable(self, top, read=1):
  1222. """Make the specified directory tree readable (read == 1)
  1223. or not (read == None).
  1224. This method has no effect on Windows systems, which use a
  1225. completely different mechanism to control file readability.
  1226. """
  1227. if sys.platform == 'win32':
  1228. return
  1229. if read:
  1230. def do_chmod(fname):
  1231. try: st = os.stat(fname)
  1232. except OSError: pass
  1233. else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]|stat.S_IREAD))
  1234. else:
  1235. def do_chmod(fname):
  1236. try: st = os.stat(fname)
  1237. except OSError: pass
  1238. else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]&~stat.S_IREAD))
  1239. if os.path.isfile(top):
  1240. # If it's a file, that's easy, just chmod it.
  1241. do_chmod(top)
  1242. elif read:
  1243. # It's a directory and we're trying to turn on read
  1244. # permission, so it's also pretty easy, just chmod the
  1245. # directory and then chmod every entry on our walk down the
  1246. # tree. Because os.path.walk() is top-down, we'll enable
  1247. # read permission on any directories that have it disabled
  1248. # before os.path.walk() tries to list their contents.
  1249. do_chmod(top)
  1250. def chmod_entries(arg, dirname, names, do_chmod=do_chmod):
  1251. for n in names:
  1252. do_chmod(os.path.join(dirname, n))
  1253. os.path.walk(top, chmod_entries, None)
  1254. else:
  1255. # It's a directory and we're trying to turn off read
  1256. # permission, which means we have to chmod the directoreis
  1257. # in the tree bottom-up, lest disabling read permission from
  1258. # the top down get in the way of being able to get at lower
  1259. # parts of the tree. But os.path.walk() visits things top
  1260. # down, so we just use an object to collect a list of all
  1261. # of the entries in the tree, reverse the list, and then
  1262. # chmod the reversed (bottom-up) list.
  1263. col = Collector(top)
  1264. os.path.walk(top, col, None)
  1265. col.entries.reverse()
  1266. for d in col.entries: do_chmod(d)
  1267. def writable(self, top, write=1):
  1268. """Make the specified directory tree writable (write == 1)
  1269. or not (write == None).
  1270. """
  1271. if sys.platform == 'win32':
  1272. if write:
  1273. def do_chmod(fname):
  1274. try: os.chmod(fname, stat.S_IWRITE)
  1275. except OSError: pass
  1276. else:
  1277. def do_chmod(fname):
  1278. try: os.chmod(fname, stat.S_IREAD)
  1279. except OSError: pass
  1280. else:
  1281. if write:
  1282. def do_chmod(fname):
  1283. try: st = os.stat(fname)
  1284. except OSError: pass
  1285. else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]|0200))
  1286. else:
  1287. def do_chmod(fname):
  1288. try: st = os.stat(fname)
  1289. except OSError: pass
  1290. else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]&~0200))
  1291. if os.path.isfile(top):
  1292. do_chmod(top)
  1293. else:
  1294. col = Collector(top)
  1295. os.path.walk(top, col, None)
  1296. for d in col.entries: do_chmod(d)
  1297. def executable(self, top, execute=1):
  1298. """Make the specified directory tree executable (execute == 1)
  1299. or not (execute == None).
  1300. This method has no effect on Windows systems, which use a
  1301. completely different mechanism to control file executability.
  1302. """
  1303. if sys.platform == 'win32':
  1304. return
  1305. if execute:
  1306. def do_chmod(fname):
  1307. try: st = os.stat(fname)
  1308. except OSError: pass
  1309. else: os.chmod(fname, stat.S_IMODE(st[stat.ST_MODE]|stat.S_IEXEC))
  1310. else:
  1311. def do_chmod(fname):
  1312. try: st = os.stat(fname)
  1313. except OSError

Large files files are truncated, but you can click here to view the full file