📄 testcmd.py
字号:
""" if not condition: return self.condition = 'no_result' no_result(self = self, condition = condition, function = function, skip = skip) def pass_test(self, condition=True, function=None): """Cause the test to pass. """ if not condition: return self.condition = 'pass_test' pass_test(self = self, condition = condition, function = function) def preserve(self, *conditions): """Arrange for the temporary working directories for the specified TestCmd environment to be preserved for one or more conditions. If no conditions are specified, arranges for the temporary working directories to be preserved for all conditions. """ if conditions is (): conditions = ('pass_test', 'fail_test', 'no_result') for cond in conditions: self._preserve[cond] = 1 def program_set(self, program): """Set the executable program or script to be tested. """ if program and program[0] and not os.path.isabs(program[0]): program[0] = os.path.join(self._cwd, program[0]) self.program = program def read(self, file, mode='rb'): """Reads and returns the contents of the specified file name. The file name may be a list, in which case the elements are concatenated with the os.path.join() method. The file is assumed to be under the temporary working directory unless it is an absolute path name. The I/O mode for the file may be specified; it must begin with an 'r'. The default is 'rb' (binary read). """ if type(file) is ListType: file = apply(os.path.join, tuple(file)) if not os.path.isabs(file): file = os.path.join(self.workdir, file) if mode[0] != 'r': raise ValueError, "mode must begin with 'r'" return open(file, mode).read() def run(self, program=None, arguments=None, chdir=None, stdin=None): """Runs a test of the program or script for the test environment. Standard output and error output are saved for future retrieval via the stdout() and stderr() methods. """ if chdir: oldcwd = os.getcwd() if not os.path.isabs(chdir): chdir = os.path.join(self.workpath(chdir)) if self.verbose: sys.stderr.write("chdir(" + chdir + ")\n") os.chdir(chdir) cmd = [] if program and program[0]: if program[0] != self.program[0] and not os.path.isabs(program[0]): program[0] = os.path.join(self._cwd, program[0]) cmd += program else: cmd += self.program if arguments: cmd += arguments.split(" ") if self.verbose: sys.stderr.write(join(cmd, " ") + "\n") try: p = popen2.Popen3(cmd, 1) except AttributeError: # We end up here in case the popen2.Popen3 class is not available # (e.g. on Windows). We will be using the os.popen3() Python API # which takes a string parameter and so needs its executable quoted # in case its name contains spaces. cmd[0] = '"' + cmd[0] + '"' command_string = join(cmd, " ") if ( os.name == 'nt' ): # This is a workaround for a longstanding Python bug on Windows # when using os.popen(), os.system() and similar functions to # execute a command containing quote characters. The bug seems # to be related to the quote stripping functionality used by the # Windows cmd.exe interpreter when its /S is not specified. # # Cleaned up quote from the cmd.exe help screen as displayed on # Windows XP SP2: # # 1. If all of the following conditions are met, then quote # characters on the command line are preserved: # # - no /S switch # - exactly two quote characters # - no special characters between the two quote # characters, where special is one of: &<>()@^| # - there are one or more whitespace characters between # the two quote characters # - the string between the two quote characters is the # name of an executable file. # # 2. Otherwise, old behavior is to see if the first character # is a quote character and if so, strip the leading # character and remove the last quote character on the # command line, preserving any text after the last quote # character. # # This causes some commands containing quotes not to be executed # correctly. For example: # # "\Long folder name\aaa.exe" --name="Jurko" --no-surname # # would get its outermost quotes stripped and would be executed # as: # # \Long folder name\aaa.exe" --name="Jurko --no-surname # # which would report an error about '\Long' not being a valid # command. # # cmd.exe help seems to indicate it would be enough to add an # extra space character in front of the command to avoid this # but this does not work, most likely due to the shell first # stripping all leading whitespace characters from the command. # # Solution implemented here is to quote the whole command in # case it contains any quote characters. Note thought this will # not work correctly should Python ever fix this bug. # (01.05.2008.) (Jurko) if command_string.find('"') != -1: command_string = '"' + command_string + '"' (tochild, fromchild, childerr) = os.popen3(command_string) if stdin: if type(stdin) is ListType: for line in stdin: tochild.write(line) else: tochild.write(stdin) tochild.close() self._stdout.append(fromchild.read()) self._stderr.append(childerr.read()) fromchild.close() self.status = childerr.close() if not self.status: self.status = 0 except: raise else: if stdin: if type(stdin) is ListType: for line in stdin: p.tochild.write(line) else: p.tochild.write(stdin) p.tochild.close() self._stdout.append(p.fromchild.read()) self._stderr.append(p.childerr.read()) self.status = p.wait() if self.verbose: sys.stdout.write(self._stdout[-1]) sys.stderr.write(self._stderr[-1]) if chdir: os.chdir(oldcwd) def stderr(self, run=None): """Returns the error output from the specified run number. If there is no specified run number, then returns the error output of the last run. If the run number is less than zero, then returns the error output from that many runs back from the current run. """ if not run: run = len(self._stderr) elif run < 0: run = len(self._stderr) + run run = run - 1 if (run < 0): return '' return self._stderr[run] def stdout(self, run=None): """Returns the standard output from the specified run number. If there is no specified run number, then returns the standard output of the last run. If the run number is less than zero, then returns the standard output from that many runs back from the current run. """ if not run: run = len(self._stdout) elif run < 0: run = len(self._stdout) + run run = run - 1 if (run < 0): return '' return self._stdout[run] def subdir(self, *subdirs): """Create new subdirectories under the temporary working directory, one for each argument. An argument may be a list, in which case the list elements are concatenated using the os.path.join() method. Subdirectories multiple levels deep must be created using a separate argument for each level: test.subdir('sub', ['sub', 'dir'], ['sub', 'dir', 'ectory']) Returns the number of subdirectories actually created. """ count = 0 for sub in subdirs: if sub is None: continue if type(sub) is ListType: sub = apply(os.path.join, tuple(sub)) new = os.path.join(self.workdir, sub) try: os.mkdir(new) except: pass else: count = count + 1 return count def unlink (self, file): """Unlinks the specified file name. The file name may be a list, in which case the elements are concatenated using the os.path.join() method. The file is assumed to be under the temporary working directory unless it is an absolute path name. """ if type(file) is ListType: file = apply(os.path.join, tuple(file)) if not os.path.isabs(file): file = os.path.join(self.workdir, file) os.unlink(file) def verbose_set(self, verbose): """Set the verbose level. """ self.verbose = verbose def workdir_set(self, path): """Creates a temporary working directory with the specified path name. If the path is a null string (''), a unique directory name is created. """ if os.path.isabs(path): self.workdir = path else: if (path != None): if path == '': path = tempfile.mktemp() if path != None: os.mkdir(path) self._dirlist.append(path) global _Cleanup try: _Cleanup.index(self) except ValueError: _Cleanup.append(self) # We'd like to set self.workdir like this: # self.workdir = path # But symlinks in the path will report things differently from # os.getcwd(), so chdir there and back to fetch the canonical # path. cwd = os.getcwd() os.chdir(path) self.workdir = os.getcwd() os.chdir(cwd) else: self.workdir = None def workpath(self, *args): """Returns the absolute path name to a subdirectory or file within the current temporary working directory. Concatenates the temporary working directory name with the specified arguments using the os.path.join() method. """ return apply(os.path.join, (self.workdir,) + tuple(args)) def writable(self, top, write): """Make the specified directory tree writable (write == 1) or not (write == None). """ def _walk_chmod(arg, dirname, names): st = os.stat(dirname) os.chmod(dirname, arg(st[stat.ST_MODE])) for name in names: n = os.path.join(dirname, name) st = os.stat(n) os.chmod(n, arg(st[stat.ST_MODE])) def _mode_writable(mode): return stat.S_IMODE(mode|0200) def _mode_non_writable(mode): return stat.S_IMODE(mode&~0200) if write: f = _mode_writable else: f = _mode_non_writable try: os.path.walk(top, _walk_chmod, f) except: pass # Ignore any problems changing modes. def write(self, file, content, mode='wb'): """Writes the specified content text (second argument) to the specified file name (first argument). The file name may be a list, in which case the elements are concatenated using the os.path.join() method. The file is created under the temporary working directory. Any subdirectories in the path must already exist. The I/O mode for the file may be specified; it must begin with a 'w'. The default is 'wb' (binary write). """ if type(file) is ListType: file = apply(os.path.join, tuple(file)) if not os.path.isabs(file): file = os.path.join(self.workdir, file) if mode[0] != 'w': raise ValueError, "mode must begin with 'w'" open(file, mode).write(content)
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -