rem
stringlengths 0
322k
| add
stringlengths 0
2.05M
| context
stringlengths 8
228k
|
---|---|---|
os.mkdir(dst)
|
os.makedirs(dst) copystat(src, dst)
|
def copytree(src, dst, symlinks=False): """Recursively copy a directory tree using copy2(). The destination directory must not already exist. If exception(s) occur, an Error is raised with a list of reasons. If the optional symlinks flag is true, symbolic links in the source tree result in symbolic links in the destination tree; if it is false, the contents of the files pointed to by symbolic links are copied. XXX Consider this example code rather than the ultimate tool. """ names = os.listdir(src) os.mkdir(dst) errors = [] for name in names: srcname = os.path.join(src, name) dstname = os.path.join(dst, name) try: if symlinks and os.path.islink(srcname): linkto = os.readlink(srcname) os.symlink(linkto, dstname) elif os.path.isdir(srcname): copytree(srcname, dstname, symlinks) else: copy2(srcname, dstname) # XXX What about devices, sockets etc.? except (IOError, os.error), why: errors.append((srcname, dstname, why)) if errors: raise Error, errors
|
dupDB.associate(secDB, lambda a, b: a+b)
|
def f(a,b): return a+b dupDB.associate(secDB, f)
|
def test00_associateDBError(self): if verbose: print '\n', '-=' * 30 print "Running %s.test00_associateDBError..." % \ self.__class__.__name__
|
self.primary.open(self.filename, "primary", self.dbtype,
|
if db.version() >= (4, 1): self.primary.open(self.filename, "primary", self.dbtype,
|
def createDB(self, txn=None):
|
self.getDB().associate(self.secDB, self.getGenre, txn=txn)
|
if db.version() >= (4,1): self.getDB().associate(self.secDB, self.getGenre, txn=txn) else: self.getDB().associate(self.secDB, self.getGenre)
|
def test13_associate_in_transaction(self): if verbose: print '\n', '-=' * 30 print "Running %s.test13_associateAutoCommit..." % \ self.__class__.__name__
|
suite.addTest(unittest.makeSuite(AssociateBTreeTxnTestCase))
|
if db.version() >= (4, 1): suite.addTest(unittest.makeSuite(AssociateBTreeTxnTestCase))
|
def test_suite(): suite = unittest.TestSuite() if db.version() >= (3, 3, 11): suite.addTest(unittest.makeSuite(AssociateErrorTestCase)) suite.addTest(unittest.makeSuite(AssociateHashTestCase)) suite.addTest(unittest.makeSuite(AssociateBTreeTestCase)) suite.addTest(unittest.makeSuite(AssociateRecnoTestCase)) suite.addTest(unittest.makeSuite(AssociateBTreeTxnTestCase)) suite.addTest(unittest.makeSuite(ShelveAssociateHashTestCase)) suite.addTest(unittest.makeSuite(ShelveAssociateBTreeTestCase)) suite.addTest(unittest.makeSuite(ShelveAssociateRecnoTestCase)) if have_threads: suite.addTest(unittest.makeSuite(ThreadedAssociateHashTestCase)) suite.addTest(unittest.makeSuite(ThreadedAssociateBTreeTestCase)) suite.addTest(unittest.makeSuite(ThreadedAssociateRecnoTestCase)) return suite
|
def err(args):
|
def err(*args):
|
def err(args): savestdout = sys.stdout try: sys.stdout = sys.stderr for i in args: print i, print finally: sys.stdout = savestdout
|
e = 'Function', func, 'too complicated:' err(e + (a_type, a_mode, a_factor, a_sub))
|
err('Function', func, 'too complicated:', a_type, a_mode, a_factor, a_sub)
|
def generate(type, func, database): # # Check that we can handle this case: # no variable size reply arrays yet # n_in_args = 0 n_out_args = 0 # for a_type, a_mode, a_factor, a_sub in database: if a_mode == 's': n_in_args = n_in_args + 1 elif a_mode == 'r': n_out_args = n_out_args + 1 else: # Can't happen raise arg_error, ('bad a_mode', a_mode) if (a_mode == 'r' and a_sub) or a_sub == 'retval': e = 'Function', func, 'too complicated:' err(e + (a_type, a_mode, a_factor, a_sub)) print '/* XXX Too complicated to generate code for */' return # functions.append(func) # # Stub header # print print 'static object *' print 'gl_' + func + '(self, args)' print '\tobject *self;' print '\tobject *args;' print '{' # # Declare return value if any # if type <> 'void': print '\t' + type, 'retval;' # # Declare arguments # for i in range(len(database)): a_type, a_mode, a_factor, a_sub = database[i] print '\t' + a_type, brac = ket = '' if a_sub and not isnum(a_sub): if a_factor: brac = '(' ket = ')' print brac + '*', print 'arg' + `i+1` + ket, if a_sub and isnum(a_sub): print '[', a_sub, ']', if a_factor: print '[', a_factor, ']', print ';' # # Find input arguments derived from array sizes # for i in range(len(database)): a_type, a_mode, a_factor, a_sub = database[i] if a_mode == 's' and a_sub[:3] == 'arg' and isnum(a_sub[3:]): # Sending a variable-length array n = eval(a_sub[3:]) if 1 <= n <= len(database): b_type, b_mode, b_factor, b_sub = database[n-1] if b_mode == 's': database[n-1] = b_type, 'i', a_factor, `i` n_in_args = n_in_args - 1 # # Assign argument positions in the Python argument list # in_pos = [] i_in = 0 for i in range(len(database)): a_type, a_mode, a_factor, a_sub = database[i] if a_mode == 's': in_pos.append(i_in) i_in = i_in + 1 else: in_pos.append(-1) # # Get input arguments # for i in range(len(database)): a_type, a_mode, a_factor, a_sub = database[i] if a_type[:9] == 'unsigned ': xtype = a_type[9:] else: xtype = a_type if a_mode == 'i': # # Implicit argument; # a_factor is divisor if present, # a_sub indicates which arg (`database index`) # j = eval(a_sub) print '\tif', print '(!geti' + xtype + 'arraysize(args,', print `n_in_args` + ',', print `in_pos[j]` + ',', if xtype <> a_type: print '('+xtype+' *)', print '&arg' + `i+1` + '))' print '\t\treturn NULL;' if a_factor: print '\targ' + `i+1`, print '= arg' + `i+1`, print '/', a_factor + ';' elif a_mode == 's': if a_sub and not isnum(a_sub): # Allocate memory for varsize array print '\tif ((arg' + `i+1`, '=', if a_factor: print '('+a_type+'(*)['+a_factor+'])', print 'NEW(' + a_type, ',', if a_factor: print a_factor, '*', print a_sub, ')) == NULL)' print '\t\treturn err_nomem();' print '\tif', if a_factor or a_sub: # Get a fixed-size array array print '(!geti' + xtype + 'array(args,', print `n_in_args` + ',', print `in_pos[i]` + ',', if a_factor: print a_factor, if a_factor and a_sub: print '*', if a_sub: print a_sub, print ',', if (a_sub and a_factor) or xtype <> a_type: print '('+xtype+' *)', print 'arg' + `i+1` + '))' else: # Get a simple variable print '(!geti' + xtype + 'arg(args,', print `n_in_args` + ',', print `in_pos[i]` + ',', if xtype <> a_type: print '('+xtype+' *)', print '&arg' + `i+1` + '))' print '\t\treturn NULL;' # # Begin of function call # if type <> 'void': print '\tretval =', func + '(', else: print '\t' + func + '(', # # Argument list # for i in range(len(database)): if i > 0: print ',', a_type, a_mode, a_factor, a_sub = database[i] if a_mode == 'r' and not a_factor: print '&', print 'arg' + `i+1`, # # End of function call # print ');' # # Free varsize arrays # for i in range(len(database)): a_type, a_mode, a_factor, a_sub = database[i] if a_mode == 's' and a_sub and not isnum(a_sub): print '\tDEL(arg' + `i+1` + ');' # # Return # if n_out_args: # # Multiple return values -- construct a tuple # if type <> 'void': n_out_args = n_out_args + 1 if n_out_args == 1: for i in range(len(database)): a_type, a_mode, a_factor, a_sub = database[i] if a_mode == 'r': break else: raise arg_error, 'expected r arg not found' print '\treturn', print mkobject(a_type, 'arg' + `i+1`) + ';' else: print '\t{ object *v = newtupleobject(', print n_out_args, ');' print '\t if (v == NULL) return NULL;' i_out = 0 if type <> 'void': print '\t settupleitem(v,', print `i_out` + ',', print mkobject(type, 'retval') + ');' i_out = i_out + 1 for i in range(len(database)): a_type, a_mode, a_factor, a_sub = database[i] if a_mode == 'r': print '\t settupleitem(v,', print `i_out` + ',', s = mkobject(a_type, 'arg' + `i+1`) print s + ');' i_out = i_out + 1 print '\t return v;' print '\t}' else: # # Simple function return # Return None or return value # if type == 'void': print '\tINCREF(None);' print '\treturn None;' else: print '\treturn', mkobject(type, 'retval') + ';' # # Stub body closing brace # print '}'
|
sys.path.append('/ufs/guido/src/video')
|
sys.path.append('/ufs/jack/src/av/video')
|
def help(): print 'Usage: video2rgb [options] [file] ...' print print 'Options:' print '-q : quiet, no informative messages' print '-m : create monochrome (greyscale) image files' print '-f prefix : create image files with names "prefix0000.rgb"' print 'file ... : file(s) to convert; default film.video'
|
m=None
|
m = (None, None)
|
def quoteaddr(addr): """Quote a subset of the email addresses defined by RFC 821. Should be able to handle anything rfc822.parseaddr can handle. """ m=None try: m=rfc822.parseaddr(addr)[1] except AttributeError: pass if not m: #something weird here.. punt -ddm return addr else: return "<%s>" % m
|
if not m:
|
if m == (None, None):
|
def quoteaddr(addr): """Quote a subset of the email addresses defined by RFC 821. Should be able to handle anything rfc822.parseaddr can handle. """ m=None try: m=rfc822.parseaddr(addr)[1] except AttributeError: pass if not m: #something weird here.. punt -ddm return addr else: return "<%s>" % m
|
return addr
|
return "<%s>" % addr
|
def quoteaddr(addr): """Quote a subset of the email addresses defined by RFC 821. Should be able to handle anything rfc822.parseaddr can handle. """ m=None try: m=rfc822.parseaddr(addr)[1] except AttributeError: pass if not m: #something weird here.. punt -ddm return addr else: return "<%s>" % m
|
if kwargs.has_key('command')
|
if kwargs.has_key('command'):
|
def __init__(self, master, variable, value, *values, **kwargs): kw = {"borderwidth": 2, "textvariable": variable, "indicatoron": 1, "relief": RAISED, "anchor": "c", "highlightthickness": 2} Widget.__init__(self, master, "menubutton", kw) self.widgetName = 'tk_optionMenu' menu = self.__menu = Menu(self, name="menu", tearoff=0) self.menuname = menu._w # 'command' is the only supported keyword callback = kwargs.get('command') if kwargs.has_key('command') del kwargs['command'] if kwargs: raise TclError, 'unknown option -'+kwargs.keys()[0] menu.add_command(label=value, command=_setit(variable, value, callback)) for v in values: menu.add_command(label=v, command=_setit(variable, v, callback)) self["menu"] = menu
|
s = marshal.dumps(f)
|
s = marshal.dumps(f, 2)
|
def test_floats(self): # Test a few floats small = 1e-25 n = sys.maxint * 3.7e250 while n > small: for expected in (-n, n): f = float(expected) s = marshal.dumps(f) got = marshal.loads(s) self.assertEqual(f, got) marshal.dump(f, file(test_support.TESTFN, "wb")) got = marshal.load(file(test_support.TESTFN, "rb")) self.assertEqual(f, got) n /= 123.4567
|
fp = open(MOFILE, 'w')
|
fp = open(MOFILE, 'wb')
|
def setup(): os.makedirs(LOCALEDIR) fp = open(MOFILE, 'w') fp.write(base64.decodestring(GNU_MO_DATA)) fp.close()
|
packkey(ae, key, value)
|
ae.AEPutAttributeDesc(key, pack(value))
|
def packevent(ae, parameters = {}, attributes = {}): for key, value in parameters.items(): packkey(ae, key, value) for key, value in attributes.items(): packkey(ae, key, value)
|
arguments[key] = edict[v]
|
arguments[key] = Enum(edict[v])
|
def enumsubst(arguments, key, edict): """Substitute a single enum keyword argument, if it occurs""" if not arguments.has_key(key) or edict is None: return v = arguments[key] ok = edict.values() if edict.has_key(v): arguments[key] = edict[v] elif not v in ok: raise TypeError, 'Unknown enumerator: %s'%v
|
opt_dict[opt] = (filename, parser.get(section,opt))
|
val = parser.get(section,opt) opt = string.replace(opt, '-', '_') opt_dict[opt] = (filename, val)
|
def parse_config_files (self, filenames=None):
|
true if command-line were successfully parsed and we should carry
|
true if command-line was successfully parsed and we should carry
|
def parse_command_line (self): """Parse the setup script's command line, taken from the 'script_args' instance attribute (which defaults to 'sys.argv[1:]' -- see 'setup()' in core.py). This list is first processed for "global options" -- options that set attributes of the Distribution instance. Then, it is alternately scanned for Distutils commands and options for that command. Each new command terminates the options for the previous command. The allowed options for a command are determined by the 'user_options' attribute of the command class -- thus, we have to be able to load command classes in order to parse the command line. Any error in that 'options' attribute raises DistutilsGetoptError; any error on the command-line raises DistutilsArgError. If no Distutils commands were found on the command line, raises DistutilsArgError. Return true if command-line were successfully parsed and we should carry on with executing commands; false if no errors but we shouldn't execute commands (currently, this only happens if user asks for help). """ # We have to parse the command line a bit at a time -- global # options, then the first command, then its options, and so on -- # because each command will be handled by a different class, and # the options that are valid for a particular class aren't known # until we have loaded the command class, which doesn't happen # until we know what the command is.
|
'command_obj' must be a Commnd instance. If 'option_dict' is not
|
'command_obj' must be a Command instance. If 'option_dict' is not
|
def _set_command_options (self, command_obj, option_dict=None): """Set the options for 'command_obj' from 'option_dict'. Basically this means copying elements of a dictionary ('option_dict') to attributes of an instance ('command').
|
if not hasattr(command_obj, option): raise DistutilsOptionError, \ ("error in %s: command '%s' has no such option '%s'") % \ (source, command_name, option) setattr(command_obj, option, value)
|
try: bool_opts = command_obj.boolean_options except AttributeError: bool_opts = [] try: neg_opt = command_obj.negative_opt except AttributeError: neg_opt = {} try: if neg_opt.has_key(option): setattr(command_obj, neg_opt[option], not strtobool(value)) elif option in bool_opts: setattr(command_obj, option, strtobool(value)) elif hasattr(command_obj, option): setattr(command_obj, option, value) else: raise DistutilsOptionError, \ ("error in %s: command '%s' has no such option '%s'" % (source, command_name, option)) except ValueError, msg: raise DistutilsOptionError, msg
|
def _set_command_options (self, command_obj, option_dict=None): """Set the options for 'command_obj' from 'option_dict'. Basically this means copying elements of a dictionary ('option_dict') to attributes of an instance ('command').
|
os.execve(scriptfile, args, env)
|
os.execve(scriptfile, args, os.environ)
|
def run_cgi(self): """Execute a CGI script.""" dir, rest = self.cgi_info i = rest.rfind('?') if i >= 0: rest, query = rest[:i], rest[i+1:] else: query = '' i = rest.find('/') if i >= 0: script, rest = rest[:i], rest[i:] else: script, rest = rest, '' scriptname = dir + '/' + script scriptfile = self.translate_path(scriptname) if not os.path.exists(scriptfile): self.send_error(404, "No such CGI script (%s)" % `scriptname`) return if not os.path.isfile(scriptfile): self.send_error(403, "CGI script is not a plain file (%s)" % `scriptname`) return ispy = self.is_python(scriptname) if not ispy: if not (self.have_fork or self.have_popen2 or self.have_popen3): self.send_error(403, "CGI script is not a Python script (%s)" % `scriptname`) return if not self.is_executable(scriptfile): self.send_error(403, "CGI script is not executable (%s)" % `scriptname`) return
|
self.error("expected name token")
|
self.error("expected name token at %r" % rawdata[declstartpos:declstartpos+20])
|
def _scan_name(self, i, declstartpos): rawdata = self.rawdata n = len(rawdata) if i == n: return None, -1 m = _declname_match(rawdata, i) if m: s = m.group() name = s.strip() if (i + len(s)) == n: return None, -1 # end of buffer return name.lower(), m.end() else: self.updatepos(declstartpos, i) self.error("expected name token")
|
st = os.stat(src) mode = stat.S_IMODE(st[stat.ST_MODE]) os.chmod(dst, mode)
|
if hasattr(os, 'chmod'): st = os.stat(src) mode = stat.S_IMODE(st[stat.ST_MODE]) os.chmod(dst, mode)
|
def copymode(src, dst): """Copy mode bits from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st[stat.ST_MODE]) os.chmod(dst, mode)
|
os.utime(dst, (st[stat.ST_ATIME], st[stat.ST_MTIME])) os.chmod(dst, mode)
|
if hasattr(os, 'utime'): os.utime(dst, (st[stat.ST_ATIME], st[stat.ST_MTIME])) if hasattr(os, 'chmod'): os.chmod(dst, mode)
|
def copystat(src, dst): """Copy all stat info (mode bits, atime and mtime) from src to dst""" st = os.stat(src) mode = stat.S_IMODE(st[stat.ST_MODE]) os.utime(dst, (st[stat.ST_ATIME], st[stat.ST_MTIME])) os.chmod(dst, mode)
|
matches = (['class', name], ['class', name + ':'])
|
pat = re.compile(r'^\s*class\s*' + name + r'\b')
|
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" try: file = open(getsourcefile(object)) except (TypeError, IOError): raise IOError, 'could not get source code' lines = file.readlines() file.close() if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ matches = (['class', name], ['class', name + ':']) for i in range(len(lines)): if string.split(lines[i])[:2] in matches: return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError, 'could not find function definition' lnum = object.co_firstlineno - 1 while lnum > 0: if string.split(lines[lnum])[:1] == ['def']: break lnum = lnum - 1 return lines, lnum
|
if string.split(lines[i])[:2] in matches: return lines, i
|
if pat.match(lines[i]): return lines, i
|
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" try: file = open(getsourcefile(object)) except (TypeError, IOError): raise IOError, 'could not get source code' lines = file.readlines() file.close() if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ matches = (['class', name], ['class', name + ':']) for i in range(len(lines)): if string.split(lines[i])[:2] in matches: return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError, 'could not find function definition' lnum = object.co_firstlineno - 1 while lnum > 0: if string.split(lines[lnum])[:1] == ['def']: break lnum = lnum - 1 return lines, lnum
|
if string.split(lines[lnum])[:1] == ['def']: break
|
if pat.match(lines[lnum]): break
|
def findsource(object): """Return the entire source file and starting line number for an object. The argument may be a module, class, method, function, traceback, frame, or code object. The source code is returned as a list of all the lines in the file and the line number indexes a line in that list. An IOError is raised if the source code cannot be retrieved.""" try: file = open(getsourcefile(object)) except (TypeError, IOError): raise IOError, 'could not get source code' lines = file.readlines() file.close() if ismodule(object): return lines, 0 if isclass(object): name = object.__name__ matches = (['class', name], ['class', name + ':']) for i in range(len(lines)): if string.split(lines[i])[:2] in matches: return lines, i else: raise IOError, 'could not find class definition' if ismethod(object): object = object.im_func if isfunction(object): object = object.func_code if istraceback(object): object = object.tb_frame if isframe(object): object = object.f_code if iscode(object): if not hasattr(object, 'co_firstlineno'): raise IOError, 'could not find function definition' lnum = object.co_firstlineno - 1 while lnum > 0: if string.split(lines[lnum])[:1] == ['def']: break lnum = lnum - 1 return lines, lnum
|
print 'h=',h
|
def getentry(self, which): self._check() if which == 'in': cmd = IN_ENTRY_SENSE elif which == 'out': cmd = OUT_ENTRY_SENSE self.replycmd(cmd) h = self._getnumber(2) print 'h=',h m = self._getnumber(2) print 'm=',m s = self._getnumber(2) print 's=',s f = self._getnumber(2) print 'f=',f return (h, m, s, f)
|
|
print 'm=',m
|
def getentry(self, which): self._check() if which == 'in': cmd = IN_ENTRY_SENSE elif which == 'out': cmd = OUT_ENTRY_SENSE self.replycmd(cmd) h = self._getnumber(2) print 'h=',h m = self._getnumber(2) print 'm=',m s = self._getnumber(2) print 's=',s f = self._getnumber(2) print 'f=',f return (h, m, s, f)
|
|
print 's=',s
|
def getentry(self, which): self._check() if which == 'in': cmd = IN_ENTRY_SENSE elif which == 'out': cmd = OUT_ENTRY_SENSE self.replycmd(cmd) h = self._getnumber(2) print 'h=',h m = self._getnumber(2) print 'm=',m s = self._getnumber(2) print 's=',s f = self._getnumber(2) print 'f=',f return (h, m, s, f)
|
|
print 'f=',f
|
def getentry(self, which): self._check() if which == 'in': cmd = IN_ENTRY_SENSE elif which == 'out': cmd = OUT_ENTRY_SENSE self.replycmd(cmd) h = self._getnumber(2) print 'h=',h m = self._getnumber(2) print 'm=',m s = self._getnumber(2) print 's=',s f = self._getnumber(2) print 'f=',f return (h, m, s, f)
|
|
if self.re._num_regs == 1: return () return apply(self.group, tuple(range(1, self.re._num_regs) ) )
|
result = [] for g in range(1, self.re._num_regs): if (self.regs[g][0] == -1) or (self.regs[g][1] == -1): result.append(None) else: result.append(self.string[self.regs[g][0]:self.regs[g][1]]) return tuple(result)
|
def groups(self):
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None):
|
def main(tests=None, testdir=None, verbose=0, quiet=False, generate=False, exclude=False, single=False, randomize=False, fromfile=None, findleaks=False, use_resources=None, trace=False):
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=']) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-q', '--quiet'): quiet = 1; verbose = 0 elif o in ('-g', '--generate'): generate = 1 elif o in ('-x', '--exclude'): exclude = 1 elif o in ('-s', '--single'): single = 1 elif o in ('-r', '--randomize'): randomize = 1 elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = 1 elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = 0 else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) sys.exit(len(bad) > 0)
|
The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line.
|
The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, use_resources, and trace) allow programmers calling main() directly to set the values that would normally be set by flags on the command line.
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=']) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-q', '--quiet'): quiet = 1; verbose = 0 elif o in ('-g', '--generate'): generate = 1 elif o in ('-x', '--exclude'): exclude = 1 elif o in ('-s', '--single'): single = 1 elif o in ('-r', '--randomize'): randomize = 1 elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = 1 elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = 0 else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) sys.exit(len(bad) > 0)
|
opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:',
|
opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:T',
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=']) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-q', '--quiet'): quiet = 1; verbose = 0 elif o in ('-g', '--generate'): generate = 1 elif o in ('-x', '--exclude'): exclude = 1 elif o in ('-s', '--single'): single = 1 elif o in ('-r', '--randomize'): randomize = 1 elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = 1 elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = 0 else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) sys.exit(len(bad) > 0)
|
'findleaks', 'use=', 'threshold='])
|
'findleaks', 'use=', 'threshold=', 'trace', ])
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=']) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-q', '--quiet'): quiet = 1; verbose = 0 elif o in ('-g', '--generate'): generate = 1 elif o in ('-x', '--exclude'): exclude = 1 elif o in ('-s', '--single'): single = 1 elif o in ('-r', '--randomize'): randomize = 1 elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = 1 elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = 0 else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) sys.exit(len(bad) > 0)
|
quiet = 1;
|
quiet = True;
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=']) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-q', '--quiet'): quiet = 1; verbose = 0 elif o in ('-g', '--generate'): generate = 1 elif o in ('-x', '--exclude'): exclude = 1 elif o in ('-s', '--single'): single = 1 elif o in ('-r', '--randomize'): randomize = 1 elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = 1 elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = 0 else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) sys.exit(len(bad) > 0)
|
generate = 1
|
generate = True
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=']) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-q', '--quiet'): quiet = 1; verbose = 0 elif o in ('-g', '--generate'): generate = 1 elif o in ('-x', '--exclude'): exclude = 1 elif o in ('-s', '--single'): single = 1 elif o in ('-r', '--randomize'): randomize = 1 elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = 1 elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = 0 else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) sys.exit(len(bad) > 0)
|
exclude = 1
|
exclude = True
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=']) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-q', '--quiet'): quiet = 1; verbose = 0 elif o in ('-g', '--generate'): generate = 1 elif o in ('-x', '--exclude'): exclude = 1 elif o in ('-s', '--single'): single = 1 elif o in ('-r', '--randomize'): randomize = 1 elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = 1 elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = 0 else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) sys.exit(len(bad) > 0)
|
single = 1
|
single = True
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=']) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-q', '--quiet'): quiet = 1; verbose = 0 elif o in ('-g', '--generate'): generate = 1 elif o in ('-x', '--exclude'): exclude = 1 elif o in ('-s', '--single'): single = 1 elif o in ('-r', '--randomize'): randomize = 1 elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = 1 elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = 0 else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) sys.exit(len(bad) > 0)
|
randomize = 1
|
randomize = True
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=']) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-q', '--quiet'): quiet = 1; verbose = 0 elif o in ('-g', '--generate'): generate = 1 elif o in ('-x', '--exclude'): exclude = 1 elif o in ('-s', '--single'): single = 1 elif o in ('-r', '--randomize'): randomize = 1 elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = 1 elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = 0 else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) sys.exit(len(bad) > 0)
|
findleaks = 1
|
findleaks = True
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=']) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-q', '--quiet'): quiet = 1; verbose = 0 elif o in ('-g', '--generate'): generate = 1 elif o in ('-x', '--exclude'): exclude = 1 elif o in ('-s', '--single'): single = 1 elif o in ('-r', '--randomize'): randomize = 1 elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = 1 elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = 0 else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) sys.exit(len(bad) > 0)
|
findleaks = 0
|
findleaks = False
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=']) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-q', '--quiet'): quiet = 1; verbose = 0 elif o in ('-g', '--generate'): generate = 1 elif o in ('-x', '--exclude'): exclude = 1 elif o in ('-s', '--single'): single = 1 elif o in ('-r', '--randomize'): randomize = 1 elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = 1 elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = 0 else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) sys.exit(len(bad) > 0)
|
ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test)
|
if trace: tracer.runctx('runtest(test, generate, verbose, quiet, testdir)', globals=globals(), locals=vars())
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=']) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-q', '--quiet'): quiet = 1; verbose = 0 elif o in ('-g', '--generate'): generate = 1 elif o in ('-x', '--exclude'): exclude = 1 elif o in ('-s', '--single'): single = 1 elif o in ('-r', '--randomize'): randomize = 1 elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = 1 elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = 0 else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) sys.exit(len(bad) > 0)
|
skipped.append(test) if ok == -2: resource_denieds.append(test)
|
ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test)
|
def main(tests=None, testdir=None, verbose=0, quiet=0, generate=0, exclude=0, single=0, randomize=0, fromfile=None, findleaks=0, use_resources=None): """Execute a test suite. This also parses command-line options and modifies its behavior accordingly. tests -- a list of strings containing test names (optional) testdir -- the directory in which to look for tests (optional) Users other than the Python test suite will certainly want to specify testdir; if it's omitted, the directory containing the Python test suite is searched for. If the tests argument is omitted, the tests listed on the command-line will be used. If that's empty, too, then all *.py files beginning with test_ will be used. The other default arguments (verbose, quiet, generate, exclude, single, randomize, findleaks, and use_resources) allow programmers calling main() directly to set the values that would normally be set by flags on the command line. """ test_support.record_original_stdout(sys.stdout) try: opts, args = getopt.getopt(sys.argv[1:], 'hvgqxsrf:lu:t:', ['help', 'verbose', 'quiet', 'generate', 'exclude', 'single', 'random', 'fromfile', 'findleaks', 'use=', 'threshold=']) except getopt.error, msg: usage(2, msg) # Defaults if use_resources is None: use_resources = [] for o, a in opts: if o in ('-h', '--help'): usage(0) elif o in ('-v', '--verbose'): verbose += 1 elif o in ('-q', '--quiet'): quiet = 1; verbose = 0 elif o in ('-g', '--generate'): generate = 1 elif o in ('-x', '--exclude'): exclude = 1 elif o in ('-s', '--single'): single = 1 elif o in ('-r', '--randomize'): randomize = 1 elif o in ('-f', '--fromfile'): fromfile = a elif o in ('-l', '--findleaks'): findleaks = 1 elif o in ('-t', '--threshold'): import gc gc.set_threshold(int(a)) elif o in ('-u', '--use'): u = [x.lower() for x in a.split(',')] for r in u: if r == 'all': use_resources[:] = RESOURCE_NAMES continue remove = False if r[0] == '-': remove = True r = r[1:] if r not in RESOURCE_NAMES: usage(1, 'Invalid -u/--use option: ' + a) if remove: if r in use_resources: use_resources.remove(r) elif r not in use_resources: use_resources.append(r) if generate and verbose: usage(2, "-g and -v don't go together!") if single and fromfile: usage(2, "-s and -f don't go together!") good = [] bad = [] skipped = [] resource_denieds = [] if findleaks: try: import gc except ImportError: print 'No GC available, disabling findleaks.' findleaks = 0 else: # Uncomment the line below to report garbage that is not # freeable by reference counting alone. By default only # garbage that is not collectable by the GC is reported. #gc.set_debug(gc.DEBUG_SAVEALL) found_garbage = [] if single: from tempfile import gettempdir filename = os.path.join(gettempdir(), 'pynexttest') try: fp = open(filename, 'r') next = fp.read().strip() tests = [next] fp.close() except IOError: pass if fromfile: tests = [] fp = open(fromfile) for line in fp: guts = line.split() # assuming no test has whitespace in its name if guts and not guts[0].startswith('#'): tests.extend(guts) fp.close() # Strip .py extensions. if args: args = map(removepy, args) if tests: tests = map(removepy, tests) stdtests = STDTESTS[:] nottests = NOTTESTS[:] if exclude: for arg in args: if arg in stdtests: stdtests.remove(arg) nottests[:0] = args args = [] tests = tests or args or findtests(testdir, stdtests, nottests) if single: tests = tests[:1] if randomize: random.shuffle(tests) test_support.verbose = verbose # Tell tests to be moderately quiet test_support.use_resources = use_resources save_modules = sys.modules.keys() for test in tests: if not quiet: print test sys.stdout.flush() ok = runtest(test, generate, verbose, quiet, testdir) if ok > 0: good.append(test) elif ok == 0: bad.append(test) else: skipped.append(test) if ok == -2: resource_denieds.append(test) if findleaks: gc.collect() if gc.garbage: print "Warning: test created", len(gc.garbage), print "uncollectable object(s)." # move the uncollectable objects somewhere so we don't see # them again found_garbage.extend(gc.garbage) del gc.garbage[:] # Unload the newly imported modules (best effort finalization) for module in sys.modules.keys(): if module not in save_modules and module.startswith("test."): test_support.unload(module) # The lists won't be sorted if running with -r good.sort() bad.sort() skipped.sort() if good and not quiet: if not bad and not skipped and len(good) > 1: print "All", print count(len(good), "test"), "OK." if verbose: print "CAUTION: stdout isn't compared in verbose mode:" print "a test that passes in verbose mode may fail without it." if bad: print count(len(bad), "test"), "failed:" printlist(bad) if skipped and not quiet: print count(len(skipped), "test"), "skipped:" printlist(skipped) e = _ExpectedSkips() plat = sys.platform if e.isvalid(): surprise = set(skipped) - e.getexpected() - set(resource_denieds) if surprise: print count(len(surprise), "skip"), \ "unexpected on", plat + ":" printlist(surprise) else: print "Those skips are all expected on", plat + "." else: print "Ask someone to teach regrtest.py about which tests are" print "expected to get skipped on", plat + "." if single: alltests = findtests(testdir, stdtests, nottests) for i in range(len(alltests)): if tests[0] == alltests[i]: if i == len(alltests) - 1: os.unlink(filename) else: fp = open(filename, 'w') fp.write(alltests[i+1] + '\n') fp.close() break else: os.unlink(filename) sys.exit(len(bad) > 0)
|
path = os.path.join(os.path.dirname(test_email.__file__), 'data', filename)
|
path = os.path.join(os.path.dirname(test_support_file), 'data', filename)
|
def openfile(filename): path = os.path.join(os.path.dirname(test_email.__file__), 'data', filename) return open(path)
|
if __name__ == '__main__': unittest.main(defaultTest='suite') else:
|
def test_main():
|
def suite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(TestMessageAPI)) suite.addTest(unittest.makeSuite(TestEncoders)) suite.addTest(unittest.makeSuite(TestLongHeaders)) suite.addTest(unittest.makeSuite(TestFromMangling)) suite.addTest(unittest.makeSuite(TestMIMEAudio)) suite.addTest(unittest.makeSuite(TestMIMEImage)) suite.addTest(unittest.makeSuite(TestMIMEText)) suite.addTest(unittest.makeSuite(TestMultipartMixed)) suite.addTest(unittest.makeSuite(TestNonConformant)) suite.addTest(unittest.makeSuite(TestRFC2047)) suite.addTest(unittest.makeSuite(TestMIMEMessage)) suite.addTest(unittest.makeSuite(TestIdempotent)) suite.addTest(unittest.makeSuite(TestMiscellaneous)) suite.addTest(unittest.makeSuite(TestIterators)) suite.addTest(unittest.makeSuite(TestParsers)) return suite
|
def seval(item): """ Strips parens from item prior to calling eval in an attempt to make it safer """ return eval(item.replace('(', '').replace(')', ''))
|
def seval(item): """ Strips parens from item prior to calling eval in an attempt to make it safer """ return eval(item.replace('(', '').replace(')', ''))
|
|
try:
|
for thisType in [int, long, float, complex]:
|
def seval(item): """ Strips parens from item prior to calling eval in an attempt to make it safer """ return eval(item.replace('(', '').replace(')', ''))
|
thisType = type(seval(row[col])) except OverflowError: thisType = type(seval(row[col] + 'L')) thisType = type(0) except:
|
thisType(row[col]) break except ValueError, OverflowError: pass else:
|
def seval(item): """ Strips parens from item prior to calling eval in an attempt to make it safer """ return eval(item.replace('(', '').replace(')', ''))
|
eval("%s(%s)" % (colType.__name__, header[col])) except:
|
colType(header[col]) except ValueError, TypeError:
|
def seval(item): """ Strips parens from item prior to calling eval in an attempt to make it safer """ return eval(item.replace('(', '').replace(')', ''))
|
return s.split(NUL, 1)[0]
|
return s.rstrip(NUL)
|
def nts(s): """Convert a null-terminated string buffer to a python string. """ return s.split(NUL, 1)[0]
|
parts.append(value + (fieldsize - l) * NUL)
|
parts.append(value[:fieldsize] + (fieldsize - l) * NUL)
|
def tobuf(self): """Return a tar header block as a 512 byte string. """ name = self.name
|
self.chunks = [0]
|
def __init__(self, name=None, mode="r", fileobj=None): """Open an (uncompressed) tar archive `name'. `mode' is either 'r' to read from an existing archive, 'a' to append data to an existing file or 'w' to create a new file overwriting an existing one. `mode' defaults to 'r'. If `fileobj' is given, it is used for reading or writing data. If it can be determined, `mode' is overridden by `fileobj's mode. `fileobj' is not closed, when TarFile is closed. """ self.name = name
|
|
self.members.append(tarinfo) self.membernames.append(tarinfo.name) self.chunks.append(self.offset)
|
self._record_member(tarinfo)
|
def addfile(self, tarinfo, fileobj=None): """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is given, tarinfo.size bytes are read from it and added to the archive. You can create TarInfo objects using gettarinfo(). On Windows platforms, `fileobj' should always be opened with mode 'rb' to avoid irritation about the file size. """ self._check("aw")
|
self.fileobj.seek(self.chunks[-1])
|
self.fileobj.seek(self.offset)
|
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
|
if self.chunks[-1] == 0:
|
if self.offset == 0:
|
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
|
tarinfo = self.TYPE_METH[tarinfo.type](self, tarinfo) else: tarinfo.offset_data = self.offset if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES: self.offset += self._block(tarinfo.size)
|
return self.TYPE_METH[tarinfo.type](self, tarinfo) tarinfo.offset_data = self.offset if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES: self.offset += self._block(tarinfo.size)
|
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
|
self.members.append(tarinfo) self.membernames.append(tarinfo.name) self.chunks.append(self.offset)
|
self._record_member(tarinfo)
|
def next(self): """Return the next member of the archive as a TarInfo object, when TarFile is opened for reading. Return None if there is no more available. """ self._check("ra") if self.firstmember is not None: m = self.firstmember self.firstmember = None return m
|
name = nts(buf) if tarinfo.type == GNUTYPE_LONGLINK: linkname = nts(buf) buf = self.fileobj.read(BLOCKSIZE) tarinfo = TarInfo.frombuf(buf) tarinfo.offset = self.offset self.offset += BLOCKSIZE tarinfo.offset_data = self.offset tarinfo.name = name or tarinfo.name tarinfo.linkname = linkname or tarinfo.linkname if tarinfo.isreg() or tarinfo.type not in SUPPORTED_TYPES: self.offset += self._block(tarinfo.size) return tarinfo
|
next.name = nts(buf) elif tarinfo.type == GNUTYPE_LONGLINK: next.linkname = nts(buf) return next
|
def proc_gnulong(self, tarinfo): """Evaluate the blocks that hold a GNU longname or longlink member. """ buf = "" name = None linkname = None count = tarinfo.size while count > 0: block = self.fileobj.read(BLOCKSIZE) buf += block self.offset += BLOCKSIZE count -= BLOCKSIZE
|
onerror()
|
onerror(name)
|
def seen(p, m={}): if p in m: return True m[p] = True
|
for item in walk_packages(path, name+'.'):
|
for item in walk_packages(path, name+'.', onerror):
|
def seen(p, m={}): if p in m: return True m[p] = True
|
return self.fp.tell() - self.start
|
return self.fp.tell() - len(self.readahead) - self.start
|
def tell(self): if self.level > 0: return self.lastpos return self.fp.tell() - self.start
|
test_support.run_unittest( TrivialTests, OpenerDirectorTests, HandlerTests, MiscTests, )
|
tests = (TrivialTests, OpenerDirectorTests, HandlerTests, MiscTests) if test_support.is_resource_enabled('network'): tests += (NetworkTests,) test_support.run_unittest(*tests)
|
def test_main(verbose=None): from test import test_sets test_support.run_unittest( TrivialTests, OpenerDirectorTests, HandlerTests, MiscTests, )
|
assert output_dir is not None
|
if output_dir is None: output_dir = ''
|
def object_filenames(self, source_filenames, strip_dir=0, output_dir=''): assert output_dir is not None obj_names = [] for src_name in source_filenames: base, ext = os.path.splitext(src_name) if ext not in self.src_extensions: raise UnknownFileError, \ "unknown file type '%s' (from '%s')" % (ext, src_name) if strip_dir: base = os.path.basename(base) obj_names.append(os.path.join(output_dir, base + self.obj_extension)) return obj_names
|
ext_modules=[Extension('struct', ['structmodule.c'])],
|
ext_modules=[Extension('_struct', ['_struct.c'])],
|
def main(): # turn off warnings when deprecated modules are imported import warnings warnings.filterwarnings("ignore",category=DeprecationWarning) setup(# PyPI Metadata (PEP 301) name = "Python", version = sys.version.split()[0], url = "http://www.python.org/%s" % sys.version[:3], maintainer = "Guido van Rossum and the Python community", maintainer_email = "[email protected]", description = "A high-level object-oriented programming language", long_description = SUMMARY.strip(), license = "PSF license", classifiers = filter(None, CLASSIFIERS.split("\n")), platforms = ["Many"], # Build info cmdclass = {'build_ext':PyBuildExt, 'install':PyBuildInstall, 'install_lib':PyBuildInstallLib}, # The struct module is defined here, because build_ext won't be # called unless there's at least one extension module defined. ext_modules=[Extension('struct', ['structmodule.c'])], # Scripts to install scripts = ['Tools/scripts/pydoc', 'Tools/scripts/idle', 'Lib/smtpd.py'] )
|
regexp=None, nocase=None, count=None):
|
regexp=None, nocase=None, count=None, elide=None):
|
def search(self, pattern, index, stopindex=None, forwards=None, backwards=None, exact=None, regexp=None, nocase=None, count=None): """Search PATTERN beginning from INDEX until STOPINDEX. Return the index of the first character of a match or an empty string.""" args = [self._w, 'search'] if forwards: args.append('-forwards') if backwards: args.append('-backwards') if exact: args.append('-exact') if regexp: args.append('-regexp') if nocase: args.append('-nocase') if count: args.append('-count'); args.append(count) if pattern[0] == '-': args.append('--') args.append(pattern) args.append(index) if stopindex: args.append(stopindex) return self.tk.call(tuple(args))
|
def checkSetMinor(self):
|
def test_checkSetMinor(self):
|
def checkSetMinor(self): au = MIMEAudio(self._audiodata, 'fish') self.assertEqual(im.get_type(), 'audio/fish')
|
self.assertEqual(im.get_type(), 'audio/fish')
|
self.assertEqual(au.get_type(), 'audio/fish')
|
def checkSetMinor(self): au = MIMEAudio(self._audiodata, 'fish') self.assertEqual(im.get_type(), 'audio/fish')
|
def checkSetMinor(self):
|
def test_checkSetMinor(self):
|
def checkSetMinor(self): im = MIMEImage(self._imgdata, 'fish') self.assertEqual(im.get_type(), 'image/fish')
|
if (code in (301, 302, 303, 307) and req.method() in ("GET", "HEAD") or code in (302, 303) and req.method() == "POST"):
|
if "location" in headers: newurl = headers["location"] elif "uri" in headers: newurl = headers["uri"] else: return newurl = urlparse.urljoin(req.get_full_url(), newurl) m = req.get_method() if (code in (301, 302, 303, 307) and m in ("GET", "HEAD") or code in (302, 303) and m == "POST"):
|
def redirect_request(self, req, fp, code, msg, headers): """Return a Request or None in response to a redirect.
|
try: h = http_class(host) if req.has_data(): data = req.get_data() h.putrequest('POST', req.get_selector()) if not 'Content-type' in req.headers: h.putheader('Content-type', 'application/x-www-form-urlencoded') if not 'Content-length' in req.headers: h.putheader('Content-length', '%d' % len(data)) else: h.putrequest('GET', req.get_selector()) except socket.error, err: raise URLError(err)
|
h = http_class(host) if req.has_data(): data = req.get_data() h.putrequest('POST', req.get_selector()) if not 'Content-type' in req.headers: h.putheader('Content-type', 'application/x-www-form-urlencoded') if not 'Content-length' in req.headers: h.putheader('Content-length', '%d' % len(data)) else: h.putrequest('GET', req.get_selector())
|
def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given')
|
h.endheaders()
|
try: h.endheaders() except socket.error, err: raise URLError(err)
|
def do_open(self, http_class, req): host = req.get_host() if not host: raise URLError('no host given')
|
timestamp = 1000000000 utc = FixedOffset(0, "utc", 0) expected = datetime(2001, 9, 9, 1, 46, 40) got = datetime.utcfromtimestamp(timestamp) self.failUnless(abs(got - expected) < timedelta(minutes=1)) est = FixedOffset(-5*60, "est", 0) expected -= timedelta(hours=5) got = datetime.fromtimestamp(timestamp, est).replace(tzinfo=None) self.failUnless(abs(got - expected) < timedelta(minutes=1))
|
timestamp = 1000000000 utcdatetime = datetime.utcfromtimestamp(timestamp) utcoffset = timedelta(hours=-15, minutes=39) tz = FixedOffset(utcoffset, "tz", 0) expected = utcdatetime + utcoffset got = datetime.fromtimestamp(timestamp, tz) self.assertEqual(expected, got.replace(tzinfo=None))
|
def test_tzinfo_fromtimestamp(self): import time meth = self.theclass.fromtimestamp ts = time.time() # Ensure it doesn't require tzinfo (i.e., that this doesn't blow up). base = meth(ts) # Try with and without naming the keyword. off42 = FixedOffset(42, "42") another = meth(ts, off42) again = meth(ts, tz=off42) self.failUnless(another.tzinfo is again.tzinfo) self.assertEqual(another.utcoffset(), timedelta(minutes=42)) # Bad argument with and w/o naming the keyword. self.assertRaises(TypeError, meth, ts, 16) self.assertRaises(TypeError, meth, ts, tzinfo=16) # Bad keyword name. self.assertRaises(TypeError, meth, ts, tinfo=off42) # Too many args. self.assertRaises(TypeError, meth, ts, off42, off42) # Too few args. self.assertRaises(TypeError, meth)
|
self._arrow = _canvas.create_line(x-dx,y+dy,x,y,
|
self._arrow = self._canvas.create_line(x-dx,y+dy,x,y,
|
def _draw_turtle(self,position=[]): if not self._tracing: return if position == []: position = self._position x,y = position distance = 8 dx = distance * cos(self._angle*self._invradian) dy = distance * sin(self._angle*self._invradian) self._delete_turtle() self._arrow = _canvas.create_line(x-dx,y+dy,x,y, width=self._width, arrow="last", capstyle="round", fill=self._color) self._canvas.update()
|
print 'DBG interaction'
|
def edit_applet(name): pref_handle = openpreffile(READ) app_handle = openapplet(name) notfound = '' l, sr = getprefpath(OVERRIDE_PATH_STRINGS_ID) if l == None: notfound = 'path' l, dummy = getprefpath(PATH_STRINGS_ID) if l == None: message('Cannot find any sys.path resource! (Old python?)') sys.exit(0) fss, dr, fss_changed = getprefdir(OVERRIDE_DIRECTORY_ID) if fss == None: if notfound: notfound = notfound + ', directory' else: notfound = 'directory' fss, dummy, dummy2 = getprefdir(DIRECTORY_ID) if fss == None: fss = macfs.FSSpec(os.getcwd()) fss_changed = 1 options, opr = getoptions(OVERRIDE_OPTIONS_ID) if not opr: if notfound: notfound = notfound + ', options' else: notfound = 'options' options, dummy = getoptions(OPTIONS_ID) saved_options = options[:] creator, type, delaycons, gusi_opr = getgusioptions(OVERRIDE_GUSI_ID) if not gusi_opr: if notfound: notfound = notfound + ', GUSI options' else: notfound = 'GUSI options' creator, type, delaycons, gusi_opr = getgusioptions(GUSI_ID) saved_gusi_options = creator, type, delaycons dummy = dummy2 = None # Discard them. if notfound: message('Warning: initial %s taken from system-wide defaults'%notfound) # Let the user play away print 'DBG interaction' result = interact(l, fss, (options, creator, type, delaycons), name) # See what we have to update, and how if result == None: sys.exit(0) pathlist, nfss, (options, creator, type, delaycons) = result if nfss != fss: fss_changed = 1 if fss_changed: alias = nfss.NewAlias() if dr: dr.data = alias.data dr.ChangedResource() else: dr = Resource(alias.data) dr.AddResource('alis', OVERRIDE_DIRECTORY_ID, '') if pathlist != l: if pathlist == []: if sr.HomeResFile() == app_handle: sr.RemoveResource() elif sr and sr.HomeResFile() == app_handle: sr.data = listtores(pathlist) sr.ChangedResource() else: sr = Resource(listtores(pathlist)) sr.AddResource('STR#', OVERRIDE_PATH_STRINGS_ID, '') if options != saved_options: newdata = reduce(lambda x, y: x+chr(y), options, '') if opr and opr.HomeResFile() == app_handle: opr.data = newdata opr.ChangedResource() else: opr = Resource(newdata) opr.AddResource('Popt', OVERRIDE_OPTIONS_ID, '') if (creator, type, delaycons) != saved_gusi_options: newdata = setgusioptions(gusi_opr, creator, type, delaycons) id, type, name = gusi_opr.GetResInfo() if gusi_opr.HomeResFile() == app_handle and id == OVERRIDE_GUSI_ID: gusi_opr.data = newdata gusi_opr.ChangedResource() else: ngusi_opr = Resource(newdata) ngusi_opr.AddResource('GU\267I', OVERRIDE_GUSI_ID, '') CloseResFile(app_handle)
|
|
def readline(self):
|
def readline(self, size=-1): if size < 0: size = sys.maxint
|
def readline(self): bufs = [] readsize = 100 while 1: c = self.read(readsize) i = string.find(c, '\n') if i >= 0 or c == '': bufs.append(c[:i+1]) self._unread(c[i+1:]) return string.join(bufs, '') bufs.append(c) readsize = readsize * 2
|
readsize = 100
|
orig_size = size readsize = min(100, size)
|
def readline(self): bufs = [] readsize = 100 while 1: c = self.read(readsize) i = string.find(c, '\n') if i >= 0 or c == '': bufs.append(c[:i+1]) self._unread(c[i+1:]) return string.join(bufs, '') bufs.append(c) readsize = readsize * 2
|
readsize = readsize * 2 def readlines(self, ignored=None): buf = self.read() lines = string.split(buf, '\n') for i in range(len(lines)-1): lines[i] = lines[i] + '\n' if lines and not lines[-1]: del lines[-1] return lines
|
size = size - len(c) readsize = min(size, readsize * 2) def readlines(self, sizehint=0): if sizehint <= 0: sizehint = sys.maxint L = [] while sizehint > 0: line = self.readline() if line == "": break L.append( line ) sizehint = sizehint - len(line) return L
|
def readline(self): bufs = [] readsize = 100 while 1: c = self.read(readsize) i = string.find(c, '\n') if i >= 0 or c == '': bufs.append(c[:i+1]) self._unread(c[i+1:]) return string.join(bufs, '') bufs.append(c) readsize = readsize * 2
|
retval = os.spawnl(os.P_WAIT, sys.executable, sys.executable, tester, v, fd)
|
if sys.platform in ('win32'): decorated = '"%s"' % sys.executable tester = '"%s"' % tester else: decorated = sys.executable retval = os.spawnl(os.P_WAIT, sys.executable, decorated, tester, v, fd)
|
def test_noinherit(self): # _mkstemp_inner file handles are not inherited by child processes if not has_spawnl: return # ugh, can't use TestSkipped.
|
def createMessage(self, dir):
|
def createMessage(self, dir, mbox=False):
|
def createMessage(self, dir): t = int(time.time() % 1000000) pid = self._counter self._counter += 1 filename = os.extsep.join((str(t), str(pid), "myhostname", "mydomain")) tmpname = os.path.join(self._dir, "tmp", filename) newname = os.path.join(self._dir, dir, filename) fp = open(tmpname, "w") self._msgfiles.append(tmpname) fp.write(DUMMY_MESSAGE) fp.close() if hasattr(os, "link"): os.link(tmpname, newname) else: fp = open(newname, "w") fp.write(DUMMY_MESSAGE) fp.close() self._msgfiles.append(newname)
|
t>>11, (t>>5)&0x3F, t&0x1F * 2 )
|
t>>11, (t>>5)&0x3F, (t&0x1F) * 2 )
|
def _GetContents(self): "Read in the table of contents for the zip file" fp = self.fp fp.seek(-22, 2) # Start of end-of-archive record filesize = fp.tell() + 22 # Get file size endrec = fp.read(22) # Archive must not end with a comment! if endrec[0:4] != stringEndArchive or endrec[-2:] != "\000\000": raise BadZipfile, "File is not a zip file, or ends with a comment" endrec = struct.unpack(structEndArchive, endrec) if self.debug > 1: print endrec size_cd = endrec[5] # bytes in central directory offset_cd = endrec[6] # offset of central directory x = filesize - 22 - size_cd # "concat" is zero, unless zip was concatenated to another file concat = x - offset_cd if self.debug > 2: print "given, inferred, offset", offset_cd, x, concat # self.start_dir: Position of start of central directory self.start_dir = offset_cd + concat fp.seek(self.start_dir, 0) total = 0 while total < size_cd: centdir = fp.read(46) total = total + 46 if centdir[0:4] != stringCentralDir: raise BadZipfile, "Bad magic number for central directory" centdir = struct.unpack(structCentralDir, centdir) if self.debug > 2: print centdir filename = fp.read(centdir[12]) # Create ZipInfo instance to store file information x = ZipInfo(filename) x.extra = fp.read(centdir[13]) x.comment = fp.read(centdir[14]) total = total + centdir[12] + centdir[13] + centdir[14] x.header_offset = centdir[18] + concat x.file_offset = x.header_offset + 30 + centdir[12] + centdir[13] (x.create_version, x.create_system, x.extract_version, x.reserved, x.flag_bits, x.compress_type, t, d, x.CRC, x.compress_size, x.file_size) = centdir[1:12] x.volume, x.internal_attr, x.external_attr = centdir[15:18] # Convert date/time code to (year, month, day, hour, min, sec) x.date_time = ( (d>>9)+1980, (d>>5)&0xF, d&0x1F, t>>11, (t>>5)&0x3F, t&0x1F * 2 ) self.filelist.append(x) self.NameToInfo[x.filename] = x if self.debug > 2: print "total", total for data in self.filelist: fp.seek(data.header_offset, 0) fheader = fp.read(30) if fheader[0:4] != stringFileHeader: raise BadZipfile, "Bad magic number for file header" fheader = struct.unpack(structFileHeader, fheader) fname = fp.read(fheader[10]) if fname != data.filename: raise RuntimeError, \
|
def AS_TYPE_64BIT(as_): return \
|
def AS_TYPE_64BIT(as): return \
|
def AS_TYPE_64BIT(as_): return \
|
if request.command in ('post', 'put'):
|
if request.command.lower() in ('post', 'put'):
|
def handle_request (self, request): [path, params, query, fragment] = request.split_uri()
|
res[i] = '%%%02x' % ord(c)
|
res[i] = '%%%02X' % ord(c)
|
def _fast_quote(s): global _fast_safe if _fast_safe is None: _fast_safe = {} for c in _fast_safe_test: _fast_safe[c] = c res = list(s) for i in range(len(res)): c = res[i] if not _fast_safe.has_key(c): res[i] = '%%%02x' % ord(c) return ''.join(res)
|
res[i] = '%%%02x' % ord(c)
|
res[i] = '%%%02X' % ord(c)
|
def quote(s, safe = '/'): """quote('abc def') -> 'abc%20def' Each part of a URL, e.g. the path info, the query, etc., has a different set of reserved characters that must be quoted. RFC 2396 Uniform Resource Identifiers (URI): Generic Syntax lists the following reserved characters. reserved = ";" | "/" | "?" | ":" | "@" | "&" | "=" | "+" | "$" | "," Each of these characters is reserved in some component of a URL, but not necessarily in all of them. By default, the quote function is intended for quoting the path section of a URL. Thus, it will not encode '/'. This character is reserved, but in typical usage the quote function is being called on a path where the existing slash characters are used as reserved characters. """ safe = always_safe + safe if _fast_safe_test == safe: return _fast_quote(s) res = list(s) for i in range(len(res)): c = res[i] if c not in safe: res[i] = '%%%02x' % ord(c) return ''.join(res)
|
else: p = "%s-ast.h" % mod.name f = open(p, "wb") print >> f, auto_gen_msg print >> f, ' c = ChainOfVisitors(TypeDefVisitor(f), StructVisitor(f), PrototypeVisitor(f), ) c.visit(mod) print >>f, "PyObject* PyAST_mod2obj(mod_ty t);" f.close()
|
f = open(p, "wb") print >> f, auto_gen_msg print >> f, ' c = ChainOfVisitors(TypeDefVisitor(f), StructVisitor(f), PrototypeVisitor(f), ) c.visit(mod) print >>f, "PyObject* PyAST_mod2obj(mod_ty t);" f.close()
|
def main(srcfile): argv0 = sys.argv[0] components = argv0.split(os.sep) argv0 = os.sep.join(components[-2:]) auto_gen_msg = '/* File automatically generated by %s */\n' % argv0 mod = asdl.parse(srcfile) if not asdl.check(mod): sys.exit(1) if INC_DIR: p = "%s/%s-ast.h" % (INC_DIR, mod.name) else: p = "%s-ast.h" % mod.name f = open(p, "wb") print >> f, auto_gen_msg print >> f, '#include "asdl.h"\n' c = ChainOfVisitors(TypeDefVisitor(f), StructVisitor(f), PrototypeVisitor(f), ) c.visit(mod) print >>f, "PyObject* PyAST_mod2obj(mod_ty t);" f.close() if SRC_DIR: p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c") else: p = "%s-ast.c" % mod.name f = open(p, "wb") print >> f, auto_gen_msg print >> f, '#include "Python.h"' print >> f, '#include "%s-ast.h"' % mod.name print >> f print >>f, "static PyTypeObject* AST_type;" v = ChainOfVisitors( PyTypesDeclareVisitor(f), PyTypesVisitor(f), FunctionVisitor(f), ObjVisitor(f), ASTModuleVisitor(f), PartingShots(f), ) v.visit(mod) f.close()
|
else: p = "%s-ast.c" % mod.name f = open(p, "wb") print >> f, auto_gen_msg print >> f, ' print >> f, ' print >> f print >>f, "static PyTypeObject* AST_type;" v = ChainOfVisitors( PyTypesDeclareVisitor(f), PyTypesVisitor(f), FunctionVisitor(f), ObjVisitor(f), ASTModuleVisitor(f), PartingShots(f), ) v.visit(mod) f.close()
|
f = open(p, "wb") print >> f, auto_gen_msg print >> f, ' print >> f, ' print >> f print >>f, "static PyTypeObject* AST_type;" v = ChainOfVisitors( PyTypesDeclareVisitor(f), PyTypesVisitor(f), FunctionVisitor(f), ObjVisitor(f), ASTModuleVisitor(f), PartingShots(f), ) v.visit(mod) f.close()
|
def main(srcfile): argv0 = sys.argv[0] components = argv0.split(os.sep) argv0 = os.sep.join(components[-2:]) auto_gen_msg = '/* File automatically generated by %s */\n' % argv0 mod = asdl.parse(srcfile) if not asdl.check(mod): sys.exit(1) if INC_DIR: p = "%s/%s-ast.h" % (INC_DIR, mod.name) else: p = "%s-ast.h" % mod.name f = open(p, "wb") print >> f, auto_gen_msg print >> f, '#include "asdl.h"\n' c = ChainOfVisitors(TypeDefVisitor(f), StructVisitor(f), PrototypeVisitor(f), ) c.visit(mod) print >>f, "PyObject* PyAST_mod2obj(mod_ty t);" f.close() if SRC_DIR: p = os.path.join(SRC_DIR, str(mod.name) + "-ast.c") else: p = "%s-ast.c" % mod.name f = open(p, "wb") print >> f, auto_gen_msg print >> f, '#include "Python.h"' print >> f, '#include "%s-ast.h"' % mod.name print >> f print >>f, "static PyTypeObject* AST_type;" v = ChainOfVisitors( PyTypesDeclareVisitor(f), PyTypesVisitor(f), FunctionVisitor(f), ObjVisitor(f), ASTModuleVisitor(f), PartingShots(f), ) v.visit(mod) f.close()
|
exts.append( Extension('ossaudiodev', ['ossaudiodev.c']) )
|
def detect_modules(self): # Ensure that /usr/local is always used add_dir_to_list(self.compiler.library_dirs, '/usr/local/lib') add_dir_to_list(self.compiler.include_dirs, '/usr/local/include')
|
|
if len(a) < len(b): a, b = b, a res = a[:] for i in range(len(b)): res[i] = res[i] - b[i] return normalize(res)
|
neg_b = map(lambda x: -x, b[:]) return plus(a, neg_b)
|
def minus(a, b): if len(a) < len(b): a, b = b, a # make sure a is the longest res = a[:] # make a copy for i in range(len(b)): res[i] = res[i] - b[i] return normalize(res)
|
if type (package) is StringType: path = string.split (package, '.') elif type (package) in (TupleType, ListType): path = list (package) else: raise TypeError, "'package' must be a string, list, or tuple"
|
path = string.split (package, '.')
|
def get_package_dir (self, package): """Return the directory, relative to the top of the source distribution, where package 'package' should be found (at least according to the 'package_dir' option, if any)."""
|
package = tuple (path[0:-1])
|
package = string.join(path[0:-1], '.')
|
def find_modules (self): """Finds individually-specified Python modules, ie. those listed by module name in 'self.py_modules'. Returns a list of tuples (package, module_base, filename): 'package' is a tuple of the path through package-space to the module; 'module_base' is the bare (no packages, no dots) module name, and 'filename' is the path to the ".py" file (relative to the distribution root) that implements the module. """
|
newurl = basejoin("http:" + url, newurl)
|
newurl = basejoin(self.type + ":" + url, newurl)
|
def redirect_internal(self, url, fp, errcode, errmsg, headers, data): if headers.has_key('location'): newurl = headers['location'] elif headers.has_key('uri'): newurl = headers['uri'] else: return void = fp.read() fp.close() # In case the server sent a relative URL, join with original: newurl = basejoin("http:" + url, newurl) if data is None: return self.open(newurl) else: return self.open(newurl, data)
|
if sys.argv[-1] == "Release":
|
if sys.argv[1] == "Release":
|
def main(): build_all = "-a" in sys.argv if sys.argv[-1] == "Release": arch = "x86" debug = False configure = "VC-WIN32" makefile = "32.mak" elif sys.argv[-1] == "Debug": arch = "x86" debug = True configure = "VC-WIN32" makefile="d32.mak" elif sys.argv[-1] == "ReleaseItanium": arch = "ia64" debug = False configure = "VC-WIN64I" do_script = "ms\\do_win64i" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_ITANIUM" elif sys.argv[-1] == "ReleaseAMD64": arch="amd64" debug=False configure = "VC-WIN64A" do_script = "ms\\do_win64a" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_OPTERON" make_flags = "" if build_all: make_flags = "-a" # perl should be on the path, but we also look in "\perl" and "c:\\perl" # as "well known" locations perls = find_all_on_path("perl.exe", ["\\perl\\bin", "C:\\perl\\bin"]) perl = find_working_perl(perls) if perl is None: sys.exit(1) print "Found a working perl at '%s'" % (perl,) # Look for SSL 2 levels up from pcbuild - ie, same place zlib etc all live. ssl_dir = find_best_ssl_dir(("../..",)) if ssl_dir is None: sys.exit(1) old_cd = os.getcwd() try: os.chdir(ssl_dir) # If the ssl makefiles do not exist, we invoke Perl to generate them. if not os.path.isfile(makefile): print "Creating the makefiles..." # Put our working Perl at the front of our path os.environ["PATH"] = os.path.split(perl)[0] + \ os.pathsep + \ os.environ["PATH"] if arch=="x86": run_32all_py() else: run_configure(configure, do_script) # Now run make. print "Executing nmake over the ssl makefiles..." rc = os.system("nmake /nologo -f "+makefile) if rc: print "Executing d32.mak failed" print rc sys.exit(rc) finally: os.chdir(old_cd) # And finally, we can build the _ssl module itself for Python. defs = "SSL_DIR=%s" % (ssl_dir,) if debug: defs = defs + " " + "DEBUG=1" rc = os.system('nmake /nologo -f _ssl.mak ' + defs + " " + make_flags) sys.exit(rc)
|
elif sys.argv[-1] == "Debug":
|
elif sys.argv[1] == "Debug":
|
def main(): build_all = "-a" in sys.argv if sys.argv[-1] == "Release": arch = "x86" debug = False configure = "VC-WIN32" makefile = "32.mak" elif sys.argv[-1] == "Debug": arch = "x86" debug = True configure = "VC-WIN32" makefile="d32.mak" elif sys.argv[-1] == "ReleaseItanium": arch = "ia64" debug = False configure = "VC-WIN64I" do_script = "ms\\do_win64i" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_ITANIUM" elif sys.argv[-1] == "ReleaseAMD64": arch="amd64" debug=False configure = "VC-WIN64A" do_script = "ms\\do_win64a" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_OPTERON" make_flags = "" if build_all: make_flags = "-a" # perl should be on the path, but we also look in "\perl" and "c:\\perl" # as "well known" locations perls = find_all_on_path("perl.exe", ["\\perl\\bin", "C:\\perl\\bin"]) perl = find_working_perl(perls) if perl is None: sys.exit(1) print "Found a working perl at '%s'" % (perl,) # Look for SSL 2 levels up from pcbuild - ie, same place zlib etc all live. ssl_dir = find_best_ssl_dir(("../..",)) if ssl_dir is None: sys.exit(1) old_cd = os.getcwd() try: os.chdir(ssl_dir) # If the ssl makefiles do not exist, we invoke Perl to generate them. if not os.path.isfile(makefile): print "Creating the makefiles..." # Put our working Perl at the front of our path os.environ["PATH"] = os.path.split(perl)[0] + \ os.pathsep + \ os.environ["PATH"] if arch=="x86": run_32all_py() else: run_configure(configure, do_script) # Now run make. print "Executing nmake over the ssl makefiles..." rc = os.system("nmake /nologo -f "+makefile) if rc: print "Executing d32.mak failed" print rc sys.exit(rc) finally: os.chdir(old_cd) # And finally, we can build the _ssl module itself for Python. defs = "SSL_DIR=%s" % (ssl_dir,) if debug: defs = defs + " " + "DEBUG=1" rc = os.system('nmake /nologo -f _ssl.mak ' + defs + " " + make_flags) sys.exit(rc)
|
elif sys.argv[-1] == "ReleaseItanium":
|
elif sys.argv[1] == "ReleaseItanium":
|
def main(): build_all = "-a" in sys.argv if sys.argv[-1] == "Release": arch = "x86" debug = False configure = "VC-WIN32" makefile = "32.mak" elif sys.argv[-1] == "Debug": arch = "x86" debug = True configure = "VC-WIN32" makefile="d32.mak" elif sys.argv[-1] == "ReleaseItanium": arch = "ia64" debug = False configure = "VC-WIN64I" do_script = "ms\\do_win64i" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_ITANIUM" elif sys.argv[-1] == "ReleaseAMD64": arch="amd64" debug=False configure = "VC-WIN64A" do_script = "ms\\do_win64a" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_OPTERON" make_flags = "" if build_all: make_flags = "-a" # perl should be on the path, but we also look in "\perl" and "c:\\perl" # as "well known" locations perls = find_all_on_path("perl.exe", ["\\perl\\bin", "C:\\perl\\bin"]) perl = find_working_perl(perls) if perl is None: sys.exit(1) print "Found a working perl at '%s'" % (perl,) # Look for SSL 2 levels up from pcbuild - ie, same place zlib etc all live. ssl_dir = find_best_ssl_dir(("../..",)) if ssl_dir is None: sys.exit(1) old_cd = os.getcwd() try: os.chdir(ssl_dir) # If the ssl makefiles do not exist, we invoke Perl to generate them. if not os.path.isfile(makefile): print "Creating the makefiles..." # Put our working Perl at the front of our path os.environ["PATH"] = os.path.split(perl)[0] + \ os.pathsep + \ os.environ["PATH"] if arch=="x86": run_32all_py() else: run_configure(configure, do_script) # Now run make. print "Executing nmake over the ssl makefiles..." rc = os.system("nmake /nologo -f "+makefile) if rc: print "Executing d32.mak failed" print rc sys.exit(rc) finally: os.chdir(old_cd) # And finally, we can build the _ssl module itself for Python. defs = "SSL_DIR=%s" % (ssl_dir,) if debug: defs = defs + " " + "DEBUG=1" rc = os.system('nmake /nologo -f _ssl.mak ' + defs + " " + make_flags) sys.exit(rc)
|
elif sys.argv[-1] == "ReleaseAMD64":
|
elif sys.argv[1] == "ReleaseAMD64":
|
def main(): build_all = "-a" in sys.argv if sys.argv[-1] == "Release": arch = "x86" debug = False configure = "VC-WIN32" makefile = "32.mak" elif sys.argv[-1] == "Debug": arch = "x86" debug = True configure = "VC-WIN32" makefile="d32.mak" elif sys.argv[-1] == "ReleaseItanium": arch = "ia64" debug = False configure = "VC-WIN64I" do_script = "ms\\do_win64i" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_ITANIUM" elif sys.argv[-1] == "ReleaseAMD64": arch="amd64" debug=False configure = "VC-WIN64A" do_script = "ms\\do_win64a" makefile = "ms\\nt.mak" os.environ["VSEXTCOMP_USECL"] = "MS_OPTERON" make_flags = "" if build_all: make_flags = "-a" # perl should be on the path, but we also look in "\perl" and "c:\\perl" # as "well known" locations perls = find_all_on_path("perl.exe", ["\\perl\\bin", "C:\\perl\\bin"]) perl = find_working_perl(perls) if perl is None: sys.exit(1) print "Found a working perl at '%s'" % (perl,) # Look for SSL 2 levels up from pcbuild - ie, same place zlib etc all live. ssl_dir = find_best_ssl_dir(("../..",)) if ssl_dir is None: sys.exit(1) old_cd = os.getcwd() try: os.chdir(ssl_dir) # If the ssl makefiles do not exist, we invoke Perl to generate them. if not os.path.isfile(makefile): print "Creating the makefiles..." # Put our working Perl at the front of our path os.environ["PATH"] = os.path.split(perl)[0] + \ os.pathsep + \ os.environ["PATH"] if arch=="x86": run_32all_py() else: run_configure(configure, do_script) # Now run make. print "Executing nmake over the ssl makefiles..." rc = os.system("nmake /nologo -f "+makefile) if rc: print "Executing d32.mak failed" print rc sys.exit(rc) finally: os.chdir(old_cd) # And finally, we can build the _ssl module itself for Python. defs = "SSL_DIR=%s" % (ssl_dir,) if debug: defs = defs + " " + "DEBUG=1" rc = os.system('nmake /nologo -f _ssl.mak ' + defs + " " + make_flags) sys.exit(rc)
|
self.plist.CFBundleExecutable = self.name
|
def setup(self): if self.mainprogram is None and self.executable is None: raise TypeError, ("must specify either or both of " "'executable' and 'mainprogram'")
|
|
try: fp = open(file) except: return None
|
fp = open(file)
|
def __init__(self, file=None): if not file: file = os.path.join(os.environ['HOME'], ".netrc") try: fp = open(file) except: return None self.hosts = {} self.macros = {} lexer = shlex.shlex(fp)
|
emit(LOGHEADER, self.ui, os.environ, date=date, _file=tfn)
|
emit(LOGHEADER, self.ui, os.environ, date=date, _file=tf)
|
def commit(self, entry): file = entry.file # Normalize line endings in body if '\r' in self.ui.body: self.ui.body = re.sub('\r\n?', '\n', self.ui.body) # Normalize whitespace in title self.ui.title = ' '.join(self.ui.title.split()) # Check that there were any changes if self.ui.body == entry.body and self.ui.title == entry.title: self.error("You didn't make any changes!") return
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.