bugged
stringlengths
4
228k
fixed
stringlengths
0
96.3M
__index_level_0__
int64
0
481k
def tag(self, height=None, width=None, alt=None, **args): """ Generate an HTML IMG tag for this image, with customization. Arguments to self.tag() can be any valid attributes of an IMG tag. 'src' will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for 'height', 'width', and 'alt'. """ if not alt: alt=self.title_or_id()
def tag(self, height=None, width=None, alt=None, **args): """ Generate an HTML IMG tag for this image, with customization. Arguments to self.tag() can be any valid attributes of an IMG tag. 'src' will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for 'height', 'width', and 'alt'. """ if not alt: alt=self.title_or_id()
3,400
def tag(self, height=None, width=None, alt=None, **args): """ Generate an HTML IMG tag for this image, with customization. Arguments to self.tag() can be any valid attributes of an IMG tag. 'src' will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for 'height', 'width', and 'alt'. """ if not alt: alt=self.title_or_id()
def tag(self, height=None, width=None, alt=None, **args): """ Generate an HTML IMG tag for this image, with customization. Arguments to self.tag() can be any valid attributes of an IMG tag. 'src' will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for 'height', 'width', and 'alt'. """ if not alt: alt=self.title_or_id()
3,401
def tag(self, height=None, width=None, alt=None, **args): """ Generate an HTML IMG tag for this image, with customization. Arguments to self.tag() can be any valid attributes of an IMG tag. 'src' will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for 'height', 'width', and 'alt'. """ if not alt: alt=self.title_or_id()
def tag(self, height=None, width=None, alt=None, **args): """ Generate an HTML IMG tag for this image, with customization. Arguments to self.tag() can be any valid attributes of an IMG tag. 'src' will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for 'height', 'width', and 'alt'. """ if not alt: alt=self.title_or_id()
3,402
def tag(self, height=None, width=None, alt=None, **args): """ Generate an HTML IMG tag for this image, with customization. Arguments to self.tag() can be any valid attributes of an IMG tag. 'src' will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for 'height', 'width', and 'alt'. """ if not alt: alt=self.title_or_id()
def tag(self, height=None, width=None, alt=None, **args): """ Generate an HTML IMG tag for this image, with customization. Arguments to self.tag() can be any valid attributes of an IMG tag. 'src' will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for 'height', 'width', and 'alt'. """ if not alt: alt=self.title_or_id()
3,403
def filtered_manage_options(self, REQUEST=None):
def filtered_manage_options(self, REQUEST=None):
3,404
def apply(self, obj, url=None, depth=0, result=None, top=1): if result is None: result=StringIO() depth=self.depth url=urlfix(self.request['URL'], 'PROPFIND') url=urlbase(url) result.write('<?xml version="1.0" encoding="utf-8"?>\n' \ '<d:multistatus xmlns:d="DAV:">\n') iscol=isDavCollection(obj) if iscol and url[-1] != '/': url=url+'/' result.write('<d:response>\n<d:href>%s</d:href>\n' % safe_quote(url)) if hasattr(aq_base(obj), 'propertysheets'): propsets=obj.propertysheets.values() obsheets=obj.propertysheets else: davprops=DAVProps(obj) propsets=(davprops,) obsheets={'DAV:': davprops} if self.allprop: stats=[] for ps in propsets: if hasattr(aq_base(ps), 'dav__allprop'): stats.append(ps.dav__allprop()) stats=''.join(stats) or '<d:status>200 OK</d:status>\n' result.write(stats) elif self.propname: stats=[] for ps in propsets: if hasattr(aq_base(ps), 'dav__propnames'): stats.append(ps.dav__propnames()) stats=''.join(stats) or '<d:status>200 OK</d:status>\n' result.write(stats) elif self.propnames: rdict={} for name, ns in self.propnames: ps=obsheets.get(ns, None) if ps is not None and hasattr(aq_base(ps), 'dav__propstat'): stat=ps.dav__propstat(name, rdict) else: prop='<n:%s xmlns:n="%s"/>' % (name, ns) code='404 Not Found' if not rdict.has_key(code): rdict[code]=[prop] else: rdict[code].append(prop) keys=rdict.keys() keys.sort() for key in keys: result.write('<d:propstat>\n' \ ' <d:prop>\n' \ ) map(result.write, rdict[key]) result.write(' </d:prop>\n' \ ' <d:status>HTTP/1.1 %s</d:status>\n' \ '</d:propstat>\n' % key ) else: raise BadRequest, 'Invalid request' result.write('</d:response>\n') if depth in ('1', 'infinity') and iscol: for ob in obj.listDAVObjects(): if hasattr(ob,"meta_type"): if ob.meta_type=="Broken Because Product is Gone": continue dflag=hasattr(ob, '_p_changed') and (ob._p_changed == None) if hasattr(ob, '__locknull_resource__'): # Do nothing, a null resource shouldn't show up to DAV if dflag: ob._p_deactivate() elif hasattr(ob, '__dav_resource__'): uri=os.path.join(url, absattr(ob.id)) depth=depth=='infinity' and depth or 0 self.apply(ob, uri, depth, result, top=0) if dflag: ob._p_deactivate() if not top: return result result.write('</d:multistatus>')
def apply(self, obj, url=None, depth=0, result=None, top=1): if result is None: result=StringIO() depth=self.depth url=urlfix(self.request['URL'], 'PROPFIND') url=urlbase(url) result.write('<?xml version="1.0" encoding="utf-8"?>\n' \ '<d:multistatus xmlns:d="DAV:">\n') iscol=isDavCollection(obj) if iscol and url[-1] != '/': url=url+'/' result.write('<d:response>\n<d:href>%s</d:href>\n' % safe_quote(url)) if hasattr(aq_base(obj), 'propertysheets'): propsets=obj.propertysheets.values() obsheets=obj.propertysheets else: davprops=DAVProps(obj) propsets=(davprops,) obsheets={'DAV:': davprops} if self.allprop: stats=[] for ps in propsets: if hasattr(aq_base(ps), 'dav__allprop'): stats.append(ps.dav__allprop()) stats=''.join(stats) or '<d:status>200 OK</d:status>\n' result.write(stats) elif self.propname: stats=[] for ps in propsets: if hasattr(aq_base(ps), 'dav__propnames'): stats.append(ps.dav__propnames()) stats=''.join(stats) or '<d:status>200 OK</d:status>\n' result.write(stats) elif self.propnames: rdict={} for name, ns in self.propnames: ps=obsheets.get(ns, None) if ps is not None and hasattr(aq_base(ps), 'dav__propstat'): stat=ps.dav__propstat(name, rdict) else: prop='<n:%s xmlns:n="%s"/>' % (name, ns) code='404 Not Found' if not rdict.has_key(code): rdict[code]=[prop] else: rdict[code].append(prop) keys=rdict.keys() keys.sort() for key in keys: result.write('<d:propstat>\n' \ ' <d:prop>\n' \ ) map(result.write, rdict[key]) result.write(' </d:prop>\n' \ ' <d:status>HTTP/1.1 %s</d:status>\n' \ '</d:propstat>\n' % key ) else: raise BadRequest, 'Invalid request' result.write('</d:response>\n') if depth in ('1', 'infinity') and iscol: for ob in obj.listDAVObjects(): if hasattr(ob,"meta_type"): if ob.meta_type=="Broken Because Product is Gone": continue dflag=hasattr(ob, '_p_changed') and (ob._p_changed == None) if hasattr(ob, '__locknull_resource__'): # Do nothing, a null resource shouldn't show up to DAV if dflag: ob._p_deactivate() elif hasattr(ob, '__dav_resource__'): uri=urljoin(url, absattr(ob.id)) depth=depth=='infinity' and depth or 0 self.apply(ob, uri, depth, result, top=0) if dflag: ob._p_deactivate() if not top: return result result.write('</d:multistatus>')
3,405
def apply(self, obj, creator=None, depth='infinity', token=None, result=None, url=None, top=1): """ Apply, built for recursion (so that we may lock subitems of a collection if requested """
def apply(self, obj, creator=None, depth='infinity', token=None, result=None, url=None, top=1): """ Apply, built for recursion (so that we may lock subitems of a collection if requested """
3,406
def apply(self, obj, token, url=None, result=None, top=1): if result is None: result = StringIO() url = urlfix(url, 'UNLOCK') url = urlbase(url) iscol = isDavCollection(obj) if iscol and url[-1] != '/': url = url + '/' errmsg = None
def apply(self, obj, token, url=None, result=None, top=1): if result is None: result = StringIO() url = urlfix(url, 'UNLOCK') url = urlbase(url) iscol = isDavCollection(obj) if iscol and url[-1] != '/': url = url + '/' errmsg = None
3,407
def apply(self, obj, token, user, url=None, result=None, top=1): if result is None: result = StringIO() url = urlfix(url, 'DELETE') url = urlbase(url) iscol = isDavCollection(obj) errmsg = None parent = aq_parent(obj)
def apply(self, obj, token, user, url=None, result=None, top=1): if result is None: result = StringIO() url = urlfix(url, 'DELETE') url = urlbase(url) iscol = isDavCollection(obj) errmsg = None parent = aq_parent(obj)
3,408
def doc_strong(self, s, expr = re.compile(r'\*\*([%s%s%s\s]+?)\*\*' % (letters, digits, strongem_punc)).search #expr = re.compile(r'\s*\*\*([ \n\r%s0-9.:/;,\'\"\?\-\_\/\=\-\>\<\(\)]+)\*\*(?!\*|-)' % letters).search, # old expr, inconsistent punc, failed to cross newlines. ):
def doc_strong(self, s, expr = re.compile(r'\*\*([%s%s%s\s]+?)\*\*' % (letters, digits, strongem_punc)).search #expr = re.compile(r'\s*\*\*([ \n\r%s0-9.:/;,\'\"\?\-\_\/\=\-\>\<\(\)]+)\*\*(?!\*|-)' % letters).search, # old expr, inconsistent punc, failed to cross newlines. ):
3,409
def setVirtualRoot(self, path, hard=0): """ Treat the current publishing object as a VirtualRoot """ other = self.other if type(path) is type(''): path = path.split( '/') self._script[:] = map(quote, filter(None, path)) del self._steps[:] parents = other['PARENTS'] if hard: del parents[:-1] other['VirtualRootPhysicalPath'] = parents[-1].getPhysicalPath() self._resetURLS()
def setVirtualRoot(self, path, hard=0): """ Treat the current publishing object as a VirtualRoot """ other = self.other if isinstance(path, StringType) or isinstance(path, UnicodeType): path = path.split('/') self._script[:] = map(quote, filter(None, path)) del self._steps[:] parents = other['PARENTS'] if hard: del parents[:-1] other['VirtualRootPhysicalPath'] = parents[-1].getPhysicalPath() self._resetURLS()
3,410
def getPhysicalPath(self): '''Returns a path (an immutable sequence of strings) that can be used to access this object again later, for example in a copy/paste operation. getPhysicalRoot() and getPhysicalPath() are designed to operate together. ''' path = (self.id,) p = getattr(self,'aq_inner', None) if p is not None: path = p.aq_parent.getPhysicalPath() + path print path return path
def getPhysicalPath(self): '''Returns a path (an immutable sequence of strings) that can be used to access this object again later, for example in a copy/paste operation. getPhysicalRoot() and getPhysicalPath() are designed to operate together. ''' path = (self.id,) p = getattr(self,'aq_inner', None) if p is not None: path = p.aq_parent.getPhysicalPath() + path return path
3,411
def sort(sequence, sort=(), _=None, mapping=0): """ - sequence is a sequence of objects to be sorted - sort is a sequence of tuples (key,func,direction) that define the sort order: - key is the name of an attribute to sort the objects by - func is the name of a comparison function. This parameter is optional allowed values: - "cmp" -- the standard comparison function (default) - "nocase" -- case-insensitive comparison - "strcoll" or "locale" -- locale-aware string comparison - "strcoll_nocase" or "locale_nocase" -- locale-aware case-insensitive string comparison - "xxx" -- a user-defined comparison function - direction -- defines the sort direction for the key (optional). (allowed values: "asc" (default) , "desc") """ need_sortfunc = 0 if sort: for s in sort: if len(s) > 1: # extended sort if there is reference to... # ...comparison function or sort order, even if they are "cmp" and "asc" need_sortfunc = 1 break sortfields = sort # multi sort = key1,key2 multsort = len(sortfields) > 1 # flag: is multiple sort if need_sortfunc: # prepare the list of functions and sort order multipliers sf_list = make_sortfunctions(sortfields, _) # clean the mess a bit if multsort: # More than one sort key. sortfields = map(lambda x: x[0], sf_list) else: sort = sf_list[0][0] elif sort: if multsort: # More than one sort key. sortfields = map(lambda x: x[0], sort) else: sort = sort[0][0] isort=not sort s=[] for client in sequence: k = None if type(client)==TupleType and len(client)==2: if isort: k=client[0] v=client[1] else: if isort: k=client v=client if sort: if multsort: # More than one sort key. k = [] for sk in sortfields: try: if mapping: akey = v[sk] else: akey = getattr(v, sk) except (AttributeError, KeyError): akey = None if not basic_type(akey): try: akey = akey() except: pass k.append(akey) else: # One sort key. try: if mapping: k = v[sort] else: k = getattr(v, sort) except AttributeError, KeyError: k = None if not basic_type(type(k)): try: k = k() except: pass s.append((k,client)) if need_sortfunc: by = SortBy(multsort, sf_list) s.sort(by) else: s.sort() sequence=[] for k, client in s: sequence.append(client) return sequence
def sort(sequence, sort=(), _=None, mapping=0): """ - sequence is a sequence of objects to be sorted - sort is a sequence of tuples (key,func,direction) that define the sort order: - key is the name of an attribute to sort the objects by - func is the name of a comparison function. This parameter is optional allowed values: - "cmp" -- the standard comparison function (default) - "nocase" -- case-insensitive comparison - "strcoll" or "locale" -- locale-aware string comparison - "strcoll_nocase" or "locale_nocase" -- locale-aware case-insensitive string comparison - "xxx" -- a user-defined comparison function - direction -- defines the sort direction for the key (optional). (allowed values: "asc" (default) , "desc") """ need_sortfunc = 0 if sort: for s in sort: if len(s) > 1: # extended sort if there is reference to... # ...comparison function or sort order, even if they are "cmp" and "asc" need_sortfunc = 1 break sortfields = sort # multi sort = key1,key2 multsort = len(sortfields) > 1 # flag: is multiple sort if need_sortfunc: # prepare the list of functions and sort order multipliers sf_list = make_sortfunctions(sortfields, _) # clean the mess a bit if multsort: # More than one sort key. sortfields = map(lambda x: x[0], sf_list) else: sort = sf_list[0][0] elif sort: if multsort: # More than one sort key. sortfields = map(lambda x: x[0], sort) else: sort = sort[0][0] isort=not sort s=[] for client in sequence: k = None if type(client)==TupleType and len(client)==2: if isort: k=client[0] v=client[1] else: if isort: k=client v=client if sort: if multsort: # More than one sort key. k = [] for sk in sortfields: try: if mapping: akey = v[sk] else: akey = getattr(v, sk) except (AttributeError, KeyError): akey = None if not basic_type(akey): try: akey = akey() except: pass k.append(akey) else: # One sort key. try: if mapping: k = v[sort] else: k = getattr(v, sort) except (AttributeError, KeyError): k = None if not basic_type(type(k)): try: k = k() except: pass s.append((k,client)) if need_sortfunc: by = SortBy(multsort, sf_list) s.sort(by) else: s.sort() sequence=[] for k, client in s: sequence.append(client) return sequence
3,412
def __init__( self, id, ignore_ex=None, call_methods=None, extra=None, caller=None): """Create an unindex
def __init__( self, id, ignore_ex=None, call_methods=None, extra=None, caller=None): """Create an unindex
3,413
def __init__( self, id, ignore_ex=None, call_methods=None, extra=None, caller=None): """Create an unindex
def __init__( self, id, ignore_ex=None, call_methods=None, extra=None, caller=None): """Create an unindex
3,414
def removeForwardIndexEntry(self, entry, documentId): """Take the entry provided and remove any reference to documentId in its entry in the index. """ indexRow = self._index.get(entry, _marker) if indexRow is not _marker: try: indexRow.remove(documentId) if not indexRow: del self._index[entry] self._length.change(-1) except AttributeError: # index row is an int del self._index[entry] self._length.change(-1) except: LOG.error('%s: unindex_object could not remove ' 'documentId %s from index %s. This ' 'should not happen.' % (self.__class__.__name__, str(documentId), str(self.id)), exc_info=sys.exc_info()) else: LOG.error('%s: unindex_object tried to retrieve set %s ' 'from index %s but couldn\'t. This ' 'should not happen.' % (self.__class__.__name__, repr(entry), str(self.id)))
def removeForwardIndexEntry(self, entry, documentId): """Take the entry provided and remove any reference to documentId in its entry in the index. """ indexRow = self._index.get(entry, _marker) if indexRow is not _marker: try: indexRow.remove(documentId) if not indexRow: del self._index[entry] self._length.change(-1) except AttributeError: # index row is an int del self._index[entry] self._length.change(-1) except: LOG.error('%s: unindex_object could not remove ' 'documentId %s from index %s. This ' 'should not happen.' % (self.__class__.__name__, str(documentId), str(self.id)), exc_info=sys.exc_info()) else: LOG.error('%s: unindex_object tried to retrieve set %s ' 'from index %s but couldn\'t. This ' 'should not happen.' % (self.__class__.__name__, repr(entry), str(self.id)))
3,415
def removeForwardIndexEntry(self, entry, documentId): """Take the entry provided and remove any reference to documentId in its entry in the index. """ indexRow = self._index.get(entry, _marker) if indexRow is not _marker: try: indexRow.remove(documentId) if not indexRow: del self._index[entry] self._length.change(-1) except AttributeError: # index row is an int del self._index[entry] self._length.change(-1) except: LOG.error('%s: unindex_object could not remove ' 'documentId %s from index %s. This ' 'should not happen.' % (self.__class__.__name__, str(documentId), str(self.id)), exc_info=sys.exc_info()) else: LOG.error('%s: unindex_object tried to retrieve set %s ' 'from index %s but couldn\'t. This ' 'should not happen.' % (self.__class__.__name__, repr(entry), str(self.id)))
def removeForwardIndexEntry(self, entry, documentId): """Take the entry provided and remove any reference to documentId in its entry in the index. """ indexRow = self._index.get(entry, _marker) if indexRow is not _marker: try: indexRow.remove(documentId) if not indexRow: del self._index[entry] self._length.change(-1) except AttributeError: # index row is an int del self._index[entry] self._length.change(-1) except: LOG.error('%s: unindex_object could not remove ' 'documentId %s from index %s. This ' 'should not happen.' % (self.__class__.__name__, str(documentId), str(self.id)), exc_info=sys.exc_info()) else: LOG.error('%s: unindex_object tried to retrieve set %s ' 'from index %s but couldn\'t. This ' 'should not happen.' % (self.__class__.__name__, repr(entry), str(self.id)))
3,416
def removeForwardIndexEntry(self, entry, documentId): """Take the entry provided and remove any reference to documentId in its entry in the index. """ indexRow = self._index.get(entry, _marker) if indexRow is not _marker: try: indexRow.remove(documentId) if not indexRow: del self._index[entry] self._length.change(-1) except AttributeError: # index row is an int del self._index[entry] self._length.change(-1) except: LOG.error('%s: unindex_object could not remove ' 'documentId %s from index %s. This ' 'should not happen.' % (self.__class__.__name__, str(documentId), str(self.id)), exc_info=sys.exc_info()) else: LOG.error('%s: unindex_object tried to retrieve set %s ' 'from index %s but couldn\'t. This ' 'should not happen.' % (self.__class__.__name__, repr(entry), str(self.id)))
def removeForwardIndexEntry(self, entry, documentId): """Take the entry provided and remove any reference to documentId in its entry in the index. """ indexRow = self._index.get(entry, _marker) if indexRow is not _marker: try: indexRow.remove(documentId) if not indexRow: del self._index[entry] self._length.change(-1) except AttributeError: # index row is an int del self._index[entry] self._length.change(-1) except: LOG.error('%s: unindex_object could not remove ' 'documentId %s from index %s. This ' 'should not happen.' % (self.__class__.__name__, str(documentId), str(self.id)), exc_info=sys.exc_info()) else: LOG.error('%s: unindex_object tried to retrieve set %s ' 'from index %s but couldn\'t. This ' 'should not happen.' % (self.__class__.__name__, repr(entry), str(self.id)))
3,417
def removeForwardIndexEntry(self, entry, documentId): """Take the entry provided and remove any reference to documentId in its entry in the index. """ indexRow = self._index.get(entry, _marker) if indexRow is not _marker: try: indexRow.remove(documentId) if not indexRow: del self._index[entry] self._length.change(-1) except AttributeError: # index row is an int del self._index[entry] self._length.change(-1) except: LOG.error('%s: unindex_object could not remove ' 'documentId %s from index %s. This ' 'should not happen.' % (self.__class__.__name__, str(documentId), str(self.id)), exc_info=sys.exc_info()) else: LOG.error('%s: unindex_object tried to retrieve set %s ' 'from index %s but couldn\'t. This ' 'should not happen.' % (self.__class__.__name__, repr(entry), str(self.id)))
def removeForwardIndexEntry(self, entry, documentId): """Take the entry provided and remove any reference to documentId in its entry in the index. """ indexRow = self._index.get(entry, _marker) if indexRow is not _marker: try: indexRow.remove(documentId) if not indexRow: del self._index[entry] self._length.change(-1) except AttributeError: # index row is an int del self._index[entry] self._length.change(-1) except: LOG.error('%s: unindex_object could not remove ' 'documentId %s from index %s. This ' 'should not happen.' % (self.__class__.__name__, str(documentId), str(self.id)), exc_info=sys.exc_info()) else: LOG.error('%s: unindex_object tried to retrieve set %s ' 'from index %s but couldn\'t. This ' 'should not happen.' % (self.__class__.__name__, repr(entry), str(self.id)))
3,418
def index_object(self, documentId, obj, threshold=None): """ wrapper to handle indexing of multiple attributes """
def index_object(self, documentId, obj, threshold=None): """ wrapper to handle indexing of multiple attributes """
3,419
def unindex_object(self, documentId): """ Unindex the object with integer id 'documentId' and don't raise an exception if we fail """ unindexRecord = self._unindex.get(documentId, _marker) if unindexRecord is _marker: return None
def unindex_object(self, documentId): """ Unindex the object with integer id 'documentId' and don't raise an exception if we fail """ unindexRecord = self._unindex.get(documentId, _marker) if unindexRecord is _marker: return None
3,420
def getIndexSourceNames(self): """ return sequence of indexed attributes """ try: return self.indexed_attrs except: return [ self.id ]
def getIndexSourceNames(self): """ return sequence of indexed attributes """ try: return self.indexed_attrs except: return [ self.id ]
3,421
def uniqueValues(self, name=None, withLengths=0): """returns the unique values for name
def uniqueValues(self, name=None, withLengths=0): """returns the unique values for name
3,422
def keyForDocument(self, id): # This method is superceded by documentToKeyMap return self._unindex[id]
def keyForDocument(self, id): # This method is superceded by documentToKeyMap return self._unindex[id]
3,423
def documentToKeyMap(self): return self._unindex
def documentToKeyMap(self): return self._unindex
3,424
def write(self, text): """ Change the Script by parsing a read()-style source text. """ self._validateProxy() mdata = self._metadata_map() bindmap = self.getBindingAssignments().getAssignedNames() bup = 0
def write(self, text): """ Change the Script by parsing a read()-style source text. """ self._validateProxy() mdata = self._metadata_map() bindmap = self.getBindingAssignments().getAssignedNames() bup = 0
3,425
def careful_getattr(md, inst, name): if name[:1]!='_': validate=md.validate if validate is None: return getattr(inst, name) if hasattr(inst,'aq_acquire'): return inst.aq_acquire(name, validate, md) v=getattr(inst, name) if validate(inst,inst,name,v,md): return v raise ValidationError, name
def careful_getattr(md, inst, name): if name[:1]!='_': validate=md.validate if validate is None: return v if hasattr(inst,'aq_acquire'): return inst.aq_acquire(name, validate, md) v=getattr(inst, name) if validate(inst,inst,name,v,md): return v raise ValidationError, name
3,426
def careful_getattr(md, inst, name): if name[:1]!='_': validate=md.validate if validate is None: return getattr(inst, name) if hasattr(inst,'aq_acquire'): return inst.aq_acquire(name, validate, md) v=getattr(inst, name) if validate(inst,inst,name,v,md): return v raise ValidationError, name
def careful_getattr(md, inst, name): if name[:1]!='_': validate=md.validate if validate is None: return getattr(inst, name) if hasattr(inst,'aq_acquire'): return inst.aq_acquire(name, validate, md) if validate(inst,inst,name,v,md): return v raise ValidationError, name
3,427
def careful_hasattr(md, inst, name): try: if name[:1]!='_': validate=md.validate if validate is None: return hasattr(inst, name) if hasattr(inst,'aq_acquire'): inst.aq_acquire(name, validate, md) return 1 v=getattr(inst, name) if validate(inst,inst,name,v,md): return 1 except: pass return 0
def careful_hasattr(md, inst, name): v=getattr(inst, name, _marker) if v is not _marker: try: if name[:1]!='_': validate=md.validate if validate is None: return 1 if hasattr(inst,'aq_acquire'): inst.aq_acquire(name, validate, md) return 1 if validate(inst,inst,name,v,md): return 1 except: pass return 0
3,428
def __init__(self, request, iid, options=[]): """ parse a request from the ZPublisher and return a uniform datastructure back to the _apply_index() method of the index
def __init__(self, request, iid, options=[]): """ parse a request from the ZPublisher and return a uniform datastructure back to the _apply_index() method of the index
3,429
def index(self, isrc, srckey): '''\ index(src, srckey)
def index(self, isrc, srckey): '''\ index(src, srckey)
3,430
def __getitem__(self, key): '''\ Get the ResultList objects for the inverted key, key. The key may be a regular expression, in which case a regular expression match is done. The key may be a string, in which case an case-insensitive match is done. ''' index = self._index_object synstop = self.synstop List = self.list_class
def __getitem__(self, key): '''\ Get the ResultList objects for the inverted key, key. The key may be a regular expression, in which case a regular expression match is done. The key may be a string, in which case an case-insensitive match is done. ''' index = self._index_object synstop = self.synstop List = self.list_class
3,431
def open_bobobase(): # Open the application database Bobobase=Globals.Bobobase=Globals.PickleDictionary(Globals.BobobaseName) product_dir=os.path.join(SOFTWARE_HOME,'lib/python/Products') __traceback_info__=sys.path try: app=Bobobase['Application'] except KeyError: app=Application() app._init() Bobobase['Application']=app get_transaction().commit() # Backward compatibility if not hasattr(app, 'Control_Panel'): cpl=ApplicationManager() cpl._init() app._setObject('Control_Panel', cpl) get_transaction().commit() if not hasattr(app, 'standard_error_message'): import Document Document.manage_addDocument( app, 'standard_error_message', 'Standard Error Message', _standard_error_msg) get_transaction().commit() import jim; jim.debug() install_products(app) get_transaction().commit() return Bobobase
def open_bobobase(): # Open the application database Bobobase=Globals.Bobobase=Globals.PickleDictionary(Globals.BobobaseName) product_dir=os.path.join(SOFTWARE_HOME,'lib/python/Products') __traceback_info__=sys.path try: app=Bobobase['Application'] except KeyError: app=Application() app._init() Bobobase['Application']=app get_transaction().commit() # Backward compatibility if not hasattr(app, 'Control_Panel'): cpl=ApplicationManager() cpl._init() app._setObject('Control_Panel', cpl) get_transaction().commit() if not hasattr(app, 'standard_error_message'): import Document Document.manage_addDocument( app, 'standard_error_message', 'Standard Error Message', _standard_error_msg) get_transaction().commit() install_products(app) get_transaction().commit() return Bobobase
3,432
def keyForDocument(self, id): return self._unindex(id)
def keyForDocument(self, id): return self._unindex(id)
3,433
def dav__displayname(self): return absattr(self.v_self().title_or_id())
def dav__displayname(self): return absattr(self.v_self().title_or_id())
3,434
def searchResults(self, REQUEST=None, used=None, **kw): # Get search arguments: if REQUEST is None and not kw: try: REQUEST=self.REQUEST except AttributeError: pass if kw: if REQUEST: m=MultiMapping() m.push(REQUEST) m.push(kw) kw=m elif REQUEST: kw=REQUEST
def searchResults(self, REQUEST=None, used=None, **kw): # Get search arguments: if REQUEST is None and not kw: try: REQUEST=self.REQUEST except AttributeError: pass if kw: if REQUEST: m=MultiMapping() m.push(REQUEST) m.push(kw) kw=m elif REQUEST: kw=REQUEST
3,435
def __call__(self, REQUEST=None, __ick__=None, src__=0, **kw): """Call the database method
def __call__(self, REQUEST=None, __ick__=None, src__=0, **kw): """Call the database method
3,436
def _print_traceback(self, msg, err, test, errlist): if self.showAll or self.dots or self._progress: self.stream.writeln("\n") self._lastWidth = 0
def _handle_problem(self, err, test, errlist): if self._debug: raise err[0], err[1], err[2] if errlist is self.errors: prefix = 'Error' else: prefix = 'Failure' tb = "".join(traceback.format_exception(*err)) if self._progress: self.stream.writeln("\r") self.stream.writeln("%s in test %s" % (prefix,test)) self.stream.writeln(tb) self._lastWidth = 0
3,437
def _print_traceback(self, msg, err, test, errlist): if self.showAll or self.dots or self._progress: self.stream.writeln("\n") self._lastWidth = 0
def _print_traceback(self, msg, err, test, errlist): if self.showAll or self.dots or self._progress: self.stream.writeln("\n") self._lastWidth = 0
3,438
def addError(self, test, err): if self._progress: self.stream.write("\r") if self._debug: raise err[0], err[1], err[2] self._print_traceback("Error in test %s" % test, err, test, self.errors)
def addError(self, test, err): if self._progress: self.stream.write("\r") if self._debug: raise err[0], err[1], err[2] self._print_traceback("Error in test %s" % test, err, test, self.errors)
3,439
def addFailure(self, test, err): if self._progress: self.stream.write("\r") if self._debug: raise err[0], err[1], err[2] self._print_traceback("Failure in test %s" % test, err, test, self.failures)
def addFailure(self, test, err): if self._progress: self.stream.write("\r") if self._debug: raise err[0], err[1], err[2] self._print_traceback("Failure in test %s" % test, err, test, self.failures)
3,440
def upload_html(object, f): dir, name = os.path.split(f) f=open(f) # There is a Document bugs that causes file uploads to fail. # Waaa. This will be fixed in 1.10.2. f=f.read() if old: call(object.manage_addDocument, id=name, file=f) else: call(object.manage_addDTMLDocument, id=name, file=f)
def upload_html(object, f): dir, name = os.path.split(f) f=open(f) # There is a Document bugs that causes file uploads to fail. # Waaa. This will be fixed in 1.10.2. title, head, body = parse_html(f) if old: call(object.manage_addDocument, id=name, file=f) else: call(object.manage_addDTMLDocument, id=name, file=f)
3,441
def upload_html(object, f): dir, name = os.path.split(f) f=open(f) # There is a Document bugs that causes file uploads to fail. # Waaa. This will be fixed in 1.10.2. f=f.read() if old: call(object.manage_addDocument, id=name, file=f) else: call(object.manage_addDTMLDocument, id=name, file=f)
def upload_html(object, f): dir, name = os.path.split(f) f=open(f) # There is a Document bugs that causes file uploads to fail. # Waaa. This will be fixed in 1.10.2. f=f.read() if old: call(object.manage_addDocument, id=name, file=body) else: call(object.manage_addDTMLDocument, id=name, file=f)
3,442
def upload_html(object, f): dir, name = os.path.split(f) f=open(f) # There is a Document bugs that causes file uploads to fail. # Waaa. This will be fixed in 1.10.2. f=f.read() if old: call(object.manage_addDocument, id=name, file=f) else: call(object.manage_addDTMLDocument, id=name, file=f)
def upload_html(object, f): dir, name = os.path.split(f) f=open(f) # There is a Document bugs that causes file uploads to fail. # Waaa. This will be fixed in 1.10.2. f=f.read() if old: call(object.manage_addDocument, id=name, file=f) else: call(object.manage_addDTMLDocument, id=name, title=title, file=body) if head: object=object.__class__(object.url+'/'+name, username=object.username, password=object.password) call(object.manage_addProperty, id="loadsite-head", type="text", value=head)
3,443
def specialcommand(self, line, results, first): assert line.startswith("/") line = line[1:] if not line: n = first else: try: n = int(line) - 1 except: print "Huh?" return if n < 0 or n >= len(results): print "Out of range" return docid, score = results[n] path = self.docpaths[docid] i = path.rfind("/") assert i > 0 folder = path[:i] n = path[i+1:] cmd = "show +%s %s" % (folder, n) if os.getenv("DISPLAY"): os.system("xterm -e %s &" % cmd) else: os.system(cmd)
def specialcommand(self, line, results, first): assert line.startswith("/") line = line[1:] if not line: n = first else: try: n = int(line) - 1 except: print "Huh?" return if n < 0 or n >= len(results): print "Out of range" return docid, score = results[n] path = self.docpaths[docid] i = path.rfind("/") assert i > 0 folder = path[:i] n = path[i+1:] cmd = "show +%s %s" % (folder, n) if os.getenv("DISPLAY"): os.system("xterm -e sh -c '%s | less' &" % cmd) else: os.system(cmd)
3,444
def formatresults(self, text, results, maxlines=MAXLINES, lo=0, hi=sys.maxint): stop = self.stopdict.has_key words = [w for w in re.findall(r"\w+\*?", text.lower()) if not stop(w)] pattern = r"\b(" + "|".join(words) + r")\b" pattern = pattern.replace("*", ".*") # glob -> re syntax prog = re.compile(pattern, re.IGNORECASE) print '='*70 rank = lo qw = max(1, self.index.query_weight(text)) factor = 100.0 / qw / 1024 for docid, score in results[lo:hi]: rank += 1 path = self.docpaths[docid] score = min(100, int(score * factor)) print "Rank: %d Score: %d%% File: %s" % (rank, score, path) path = os.path.join(self.mh.getpath(), path) fp = open(path) msg = mhlib.Message("<folder>", 0, fp) for header in "From", "To", "Cc", "Bcc", "Subject", "Date": h = msg.getheader(header) if h: print "%-8s %s" % (header+":", h) text = self.getmessagetext(msg) if text: print nleft = maxlines for part in text: for line in part.splitlines(): if prog.search(line): print line nleft -= 1 if nleft <= 0: break if nleft <= 0: break print '-'*70
def formatresults(self, text, results, maxlines=MAXLINES, lo=0, hi=sys.maxint): stop = self.stopdict.has_key words = [w for w in re.findall(r"\w+\*?", text.lower()) if not stop(w)] pattern = r"\b(" + "|".join(words) + r")\b" pattern = pattern.replace("*", ".*") # glob -> re syntax prog = re.compile(pattern, re.IGNORECASE) print '='*70 rank = lo qw = self.index.query_weight(text) for docid, score in results[lo:hi]: rank += 1 path = self.docpaths[docid] score = min(100, int(score * factor)) print "Rank: %d Score: %d%% File: %s" % (rank, score, path) path = os.path.join(self.mh.getpath(), path) fp = open(path) msg = mhlib.Message("<folder>", 0, fp) for header in "From", "To", "Cc", "Bcc", "Subject", "Date": h = msg.getheader(header) if h: print "%-8s %s" % (header+":", h) text = self.getmessagetext(msg) if text: print nleft = maxlines for part in text: for line in part.splitlines(): if prog.search(line): print line nleft -= 1 if nleft <= 0: break if nleft <= 0: break print '-'*70
3,445
def formatresults(self, text, results, maxlines=MAXLINES, lo=0, hi=sys.maxint): stop = self.stopdict.has_key words = [w for w in re.findall(r"\w+\*?", text.lower()) if not stop(w)] pattern = r"\b(" + "|".join(words) + r")\b" pattern = pattern.replace("*", ".*") # glob -> re syntax prog = re.compile(pattern, re.IGNORECASE) print '='*70 rank = lo qw = max(1, self.index.query_weight(text)) factor = 100.0 / qw / 1024 for docid, score in results[lo:hi]: rank += 1 path = self.docpaths[docid] score = min(100, int(score * factor)) print "Rank: %d Score: %d%% File: %s" % (rank, score, path) path = os.path.join(self.mh.getpath(), path) fp = open(path) msg = mhlib.Message("<folder>", 0, fp) for header in "From", "To", "Cc", "Bcc", "Subject", "Date": h = msg.getheader(header) if h: print "%-8s %s" % (header+":", h) text = self.getmessagetext(msg) if text: print nleft = maxlines for part in text: for line in part.splitlines(): if prog.search(line): print line nleft -= 1 if nleft <= 0: break if nleft <= 0: break print '-'*70
def formatresults(self, text, results, maxlines=MAXLINES, lo=0, hi=sys.maxint): stop = self.stopdict.has_key words = [w for w in re.findall(r"\w+\*?", text.lower()) if not stop(w)] pattern = r"\b(" + "|".join(words) + r")\b" pattern = pattern.replace("*", ".*") # glob -> re syntax prog = re.compile(pattern, re.IGNORECASE) print '='*70 rank = lo qw = max(1, self.index.query_weight(text)) factor = 100.0 / qw / 1024 for docid, score in results[lo:hi]: rank += 1 path = self.docpaths[docid] score = 100.0*score/qw print "Rank: %d Score: %d%% File: %s" % (rank, score, path) path = os.path.join(self.mh.getpath(), path) fp = open(path) msg = mhlib.Message("<folder>", 0, fp) for header in "From", "To", "Cc", "Bcc", "Subject", "Date": h = msg.getheader(header) if h: print "%-8s %s" % (header+":", h) text = self.getmessagetext(msg) if text: print nleft = maxlines for part in text: for line in part.splitlines(): if prog.search(line): print line nleft -= 1 if nleft <= 0: break if nleft <= 0: break print '-'*70
3,446
def MOVE(self, REQUEST, RESPONSE): """Move a resource to a new location. Though we may later try to make a move appear seamless across namespaces (e.g. from Zope to Apache), MOVE is currently only supported within the Zope namespace.""" self.dav__init(REQUEST, RESPONSE) self.dav__validate(self, 'DELETE', REQUEST) if not hasattr(aq_base(self), 'cb_isMoveable') or \ not self.cb_isMoveable(): raise MethodNotAllowed, 'This object may not be moved.'
def MOVE(self, REQUEST, RESPONSE): """Move a resource to a new location. Though we may later try to make a move appear seamless across namespaces (e.g. from Zope to Apache), MOVE is currently only supported within the Zope namespace.""" self.dav__init(REQUEST, RESPONSE) self.dav__validate(self, 'DELETE', REQUEST) if not hasattr(aq_base(self), 'cb_isMoveable') or \ not self.cb_isMoveable(): raise MethodNotAllowed, 'This object may not be moved.'
3,447
def __save__(self): pass
def __save__(self): pass
3,448
def install_products(app): # Install a list of products into the basic folder class, so # that all folders know about top-level objects, aka products path_join=os.path.join product_dir=path_join(SOFTWARE_HOME,'Products') isdir=os.path.isdir exists=os.path.exists DictType=type({}) from Folder import Folder folder_permissions={} for p in Folder.__ac_permissions__: permission, names = p[:2] folder_permissions[permission]=names meta_types=list(Folder.dynamic_meta_types) product_names=os.listdir(product_dir) product_names.sort() global_dict=globals() silly=('__doc__',) for product_name in product_names: package_dir=path_join(product_dir, product_name) if not isdir(package_dir): continue if not exists(path_join(package_dir, '__init__.py')): if not exists(path_join(package_dir, '__init__.pyc')): continue product=__import__("Products.%s" % product_name, global_dict, global_dict, silly) permissions={} new_permissions={} for permission, names in pgetattr(product, '__ac_permissions__', ()): if names: for name in names: permissions[name]=permission elif not folder_permissions.has_key(permission): new_permissions[permission]=() for meta_type in pgetattr(product, 'meta_types', ()): if product_name=='OFSP': meta_types.insert(0,meta_type) else: meta_types.append(meta_type) name=meta_type['name'] for name,method in pgetattr(product, 'methods', {}).items(): if not hasattr(Folder, name): setattr(Folder, name, method) if name[-9:]=='__roles__': continue # Just setting roles if (permissions.has_key(name) and not folder_permissions.has_key(permissions[name])): permission=permissions[name] if new_permissions.has_key(permission): new_permissions[permission].append(name) else: new_permissions[permission]=[name] if new_permissions: new_permissions=new_permissions.items() for permission, names in new_permissions: folder_permissions[permission]=names new_permissions.sort() Folder.__dict__['__ac_permissions__']=tuple( list(Folder.__ac_permissions__)+new_permissions) misc_=pgetattr(product, 'misc_', {}) if type(misc_) is DictType: misc_=Misc_(product_name, misc_) Application.misc_.__dict__[product_name]=misc_ # Set up dynamic project information. App.Product.initializeProduct(product_name, package_dir, app) Folder.dynamic_meta_types=tuple(meta_types) Globals.default__class_init__(Folder)
def install_products(app): # Install a list of products into the basic folder class, so # that all folders know about top-level objects, aka products path_join=os.path.join product_dir=path_join(SOFTWARE_HOME,'Products') isdir=os.path.isdir exists=os.path.exists DictType=type({}) from Folder import Folder folder_permissions={} for p in Folder.__ac_permissions__: permission, names = p[:2] folder_permissions[permission]=names meta_types=list(Folder.dynamic_meta_types) product_names=os.listdir(product_dir) product_names.sort() global_dict=globals() silly=('__doc__',) for product_name in product_names: package_dir=path_join(product_dir, product_name) if not isdir(package_dir): continue if not exists(path_join(package_dir, '__init__.py')): if not exists(path_join(package_dir, '__init__.pyc')): continue product=__import__("Products.%s" % product_name, global_dict, global_dict, silly) permissions={} new_permissions={} for permission, names in pgetattr(product, '__ac_permissions__', ()): if names: for name in names: permissions[name]=permission elif not folder_permissions.has_key(permission): new_permissions[permission]=() for meta_type in pgetattr(product, 'meta_types', ()): if product_name=='OFSP': meta_types.insert(0,meta_type) else: meta_types.append(meta_type) name=meta_type['name'] for name,method in pgetattr(product, 'methods', {}).items(): if not hasattr(Folder, name): setattr(Folder, name, method) if name[-9:]=='__roles__': continue # Just setting roles if (permissions.has_key(name) and not folder_permissions.has_key(permissions[name])): permission=permissions[name] if new_permissions.has_key(permission): new_permissions[permission].append(name) else: new_permissions[permission]=[name] if new_permissions: new_permissions=new_permissions.items() for permission, names in new_permissions: folder_permissions[permission]=names new_permissions.sort() Folder.__dict__['__ac_permissions__']=tuple( list(Folder.__ac_permissions__)+new_permissions) misc_=pgetattr(product, 'misc_', {}) if type(misc_) is DictType: misc_=Misc_(product_name, misc_) Application.misc_.__dict__[product_name]=misc_ # Set up dynamic project information. App.Product.initializeProduct(product, product_name, package_dir, app) Folder.dynamic_meta_types=tuple(meta_types) Globals.default__class_init__(Folder)
3,449
def install_products(app): # Install a list of products into the basic folder class, so # that all folders know about top-level objects, aka products path_join=os.path.join product_dir=path_join(SOFTWARE_HOME,'Products') isdir=os.path.isdir exists=os.path.exists DictType=type({}) from Folder import Folder folder_permissions={} for p in Folder.__ac_permissions__: permission, names = p[:2] folder_permissions[permission]=names meta_types=list(Folder.dynamic_meta_types) product_names=os.listdir(product_dir) product_names.sort() global_dict=globals() silly=('__doc__',) for product_name in product_names: package_dir=path_join(product_dir, product_name) if not isdir(package_dir): continue if not exists(path_join(package_dir, '__init__.py')): if not exists(path_join(package_dir, '__init__.pyc')): continue product=__import__("Products.%s" % product_name, global_dict, global_dict, silly) permissions={} new_permissions={} for permission, names in pgetattr(product, '__ac_permissions__', ()): if names: for name in names: permissions[name]=permission elif not folder_permissions.has_key(permission): new_permissions[permission]=() for meta_type in pgetattr(product, 'meta_types', ()): if product_name=='OFSP': meta_types.insert(0,meta_type) else: meta_types.append(meta_type) name=meta_type['name'] for name,method in pgetattr(product, 'methods', {}).items(): if not hasattr(Folder, name): setattr(Folder, name, method) if name[-9:]=='__roles__': continue # Just setting roles if (permissions.has_key(name) and not folder_permissions.has_key(permissions[name])): permission=permissions[name] if new_permissions.has_key(permission): new_permissions[permission].append(name) else: new_permissions[permission]=[name] if new_permissions: new_permissions=new_permissions.items() for permission, names in new_permissions: folder_permissions[permission]=names new_permissions.sort() Folder.__dict__['__ac_permissions__']=tuple( list(Folder.__ac_permissions__)+new_permissions) misc_=pgetattr(product, 'misc_', {}) if type(misc_) is DictType: misc_=Misc_(product_name, misc_) Application.misc_.__dict__[product_name]=misc_ # Set up dynamic project information. App.Product.initializeProduct(product_name, package_dir, app) Folder.dynamic_meta_types=tuple(meta_types) Globals.default__class_init__(Folder)
def install_products(app): # Install a list of products into the basic folder class, so # that all folders know about top-level objects, aka products path_join=os.path.join product_dir=path_join(SOFTWARE_HOME,'Products') isdir=os.path.isdir exists=os.path.exists DictType=type({}) from Folder import Folder folder_permissions={} for p in Folder.__ac_permissions__: permission, names = p[:2] folder_permissions[permission]=names meta_types=list(Folder.dynamic_meta_types) product_names=os.listdir(product_dir) product_names.sort() global_dict=globals() silly=('__doc__',) for product_name in product_names: package_dir=path_join(product_dir, product_name) if not isdir(package_dir): continue if not exists(path_join(package_dir, '__init__.py')): if not exists(path_join(package_dir, '__init__.pyc')): continue product=__import__("Products.%s" % product_name, global_dict, global_dict, silly) permissions={} new_permissions={} for permission, names in pgetattr(product, '__ac_permissions__', ()): if names: for name in names: permissions[name]=permission elif not folder_permissions.has_key(permission): new_permissions[permission]=() for meta_type in pgetattr(product, 'meta_types', ()): if product_name=='OFSP': meta_types.insert(0,meta_type) else: meta_types.append(meta_type) name=meta_type['name'] for name,method in pgetattr(product, 'methods', {}).items(): if not hasattr(Folder, name): setattr(Folder, name, method) if name[-9:]=='__roles__': continue # Just setting roles if (permissions.has_key(name) and not folder_permissions.has_key(permissions[name])): permission=permissions[name] if new_permissions.has_key(permission): new_permissions[permission].append(name) else: new_permissions[permission]=[name] if new_permissions: new_permissions=new_permissions.items() for permission, names in new_permissions: folder_permissions[permission]=names new_permissions.sort() Folder.__dict__['__ac_permissions__']=tuple( list(Folder.__ac_permissions__)+new_permissions) misc_=pgetattr(product, 'misc_', {}) if type(misc_) is DictType: misc_=Misc_(product_name, misc_) Application.misc_.__dict__[product_name]=misc_ # Set up dynamic project information. App.Product.initializeProduct(product_name, package_dir, app) Folder.dynamic_meta_types=tuple(meta_types) Globals.default__class_init__(Folder)
3,450
def manage_addFile(self,id,file,title='',precondition='',REQUEST=None): """Add a new File object. Creates a new file object 'id' with the contents of 'file'""" self._setObject(id, File(id,title,file,precondition)) if REQUEST is not None: return self.manage_main(self,REQUEST)
def manage_addFile(self,id,file,title='',precondition='',REQUEST=None): """Add a new File object. Creates a new file object 'id' with the contents of 'file'""" self._setObject(id, File(id,title,file,precondition)) if REQUEST is not None: return self.manage_main(self,REQUEST)
3,451
def __init__(self, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, environ=os.environ): self.environ=environ fp=None try: if environ['REQUEST_METHOD'] != 'GET': fp=stdin except: pass
def __init__(self, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, environ=os.environ): self.environ=environ fp=None try: if environ['REQUEST_METHOD'] != 'GET': fp=stdin except: pass
3,452
def __init__(self, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, environ=os.environ): self.environ=environ fp=None try: if environ['REQUEST_METHOD'] != 'GET': fp=stdin except: pass
def __init__(self, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, environ=os.environ): self.environ=environ fp=None try: if environ['REQUEST_METHOD'] != 'GET': fp=stdin except: pass
3,453
def parse_cookie(text, result=None, parmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)=\([^\0- =\"]+\)' '\([\0- ]*[;,]\)?[\0- ]*\)' ), qparmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)="\([^"]*\)\"' '\([\0- ]*[;,]\)?[\0- ]*\)' ), ): if result is None: result={} if parmre.match(text) >= 0: name=parmre.group(2) value=parmre.group(3) l=len(parmre.group(1)) elif qparmre.match(text) >= 0: name=qparmre.group(2) value=qparmre.group(3) l=len(qparmre.group(1)) else: if not text or not strip(text): return result raise "InvalidParameter", text result[name]=value return apply(parse_cookie,(text[l:],result))
def parse_cookie(text, result=None, qparmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)="\([^"]*\)\"' '\([\0- ]*[;,]\)?[\0- ]*\)' ), ): if result is None: result={} if parmre.match(text) >= 0: name=parmre.group(2) value=parmre.group(3) l=len(parmre.group(1)) elif qparmre.match(text) >= 0: name=qparmre.group(2) value=qparmre.group(3) l=len(qparmre.group(1)) else: if not text or not strip(text): return result raise "InvalidParameter", text result[name]=value return apply(parse_cookie,(text[l:],result))
3,454
def parse_cookie(text, result=None, parmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)=\([^\0- =\"]+\)' '\([\0- ]*[;,]\)?[\0- ]*\)' ), qparmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)="\([^"]*\)\"' '\([\0- ]*[;,]\)?[\0- ]*\)' ), ): if result is None: result={} if parmre.match(text) >= 0: name=parmre.group(2) value=parmre.group(3) l=len(parmre.group(1)) elif qparmre.match(text) >= 0: name=qparmre.group(2) value=qparmre.group(3) l=len(qparmre.group(1)) else: if not text or not strip(text): return result raise "InvalidParameter", text result[name]=value return apply(parse_cookie,(text[l:],result))
def parse_cookie(text, result=None, parmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)=\([^\0- =\"]+\)' '\([\0- ]*[;,]\)?[\0- ]*\)' ), qparmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)="\([^"]*\)\"' '\([\0- ]*[;,]\)?[\0- ]*\)' ), ): if result is None: result={} if qparmre.match(text) >= 0: name=qparmre.group(2) value=qparmre.group(3) l=len(qparmre.group(1)) elif parmre.match(text) >= 0: name=parmre.group(2) value=parmre.group(3) l=len(parmre.group(1)) elif qparmre.match(text) >= 0: name=qparmre.group(2) value=qparmre.group(3) l=len(qparmre.group(1)) else: if not text or not strip(text): return result raise "InvalidParameter", text result[name]=value return apply(parse_cookie,(text[l:],result))
3,455
def parse_cookie(text, result=None, parmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)=\([^\0- =\"]+\)' '\([\0- ]*[;,]\)?[\0- ]*\)' ), qparmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)="\([^"]*\)\"' '\([\0- ]*[;,]\)?[\0- ]*\)' ), ): if result is None: result={} if parmre.match(text) >= 0: name=parmre.group(2) value=parmre.group(3) l=len(parmre.group(1)) elif qparmre.match(text) >= 0: name=qparmre.group(2) value=qparmre.group(3) l=len(qparmre.group(1)) else: if not text or not strip(text): return result raise "InvalidParameter", text result[name]=value return apply(parse_cookie,(text[l:],result))
def parse_cookie(text, result=None, parmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)=\([^\0- =\"]+\)' '\([\0- ]*[;,]\)?[\0- ]*\)' ), qparmre=regex.compile( '\([\0- ]*' '\([^\0- ;,=\"]+\)="\([^"]*\)\"' '\([\0- ]*[;,]\)?[\0- ]*\)' ), ): if result is None: result={} if parmre.match(text) >= 0: name=parmre.group(2) value=parmre.group(3) l=len(parmre.group(1)) else: if not text or not strip(text): return result raise "InvalidParameter", text result[name]=value return apply(parse_cookie,(text[l:],result))
3,456
def convertSet(s, IITreeSet=IITreeSet): if len(s) == 1: try: return s[0] # convert to int except: pass # This is just an optimization. return IITreeSet(s)
def convertSet(s, IITreeSet=IITreeSet, IntType=type(0), type=type, len=len, doneTypes = (IntType, IITreeSet)): if type(s) in doneTypes: return s if len(s) == 1: try: return s[0] # convert to int except: pass # This is just an optimization. return IITreeSet(s)
3,457
def convertSet(s, IITreeSet=IITreeSet): if len(s) == 1: try: return s[0] # convert to int except: pass # This is just an optimization. return IITreeSet(s)
def convertSet(s, IITreeSet=IITreeSet): if len(s) == 1: try: return s[0] # convert to int except: pass # This is just an optimization. return IITreeSet(s)
3,458
def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw): """Render the document given a client object, REQUEST mapping, Response, and key word arguments.""" kw['document_id'] =self.id kw['document_title']=self.title
def __call__(self, client=None, REQUEST={}, RESPONSE=None, **kw): """Render the document given a client object, REQUEST mapping, Response, and key word arguments.""" kw['document_id'] =self.id kw['document_title']=self.title
3,459
def _cached_result(self, DB__, query): pure_query = query # we need to munge the incoming query key in the cache # so that the same request to a different db is returned query += '\nDBConnId: %s' % self.connection_hook # Try to fetch from cache if hasattr(self,'_v_cache'): cache=self._v_cache else: cache=self._v_cache={}, Bucket() cache, tcache = cache max_cache=self.max_cache_ now=time() t=now-self.cache_time_ if len(cache) > max_cache / 2: keys=tcache.keys() keys.reverse() while keys and (len(keys) > max_cache or keys[-1] < t): key=keys[-1] q=tcache[key] del tcache[key] if int(cache[q][0]) == key: del cache[q] del keys[-1]
def _cached_result(self, DB__, query): pure_query = query # we need to munge the incoming query key in the cache # so that the same request to a different db is returned query = query + ('\nDBConnId: %s' % self.connection_hook, ) # Try to fetch from cache if hasattr(self,'_v_cache'): cache=self._v_cache else: cache=self._v_cache={}, Bucket() cache, tcache = cache max_cache=self.max_cache_ now=time() t=now-self.cache_time_ if len(cache) > max_cache / 2: keys=tcache.keys() keys.reverse() while keys and (len(keys) > max_cache or keys[-1] < t): key=keys[-1] q=tcache[key] del tcache[key] if int(cache[q][0]) == key: del cache[q] del keys[-1]
3,460
def manage_FTPget(self): """Return body for ftp.""" if self.ZCacheable_isCachingEnabled(): result = self.ZCacheable_get(default=None) if result is not None: # We will always get None from RAMCacheManager but we will get # something implementing the IStreamIterator interface # from FileCacheManager. # the content-length is required here by HTTPResponse, even # though FTP doesn't use it. self.REQUEST.RESPONSE.setHeader('Content-Length', self.size) return result return str(self.data)
def manage_FTPget(self): """Return body for ftp.""" if self.ZCacheable_isCachingEnabled(): result = self.ZCacheable_get(default=None) if result is not None: # We will always get None from RAMCacheManager but we will get # something implementing the IStreamIterator interface # from FileCacheManager. # the content-length is required here by HTTPResponse, even # though FTP doesn't use it. RESPONSE.setHeader('Content-Length', self.size) return result return str(self.data)
3,461
def manage_FTPget(self): """Return body for ftp.""" if self.ZCacheable_isCachingEnabled(): result = self.ZCacheable_get(default=None) if result is not None: # We will always get None from RAMCacheManager but we will get # something implementing the IStreamIterator interface # from FileCacheManager. # the content-length is required here by HTTPResponse, even # though FTP doesn't use it. self.REQUEST.RESPONSE.setHeader('Content-Length', self.size) return result return str(self.data)
def manage_FTPget(self): """Return body for ftp.""" if self.ZCacheable_isCachingEnabled(): result = self.ZCacheable_get(default=None) if result is not None: # We will always get None from RAMCacheManager but we will get # something implementing the IStreamIterator interface # from FileCacheManager. # the content-length is required here by HTTPResponse, even # though FTP doesn't use it. self.REQUEST.RESPONSE.setHeader('Content-Length', self.size) return result return str(self.data)
3,462
def _docommit(self, txn, tid): self._pending.put(self._serial, COMMIT, txn) deltas = {} co = cs = None try: co = self._oids.cursor(txn=txn) cs = self._serials.cursor(txn=txn) rec = co.first() while rec: oid = rec[0] rec = co.next() # Remove from the serials table all entries with key oid where # the serial is not tid. These are the old revisions of the # object. At the same time, we want to collect the oids of # the objects referred to by this revision's pickle, so that # later we can decref those reference counts. srec = cs.set(oid) while srec: soid, stid = srec if soid <> oid: break if stid <> tid: cs.delete() data = self._pickles.get(oid+stid, txn=txn) assert data is not None self._update(deltas, data, -1) self._pickles.delete(oid+stid, txn=txn) srec = cs.next_dup() # Now add incref deltas for all objects referenced by the new # revision of this object. data = self._pickles.get(oid+tid, txn=txn) assert data is not None self._update(deltas, data, 1) finally: # There's a small window of opportunity for leaking a cursor here, # if co.close() were to fail. In practice this shouldn't happen. if co: co.close() if cs: cs.close() # We're done with this table self._oids.truncate(txn) self._pending.truncate(txn) # Now, to finish up, we need apply the refcount deltas to the # refcounts table, and do recursive collection of all refcount == 0 # objects. while deltas: deltas = self._update_refcounts(deltas, txn)
def _docommit(self, txn, tid): self._pending.put(self._serial, COMMIT, txn) deltas = {} co = cs = None try: co = self._oids.cursor(txn=txn) cs = self._serials.cursor(txn=txn) rec = co.first() while rec: oid = rec[0] rec = co.next() # Remove from the serials table all entries with key oid where # the serial is not tid. These are the old revisions of the # object. At the same time, we want to collect the oids of # the objects referred to by this revision's pickle, so that # later we can decref those reference counts. srec = cs.set(oid) while srec: soid, stid = srec if soid <> oid: break if stid == tid: data = self._pickles.get(oid+stid, txn=txn) assert data is not None self._update(deltas, data, 1) else: cs.delete() data = self._pickles.get(oid+stid, txn=txn) assert data is not None self._update(deltas, data, -1) self._pickles.delete(oid+stid, txn=txn) srec = cs.next_dup() # Now add incref deltas for all objects referenced by the new # revision of this object. data = self._pickles.get(oid+tid, txn=txn) assert data is not None self._update(deltas, data, 1) finally: # There's a small window of opportunity for leaking a cursor here, # if co.close() were to fail. In practice this shouldn't happen. if co: co.close() if cs: cs.close() # We're done with this table self._oids.truncate(txn) self._pending.truncate(txn) # Now, to finish up, we need apply the refcount deltas to the # refcounts table, and do recursive collection of all refcount == 0 # objects. while deltas: deltas = self._update_refcounts(deltas, txn)
3,463
def _docommit(self, txn, tid): self._pending.put(self._serial, COMMIT, txn) deltas = {} co = cs = None try: co = self._oids.cursor(txn=txn) cs = self._serials.cursor(txn=txn) rec = co.first() while rec: oid = rec[0] rec = co.next() # Remove from the serials table all entries with key oid where # the serial is not tid. These are the old revisions of the # object. At the same time, we want to collect the oids of # the objects referred to by this revision's pickle, so that # later we can decref those reference counts. srec = cs.set(oid) while srec: soid, stid = srec if soid <> oid: break if stid <> tid: cs.delete() data = self._pickles.get(oid+stid, txn=txn) assert data is not None self._update(deltas, data, -1) self._pickles.delete(oid+stid, txn=txn) srec = cs.next_dup() # Now add incref deltas for all objects referenced by the new # revision of this object. data = self._pickles.get(oid+tid, txn=txn) assert data is not None self._update(deltas, data, 1) finally: # There's a small window of opportunity for leaking a cursor here, # if co.close() were to fail. In practice this shouldn't happen. if co: co.close() if cs: cs.close() # We're done with this table self._oids.truncate(txn) self._pending.truncate(txn) # Now, to finish up, we need apply the refcount deltas to the # refcounts table, and do recursive collection of all refcount == 0 # objects. while deltas: deltas = self._update_refcounts(deltas, txn)
def _docommit(self, txn, tid): self._pending.put(self._serial, COMMIT, txn) deltas = {} co = cs = None try: co = self._oids.cursor(txn=txn) cs = self._serials.cursor(txn=txn) rec = co.first() while rec: oid = rec[0] rec = co.next() # Remove from the serials table all entries with key oid where # the serial is not tid. These are the old revisions of the # object. At the same time, we want to collect the oids of # the objects referred to by this revision's pickle, so that # later we can decref those reference counts. srec = cs.set(oid) while srec: soid, stid = srec if soid <> oid: break if stid <> tid: cs.delete() data = self._pickles.get(oid+stid, txn=txn) assert data is not None self._update(deltas, data, -1) self._pickles.delete(oid+stid, txn=txn) srec = cs.next_dup() # Now add incref deltas for all objects referenced by the new # revision of this object. data = self._pickles.get(oid+tid, txn=txn) assert data is not None self._update(deltas, data, 1) finally: # There's a small window of opportunity for leaking a cursor here, # if co.close() were to fail. In practice this shouldn't happen. if co: co.close() if cs: cs.close() # We're done with this table self._oids.truncate(txn) # Now, to finish up, we need apply the refcount deltas to the # refcounts table, and do recursive collection of all refcount == 0 # objects. while deltas: deltas = self._update_refcounts(deltas, txn)
3,464
def setBase(self,base):
def setBase(self,base):
3,465
def insertBase(self):
def insertBase(self):
3,466
def insertBase(self):
def insertBase(self):
3,467
def quoteHTML(self,text,
def quoteHTML(self,text,
3,468
def quoteHTML(self,text,
def def format_exception(self,etype,value,tb,limit=None): import traceback result=['Traceback (innermost last):'] if limit is None: if hasattr(sys, 'tracebacklimit'): limit = sys.tracebacklimit n = 0 while tb is not None and (limit is None or n < limit): f = tb.tb_frame lineno = tb.tb_lineno co = f.f_code filename = co.co_filename name = co.co_name locals=f.f_locals result.append(' File %s, line %d, in %s' % (filename,lineno,name)) try: result.append(' (Object: %s)' % locals[co.co_varnames[0]].__name__) except: pass try: result.append(' (Info: %s)' % str(locals['__traceback_info__'])) except: pass tb = tb.tb_next n = n+1 result.append(string.joinfields( traceback.format_exception_only(etype, value), ' ')) return result quoteHTML(self,text,
3,469
def _traceback(self,t,v,tb):
def _traceback(self,t,v,tb):
3,470
def exception(self):
def exception(self):
3,471
def default_input_form(id,arguments,action='query', tabs=''): if arguments: items=arguments.items() return ( "%s\n%s%s" % ( '<html><head><title>%s Input Data</title></head><body>\n%s\n' '<form action="<!--#var URL2-->/<!--#var id-->/%s" ' 'method="get">\n' '<h2>%s Input Data</h2>\n' 'Enter query parameters:<br>' '<table>\n' % (id,tabs,action,id), string.joinfields( map( lambda a: ('<tr><th>%s</th>\n' ' <td><input name="%s"\n' ' width=30 value="%s">' '</td></tr>' % (nicify(a[0]), ( a[1].has_key('type') and ("%s:%s" % (a[0],a[1]['type'])) or a[0] ), a[1].has_key('default') and a[1]['default'] or '' )) , items ), '\n'), '\n<tr><td colspan=2 align=center>\n' '<input type="SUBMIT" name="SUBMIT" value="Submit Query">\n' '<!--#if HTTP_REFERER-->\n' ' <input type="SUBMIT" name="SUBMIT" value="Cancel">\n' ' <INPUT NAME="CANCEL_ACTION" TYPE="HIDDEN"\n' ' VALUE="<!--#var HTTP_REFERER-->">\n' '<!--#/if HTTP_REFERER-->\n' '</td></tr>\n</table>\n</form>\n</body>\n</html>\n' ) ) else: return ( '<html><head><title>%s Input Data</title></head><body>\n%s\n' '<form action="<!--#var URL2-->/<!--#var id-->/%s" ' 'method="get">\n' '<h2>%s Input Data</h2>\n' 'This query requires no input.<p>\n' '<input type="SUBMIT" name="SUBMIT" value="Submit Query">\n' '<!--#if HTTP_REFERER-->\n' ' <input type="SUBMIT" name="SUBMIT" value="Cancel">\n' ' <INPUT NAME="CANCEL_ACTION" TYPE="HIDDEN"\n' ' VALUE="<!--#var HTTP_REFERER-->">\n' '<!--#/if HTTP_REFERER-->\n' '</td></tr>\n</table>\n</form>\n</body>\n</html>\n' % (id, tabs, action, id) )
def default_input_form(id,arguments,action='query', tabs=''): if arguments: items=arguments.items() return ( "%s\n%s%s" % ( '<html><head><title>%s Input Data</title></head><body>\n%s\n' '<form action="<!--#var URL2-->/<!--#var id-->/%s" ' 'method="get">\n' '<h2>%s Input Data</h2>\n' 'Enter query parameters:<br>' '<table>\n' % (id,tabs,action,id), string.joinfields( map( lambda a: ('<tr> <th>%s</th>\n' ' <td><input name="%s"\n' ' width=30 value="%s">' ' </td></tr>' % (nicify(a[0]), ( a[1].has_key('type') and ("%s:%s" % (a[0],a[1]['type'])) or a[0] ), a[1].has_key('default') and a[1]['default'] or '' )) , items ), '\n'), '\n<tr><td colspan=2 align=center>\n' '<input type="SUBMIT" name="SUBMIT" value="Submit Query">\n' '<!--#if HTTP_REFERER-->\n' ' <input type="SUBMIT" name="SUBMIT" value="Cancel">\n' ' <INPUT NAME="CANCEL_ACTION" TYPE="HIDDEN"\n' ' VALUE="<!--#var HTTP_REFERER-->">\n' '<!--#/if HTTP_REFERER-->\n' '</td></tr>\n</table>\n</form>\n</body>\n</html>\n' ) ) else: return ( '<html><head><title>%s Input Data</title></head><body>\n%s\n' '<form action="<!--#var URL2-->/<!--#var id-->/%s" ' 'method="get">\n' '<h2>%s Input Data</h2>\n' 'This query requires no input.<p>\n' '<input type="SUBMIT" name="SUBMIT" value="Submit Query">\n' '<!--#if HTTP_REFERER-->\n' ' <input type="SUBMIT" name="SUBMIT" value="Cancel">\n' ' <INPUT NAME="CANCEL_ACTION" TYPE="HIDDEN"\n' ' VALUE="<!--#var HTTP_REFERER-->">\n' '<!--#/if HTTP_REFERER-->\n' '</td></tr>\n</table>\n</form>\n</body>\n</html>\n' % (id, tabs, action, id) )
3,472
def custom_default_report(id, result, action='', no_table=0, goofy=regex.compile('[^a-zA-Z0-9_]').search ): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s\n</tr>' % string.joinfields( map(lambda c: ' <th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>', '</p>' else: tr, _tr = '<tr>', '</tr>' row=[] for c in columns: n=c['name'] if goofy(n) >= 0: n='expr="_vars[\'%s]"' % (`'"'+n`[2:]) row.append(' %s<!--#var %s%s-->%s\n' % (td,n,c['type']!='s' and ' null=""' or '',_td)) row=('%s\n%s\n%s' % (tr,string.joinfields(row,delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table)
def custom_default_report(id, result, action='', no_table=0, goofy=regex.compile('[^a-zA-Z0-9_]').search ): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s </tr>' % string.joinfields( map(lambda c: ' <th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>', '</p>' else: tr, _tr = '<tr>', '</tr>' row=[] for c in columns: n=c['name'] if goofy(n) >= 0: n='expr="_vars[\'%s]"' % (`'"'+n`[2:]) row.append(' %s<!--#var %s%s-->%s\n' % (td,n,c['type']!='s' and ' null=""' or '',_td)) row=('%s\n%s\n%s' % (tr,string.joinfields(row,delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table)
3,473
def custom_default_report(id, result, action='', no_table=0, goofy=regex.compile('[^a-zA-Z0-9_]').search ): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s\n</tr>' % string.joinfields( map(lambda c: ' <th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>', '</p>' else: tr, _tr = '<tr>', '</tr>' row=[] for c in columns: n=c['name'] if goofy(n) >= 0: n='expr="_vars[\'%s]"' % (`'"'+n`[2:]) row.append(' %s<!--#var %s%s-->%s\n' % (td,n,c['type']!='s' and ' null=""' or '',_td)) row=('%s\n%s\n%s' % (tr,string.joinfields(row,delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table)
def custom_default_report(id, result, action='', no_table=0, goofy=regex.compile('[^a-zA-Z0-9_]').search ): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s\n</tr>' % string.joinfields( map(lambda c: ' <th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>', '</p>' else: tr, _tr = '<tr>', '</tr>' row=[] for c in columns: n=c['name'] if goofy(n) >= 0: n='expr="_vars[\'%s]"' % (`'"'+n`[2:]) row.append(' %s<!--#var %s%s-->%s\n' % (td,n,c['type']!='s' and ' null=""' or '',_td)) row=('%s\n%s\n%s' % (tr,string.joinfields(row,delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table)
3,474
def custom_default_report(id, result, action='', no_table=0, goofy=regex.compile('[^a-zA-Z0-9_]').search ): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s\n</tr>' % string.joinfields( map(lambda c: ' <th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>', '</p>' else: tr, _tr = '<tr>', '</tr>' row=[] for c in columns: n=c['name'] if goofy(n) >= 0: n='expr="_vars[\'%s]"' % (`'"'+n`[2:]) row.append(' %s<!--#var %s%s-->%s\n' % (td,n,c['type']!='s' and ' null=""' or '',_td)) row=('%s\n%s\n%s' % (tr,string.joinfields(row,delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table)
def custom_default_report(id, result, action='', no_table=0, goofy=regex.compile('[^a-zA-Z0-9_]').search ): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s\n</tr>' % string.joinfields( map(lambda c: ' <th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ',\n' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '\n' row=[] for c in columns: n=c['name'] if goofy(n) >= 0: n='expr="_vars[\'%s]"' % (`'"'+n`[2:]) row.append(' %s<!--#var %s%s-->%s\n' % (td,n,c['type']!='s' and ' null=""' or '',_td)) row=('%s\n%s\n%s' % (tr,string.joinfields(row,delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table)
3,475
def custom_default_report(id, result, action='', no_table=0, goofy=regex.compile('[^a-zA-Z0-9_]').search ): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s\n</tr>' % string.joinfields( map(lambda c: ' <th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>', '</p>' else: tr, _tr = '<tr>', '</tr>' row=[] for c in columns: n=c['name'] if goofy(n) >= 0: n='expr="_vars[\'%s]"' % (`'"'+n`[2:]) row.append(' %s<!--#var %s%s-->%s\n' % (td,n,c['type']!='s' and ' null=""' or '',_td)) row=('%s\n%s\n%s' % (tr,string.joinfields(row,delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table)
def custom_default_report(id, result, action='', no_table=0, goofy=regex.compile('[^a-zA-Z0-9_]').search ): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s\n</tr>' % string.joinfields( map(lambda c: ' <th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>', '</p>' else: tr, _tr = '<tr>', '</tr>' row=[] for c in columns: n=c['name'] if goofy(n) >= 0: n='expr="_vars[\'%s]"' % (`'"'+n`[2:]) row.append(' %s<!--#var %s%s-->%s\n' % (td,n,c['type']!='s' and ' null=""' or '',_td)) row=('%s\n%s\n%s' % (tr,string.joinfields(row,delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table)
3,476
def custom_default_report(id, result, action='', no_table=0, goofy=regex.compile('[^a-zA-Z0-9_]').search ): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s\n</tr>' % string.joinfields( map(lambda c: ' <th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>', '</p>' else: tr, _tr = '<tr>', '</tr>' row=[] for c in columns: n=c['name'] if goofy(n) >= 0: n='expr="_vars[\'%s]"' % (`'"'+n`[2:]) row.append(' %s<!--#var %s%s-->%s\n' % (td,n,c['type']!='s' and ' null=""' or '',_td)) row=('%s\n%s\n%s' % (tr,string.joinfields(row,delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table)
def custom_default_report(id, result, action='', no_table=0, goofy=regex.compile('[^a-zA-Z0-9_]').search ): columns=result._searchable_result_columns() __traceback_info__=columns heading=('<tr>\n%s\n</tr>' % string.joinfields( map(lambda c: ' <th>%s</th>\n' % nicify(c['name']), columns), '' ) ) if no_table: tr, _tr, td, _td, delim = '<p>', '</p>', '', '', ', ' else: tr, _tr, td, _td, delim = '<tr>', '</tr>', '<td>', '</td>', '' if no_table: tr='<p>', '</p>' else: tr, _tr = '<tr>', '</tr>' row=[] for c in columns: n=c['name'] if goofy(n) >= 0: n='expr="_vars[\'%s]"' % (`'"'+n`[2:]) row.append(' %s<!--#var %s%s-->%s\n' % (td,n,c['type']!='s' and ' null=""' or '',_td)) row=(' %s\n%s\n %s' % (tr,string.joinfields(row,delim), _tr)) return custom_default_report_src( id=id,heading=heading,row=row,action=action,no_table=no_table)
3,477
def decapitate(html, RESPONSE=None, header_re=regex.compile( '\(\(' '[^\0- <>:]+:[^\n]*\n' '\|' '[ \t]+[^\0- ][^\n]*\n' '\)+\)[ \t]*\n\([\0-\377]+\)' ), space_re=regex.compile('\([ \t]+\)'), name_re=regex.compile('\([^\0- <>:]+\):\([^\n]*\)'), ): if header_re.match(html) < 0: return html headers, html = header_re.group(1,3) headers=string.split(headers,'\n') i=1 while i < len(headers): if not headers[i]: del headers[i] elif space_re.match(headers[i]) >= 0: headers[i-1]="%s %s" % (headers[i-1], headers[i][len(space_re.group(1)):]) del headers[i] else: i=i+1 for i in range(len(headers)): if name_re.match(headers[i]) >= 0: k, v = name_re.group(1,2) v=string.strip(v) else: raise ValueError, 'Invalid Header (%d): %s ' % (i,headers[i]) RESPONSE.setHeader(k,v) return html
defdecapitate(html,RESPONSE=None,header_re=regex.compile('\(\(''[^\0-<>:]+:[^\n]*\n''\|''[\t]+[^\0-][^\n]*\n''\)+\)[\t]*\n\([\0-\377]+\)'),space_re=regex.compile('\([\t]+\)'),name_re=regex.compile('\([^\0-<>:]+\):\([^\n]*\)'),):ifheader_re.match(html)<0:returnhtmlheaders,html=header_re.group(1,3)headers=string.split(headers,'\n')i=1whilei<len(headers):ifnotheaders[i]:delheaders[i]elifspace_re.match(headers[i])>=0:headers[i-1]="%s%s"%(headers[i-1],headers[i][len(space_re.group(1)):])delheaders[i]else:i=i+1foriinrange(len(headers)):ifname_re.match(headers[i])>=0:k,v=name_re.group(1,2)v=string.strip(v)else:raiseValueError,'InvalidHeader(%d):%s'%(i,headers[i])RESPONSE.setHeader(k,v)returnhtml
3,478
def raise_standardErrorMessage( self, client=None, REQUEST={}, error_type=None, error_value=None, tb=None, error_tb=None, error_message='', tagSearch=re.compile(r'[a-zA-Z]>').search):
def raise_standardErrorMessage( self, client=None, REQUEST={}, error_type=None, error_value=None, tb=None, error_tb=None, error_message='', tagSearch=re.compile(r'[a-zA-Z]>').search):
3,479
def tag(self, height=None, width=None, alt=None, scale=0, xscale=0, yscale=0, **args): """ Generate an HTML IMG tag for this image, with customization. Arguments to self.tag() can be any valid attributes of an IMG tag. 'src' will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for 'height', 'width', and 'alt'. If specified, the 'scale', 'xscale', and 'yscale' keyword arguments will be used to automatically adjust the output height and width values of the image tag. """ if height is None: height=self.height if width is None: width=self.width
def tag(self, height=None, width=None, alt=None, scale=0, xscale=0, yscale=0, **args): """ Generate an HTML IMG tag for this image, with customization. Arguments to self.tag() can be any valid attributes of an IMG tag. 'src' will always be an absolute pathname, to prevent redundant downloading of images. Defaults are applied intelligently for 'height', 'width', and 'alt'. If specified, the 'scale', 'xscale', and 'yscale' keyword arguments will be used to automatically adjust the output height and width values of the image tag. """ if height is None: height=self.height if width is None: width=self.width
3,480
def __init__(self, value=0): t = type(value) if not isinstance(t, StringType): if not isinstance(t, TupleType): if value == 0: value = time.time() value = time.localtime(value) value = time.strftime("%Y%m%dT%H:%M:%S", value) self.value = value
def __init__(self, value=0): if not isinstance(value, StringType): if not isinstance(value, TupleType): if value == 0: value = time.time() value = time.localtime(value) value = time.strftime("%Y%m%dT%H:%M:%S", value) self.value = value
3,481
def do_startTag(self, name, attrList, end=">"): if not attrList: s = "<%s%s" % (name, end) self.do_rawtextOffset(s, len(s)) return _len = len self._stream_write("<" + name) self.col = self.col + _len(name) + 1 align = self.col + 1 + _len(name) if align >= self.wrap/2: align = 4 # Avoid a narrow column far to the right for item in attrList: if _len(item) == 2: name, value = item else: ok, name, value = self.attrAction(item) if not ok: continue if value is None: s = name else: s = "%s=%s" % (name, quote(value)) if (self.wrap and self.col >= align and self.col + 1 + _len(s) > self.wrap): self._stream_write("\n" + " "*align) self.col = self.col + align else: s = " " + s self._stream_write(s) if "\n" in s: self.col = _len(s) - (rfind(s, "\n") + 1) else: self.col = self.col + _len(s) self._stream_write(end) self.col = self.col + _len(end)
def do_startTag(self, name, attrList, end=">"): if not attrList: s = "<%s%s" % (name, end) self.do_rawtextOffset(s, len(s)) return _len = len self._stream_write("<" + name) self.col = self.col + _len(name) + 1 align = self.col + 1 + _len(name) if align >= self.wrap/2: align = 4 # Avoid a narrow column far to the right for item in attrList: if _len(item) == 2: name, value = item else: ok, name, value = self.attrAction(item) if not ok: continue if value is None: s = name else: s = "%s=%s" % (name, quote(value)) if (self.wrap and self.col >= align and self.col + 1 + _len(s) > self.wrap): self._stream_write("\n" + " "*align) self.col = align else: s = " " + s self._stream_write(s) if "\n" in s: self.col = _len(s) - (rfind(s, "\n") + 1) else: self.col = self.col + _len(s) self._stream_write(end) self.col = self.col + _len(end)
3,482
def __call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw): """Call the database method
def __call__(self, REQUEST=None, __ick__=None, src__=0, test__=0, **kw): """Call the database method
3,483
def creator(self): """Return a sequence of user names who have the local Owner role on an object. The name creator is used for this method to conform to Dublin Core.""" users=[] for user, roles in self.get_local_roles(): if 'Owner' in roles: users.append(user) return ', '.join(users, ', ')
def creator(self): """Return a sequence of user names who have the local Owner role on an object. The name creator is used for this method to conform to Dublin Core.""" users=[] for user, roles in self.get_local_roles(): if 'Owner' in roles: users.append(user) return ', '.join(users, ', ')
3,484
def main(): # below assumes this script is in the BASE_DIR/inst directory global PREFIX BASE_DIR=os.path.abspath(os.path.dirname(os.path.dirname(sys.argv[0]))) BUILD_BASE=os.path.join(os.getcwd(), 'build-base') PYTHON=sys.executable MAKEFILE=open(os.path.join(BASE_DIR, 'inst', IN_MAKEFILE)).read() REQUIRE_LF_ENABLED = 1 REQUIRE_ZLIB = 1 REQURE_PYEXPAT = 1 INSTALL_FLAGS = '' DISTUTILS_OPTS = '' try: longopts = ['help', 'ignore-largefile', 'ignore-zlib', 'ignore-pyexpat', 'prefix=', 'build-base=', 'optimize', 'no-compile', 'quiet'] opts, args = getopt.getopt(sys.argv[1:], 'h', longopts) except getopt.GetoptError, v: print v usage() sys.exit(1) for o, a in opts: if o in ('-h', '--help'): usage() sys.exit() if o == '--prefix': PREFIX=os.path.abspath(os.path.expanduser(a)) if o == '--ignore-largefile': REQUIRE_LF_ENABLED=0 if o == '--ignore-zlib': REQUIRE_ZLIB=0 if o == '--ignore-pyexpat': REQUIRE_PYEXPAT=0 if o == '--optimize': INSTALL_FLAGS = '--optimize=1 --no-compile' if o == '--no-compile': INSTALL_FLAGS = '--no-compile' if o == '--build-base': BUILD_BASE = a if o == '--quiet': DISTUTILS_OPTS = '-q' global QUIET QUIET = 1 if REQUIRE_LF_ENABLED: test_largefile() if REQUIRE_ZLIB: test_zlib() if REQUIRE_PYEXPAT: test_pyexpat() out(' - Zope top-level binary directory will be %s.' % PREFIX) if INSTALL_FLAGS: out(' - Distutils install flags will be "%s"' % INSTALL_FLAGS) idata = { '<<PYTHON>>':PYTHON, '<<PREFIX>>':PREFIX, '<<BASE_DIR>>':BASE_DIR, '<<BUILD_BASE>>':BUILD_BASE, '<<INSTALL_FLAGS>>':INSTALL_FLAGS, '<<ZOPE_MAJOR_VERSION>>':versions.ZOPE_MAJOR_VERSION, '<<ZOPE_MINOR_VERSION>>':versions.ZOPE_MINOR_VERSION, '<<VERSION_RELEASE_TAG>>':versions.VERSION_RELEASE_TAG, '<<DISTUTILS_OPTS>>':DISTUTILS_OPTS, } for k,v in idata.items(): MAKEFILE = MAKEFILE.replace(k, v) f = open(os.path.join(os.getcwd(), 'makefile'), 'w') f.write(MAKEFILE) out(' - Makefile written.') out('') out(' Next, run %s.' % MAKE_COMMAND) out('')
def main(): # below assumes this script is in the BASE_DIR/inst directory global PREFIX BASE_DIR=os.path.abspath(os.path.dirname(os.path.dirname(sys.argv[0]))) BUILD_BASE=os.path.join(os.getcwd(), 'build-base') PYTHON=sys.executable MAKEFILE=open(os.path.join(BASE_DIR, 'inst', IN_MAKEFILE)).read() REQUIRE_LF_ENABLED = 1 REQUIRE_ZLIB = 1 REQUIRE_PYEXPAT = 1 INSTALL_FLAGS = '' DISTUTILS_OPTS = '' try: longopts = ['help', 'ignore-largefile', 'ignore-zlib', 'ignore-pyexpat', 'prefix=', 'build-base=', 'optimize', 'no-compile', 'quiet'] opts, args = getopt.getopt(sys.argv[1:], 'h', longopts) except getopt.GetoptError, v: print v usage() sys.exit(1) for o, a in opts: if o in ('-h', '--help'): usage() sys.exit() if o == '--prefix': PREFIX=os.path.abspath(os.path.expanduser(a)) if o == '--ignore-largefile': REQUIRE_LF_ENABLED=0 if o == '--ignore-zlib': REQUIRE_ZLIB=0 if o == '--ignore-pyexpat': REQUIRE_PYEXPAT=0 if o == '--optimize': INSTALL_FLAGS = '--optimize=1 --no-compile' if o == '--no-compile': INSTALL_FLAGS = '--no-compile' if o == '--build-base': BUILD_BASE = a if o == '--quiet': DISTUTILS_OPTS = '-q' global QUIET QUIET = 1 if REQUIRE_LF_ENABLED: test_largefile() if REQUIRE_ZLIB: test_zlib() if REQUIRE_PYEXPAT: test_pyexpat() out(' - Zope top-level binary directory will be %s.' % PREFIX) if INSTALL_FLAGS: out(' - Distutils install flags will be "%s"' % INSTALL_FLAGS) idata = { '<<PYTHON>>':PYTHON, '<<PREFIX>>':PREFIX, '<<BASE_DIR>>':BASE_DIR, '<<BUILD_BASE>>':BUILD_BASE, '<<INSTALL_FLAGS>>':INSTALL_FLAGS, '<<ZOPE_MAJOR_VERSION>>':versions.ZOPE_MAJOR_VERSION, '<<ZOPE_MINOR_VERSION>>':versions.ZOPE_MINOR_VERSION, '<<VERSION_RELEASE_TAG>>':versions.VERSION_RELEASE_TAG, '<<DISTUTILS_OPTS>>':DISTUTILS_OPTS, } for k,v in idata.items(): MAKEFILE = MAKEFILE.replace(k, v) f = open(os.path.join(os.getcwd(), 'makefile'), 'w') f.write(MAKEFILE) out(' - Makefile written.') out('') out(' Next, run %s.' % MAKE_COMMAND) out('')
3,485
def test_different_queries_same_second(self): # This tests different queries being fired into the cache # in the same second. # XXX The demonstrates a memory leak in the cache code self._check_cache({},{}) # one self._do_query('query1',1.0) self._check_cache( {('query1',1,'conn_id'): (1.0,'result for query1')}, {1: ('query1',1,'conn_id')} ) # two self._do_query( 'query2',1.1) self._check_cache( {('query1',1,'conn_id'): (1.0,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'),}, {1.0: ('query2',1,'conn_id'),} ) # three self._do_query('query3',1.2) self._check_cache( {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'),}, {1: ('query3',1,'conn_id'),} ) # four - now we drop our first cache entry, this is an off-by-one error self._do_query('query4',1.3) self._check_cache( # XXX - oops, why is query1 here still? {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'), ('query4',1,'conn_id'): (1.3,'result for query4'),}, {1: ('query4',1,'conn_id'),} ) # five - now we drop another cache entry self._do_query('query5',1.4) self._check_cache( # XXX - oops, why are query1 and query2 here still? {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'), ('query4',1,'conn_id'): (1.3,'result for query4'), ('query5',1,'conn_id'): (1.4,'result for query5'),}, {1: ('query5',1,'conn_id'),} )
def test_different_queries_same_second(self): # This tests different queries being fired into the cache # in the same second. # XXX The demonstrates a memory leak in the cache code self._check_cache({},{}) # one self._do_query('query1',1.0) self._check_cache( {('query1',1,'conn_id'): (1.0,'result for query1')}, {1: ('query1',1,'conn_id')} ) # two self._do_query( 'query2',1.1) self._check_cache( {('query1',1,'conn_id'): (1.0,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'),}, {1.0: ('query2',1,'conn_id'),} ) # three self._do_query('query3',1.2) self._check_cache( {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'),}, {1: ('query3',1,'conn_id'),} ) # four - now we drop our first cache entry, this is an off-by-one error self._do_query('query4',1.3) self._check_cache( # XXX - oops, why is query1 here still? {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'), ('query4',1,'conn_id'): (1.3,'result for query4'),}, {1: ('query4',1,'conn_id'),} ) # five - now we drop another cache entry self._do_query('query5',1.4) self._check_cache( # XXX - oops, why are query1 and query2 here still? {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'), ('query4',1,'conn_id'): (1.3,'result for query4'), ('query5',1,'conn_id'): (1.4,'result for query5'),}, {1: ('query5',1,'conn_id'),} )
3,486
def test_different_queries_same_second(self): # This tests different queries being fired into the cache # in the same second. # XXX The demonstrates a memory leak in the cache code self._check_cache({},{}) # one self._do_query('query1',1.0) self._check_cache( {('query1',1,'conn_id'): (1.0,'result for query1')}, {1: ('query1',1,'conn_id')} ) # two self._do_query( 'query2',1.1) self._check_cache( {('query1',1,'conn_id'): (1.0,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'),}, {1.0: ('query2',1,'conn_id'),} ) # three self._do_query('query3',1.2) self._check_cache( {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'),}, {1: ('query3',1,'conn_id'),} ) # four - now we drop our first cache entry, this is an off-by-one error self._do_query('query4',1.3) self._check_cache( # XXX - oops, why is query1 here still? {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'), ('query4',1,'conn_id'): (1.3,'result for query4'),}, {1: ('query4',1,'conn_id'),} ) # five - now we drop another cache entry self._do_query('query5',1.4) self._check_cache( # XXX - oops, why are query1 and query2 here still? {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'), ('query4',1,'conn_id'): (1.3,'result for query4'), ('query5',1,'conn_id'): (1.4,'result for query5'),}, {1: ('query5',1,'conn_id'),} )
def test_different_queries_same_second(self): # This tests different queries being fired into the cache # in the same second. # XXX The demonstrates a memory leak in the cache code self._check_cache({},{}) # one self._do_query('query1',1.0) self._check_cache( {('query1',1,'conn_id'): (1.0,'result for query1')}, {1: ('query1',1,'conn_id')} ) # two self._do_query( 'query2',1.1) self._check_cache( {('query1',1,'conn_id'): (1.0,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'),}, {1.0: ('query2',1,'conn_id'),} ) # three self._do_query('query3',1.2) self._check_cache( {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'),}, {1: ('query3',1,'conn_id'),} ) # four - now we drop our first cache entry, this is an off-by-one error self._do_query('query4',1.3) self._check_cache( # XXX - oops, why is query1 here still? {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'), ('query4',1,'conn_id'): (1.3,'result for query4'),}, {1: ('query4',1,'conn_id'),} ) # five - now we drop another cache entry self._do_query('query5',1.4) self._check_cache( # XXX - oops, why are query1 and query2 here still? {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'), ('query4',1,'conn_id'): (1.3,'result for query4'), ('query5',1,'conn_id'): (1.4,'result for query5'),}, {1: ('query5',1,'conn_id'),} )
3,487
def test_different_queries_same_second(self): # This tests different queries being fired into the cache # in the same second. # XXX The demonstrates a memory leak in the cache code self._check_cache({},{}) # one self._do_query('query1',1.0) self._check_cache( {('query1',1,'conn_id'): (1.0,'result for query1')}, {1: ('query1',1,'conn_id')} ) # two self._do_query( 'query2',1.1) self._check_cache( {('query1',1,'conn_id'): (1.0,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'),}, {1.0: ('query2',1,'conn_id'),} ) # three self._do_query('query3',1.2) self._check_cache( {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'),}, {1: ('query3',1,'conn_id'),} ) # four - now we drop our first cache entry, this is an off-by-one error self._do_query('query4',1.3) self._check_cache( # XXX - oops, why is query1 here still? {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'), ('query4',1,'conn_id'): (1.3,'result for query4'),}, {1: ('query4',1,'conn_id'),} ) # five - now we drop another cache entry self._do_query('query5',1.4) self._check_cache( # XXX - oops, why are query1 and query2 here still? {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'), ('query4',1,'conn_id'): (1.3,'result for query4'), ('query5',1,'conn_id'): (1.4,'result for query5'),}, {1: ('query5',1,'conn_id'),} )
def test_different_queries_same_second(self): # This tests different queries being fired into the cache # in the same second. # XXX The demonstrates a memory leak in the cache code self._check_cache({},{}) # one self._do_query('query1',1.0) self._check_cache( {('query1',1,'conn_id'): (1.0,'result for query1')}, {1: ('query1',1,'conn_id')} ) # two self._do_query( 'query2',1.1) self._check_cache( {('query1',1,'conn_id'): (1.0,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'),}, {1.0: ('query2',1,'conn_id'),} ) # three self._do_query('query3',1.2) self._check_cache( {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'),}, {1: ('query3',1,'conn_id'),} ) # four - now we drop our first cache entry, this is an off-by-one error self._do_query('query4',1.3) self._check_cache( # XXX - oops, why is query1 here still? {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'), ('query4',1,'conn_id'): (1.3,'result for query4'),}, {1: ('query4',1,'conn_id'),} ) # five - now we drop another cache entry self._do_query('query5',1.4) self._check_cache( # XXX - oops, why are query1 and query2 here still? {('query1',1,'conn_id'): (1,'result for query1'), ('query2',1,'conn_id'): (1.1,'result for query2'), ('query3',1,'conn_id'): (1.2,'result for query3'), ('query4',1,'conn_id'): (1.3,'result for query4'), ('query5',1,'conn_id'): (1.4,'result for query5'),}, {1: ('query5',1,'conn_id'),} )
3,488
def setBody(self, body, title='', is_error=0, bogus_str_search=None): if isinstance(body, xmlrpclib.Fault): # Convert Fault object to XML-RPC response. body=xmlrpclib.dumps(body, methodresponse=1) else: if type(body) == InstanceType: # Avoid disclosing private members. Private members are # by convention named with a leading underscore char. orig = body.__dict__ dict = {} for key in orig.keys(): if key[:1] != '_': dict[key] = orig[key] body = dict
def setBody(self, body, title='', is_error=0, bogus_str_search=None): if isinstance(body, xmlrpclib.Fault): # Convert Fault object to XML-RPC response. body=xmlrpclib.dumps(body, methodresponse=1) else: if type(body) == types.InstanceType: # Avoid disclosing private members. Private members are # by convention named with a leading underscore char. orig = body.__dict__ dict = {} for key in orig.keys(): if key[:1] != '_': dict[key] = orig[key] body = dict
3,489
def validate(self,request,auth='',roles=None): parent=request['PARENTS'][0]
def validate(self,request,auth='',roles=None): parent=request['PARENTS'][0]
3,490
def declareObjectProtected(self, permission_name): """Declare the object to be associated with a permission.""" self._setaccess((), permission_name)
def declareObjectProtected(self, permission_name): """Declare the object to be associated with a permission.""" self._setaccess((), permission_name)
3,491
def __init__(self, methodName='runTest'): """Create an instance of the class that will use the named test method when executed. """ try: self.__testMethod = getattr(self,methodName) except AttributeError: raise ValueError,"no such test method: %s" % methodName
def __init__(self, methodName='runTest'): """Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name. """ try: self.__testMethod = getattr(self,methodName) except AttributeError: raise ValueError,"no such test method: %s" % methodName
3,492
def __init__(self, methodName='runTest'): """Create an instance of the class that will use the named test method when executed. """ try: self.__testMethod = getattr(self,methodName) except AttributeError: raise ValueError,"no such test method: %s" % methodName
def __init__(self, methodName='runTest'): """Create an instance of the class that will use the named test method when executed. """ try: self.__testMethod = getattr(self,methodName) except AttributeError: raise ValueError,"no such test method: %s" % methodName
3,493
def __str__(self): return "%s.%s" % (self.__class__, self.__testMethod.__name__)
def __str__(self): return "%s.%s" % (self.__class__, self.__testMethod.__name__)
3,494
def assertRaises(self, excClass, callableObj, *args, **kwargs): """Assert that an exception of class excClass is thrown by callableObj when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. """ try: apply(callableObj, args, kwargs) except excClass: return else: raise AssertionError, (hasattr(excClass,'__name__') and excClass.__name__ or str(excClass))
def assertRaises(self, excClass, callableObj, *args, **kwargs): """Assert that an exception of class excClass is thrown by callableObj when invoked with arguments args and keyword arguments kwargs. If a different type of exception is thrown, it will not be caught, and the test case will be deemed to have suffered an error, exactly as for an unexpected exception. """ try: apply(callableObj, args, kwargs) except excClass: return else: raise AssertionError, (hasattr(excClass,'__name__') and excClass.__name__ or str(excClass))
3,495
def __str__(self): return "<%s tests=%s>" % (self.__class__, self._tests)
def __repr__(self): return "<%s tests=%s>" % (self.__class__, self._tests)
3,496
def __str__(self): return "<%s tests=%s>" % (self.__class__, self._tests)
def __str__(self): return "<%s tests=%s>" % (self.__class__, self._tests)
3,497
def __call__(self, result): for test in self._tests: if result.shouldStop: break test(result) return result
def class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test __call__(self, class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test result): class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test for class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test test class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test in class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test self._tests: class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test if class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test result.shouldStop: class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test break class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test test(result) class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test return class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test result class FunctionTestCase(TestCase): """A test case that wraps a test function. This is useful for slipping pre-existing test functions into the PyUnit framework. Optionally, set-up and tidy-up functions can be supplied. As with TestCase, the tidy-up ('tearDown') function will always be called if the set-up ('setUp') function ran successfully. """ def __init__(self, testFunc, setUp=None, tearDown=None, description=None): TestCase.__init__(self) self.__setUpFunc = setUp self.__tearDownFunc = tearDown self.__testFunc = testFunc self.__description = description def setUp(self): if self.__setUpFunc is not None: self.__setUpFunc() def tearDown(self): if self.__tearDownFunc is not None: self.__tearDownFunc() def runTest(self): self.__testFunc() def id(self): return self.__testFunc.__name__ def __str__(self): return "%s (%s)" % (self.__class__, self.__testFunc.__name__) def __repr__(self): return "<%s testFunc=%s>" % (self.__class__, self.__testFunc) def shortDescription(self): if self.__description is not None: return self.__description doc = self.__testFunc.__doc__ return doc and string.strip(string.split(doc, "\n")[0]) or None def getTestCaseNames(testCaseClass, prefix, sortUsing=cmp): """Extracts all the names of functions in the given test case class and its base classes that start with the given prefix. This is used by makeSuite(). """ testFnNames = filter(lambda n,p=prefix: n[:len(p)] == p, dir(testCaseClass)) for baseclass in testCaseClass.__bases__: testFnNames = testFnNames + \ getTestCaseNames(baseclass, prefix, sortUsing=None) if sortUsing: testFnNames.sort(sortUsing) return testFnNames def makeSuite(testCaseClass, prefix='test', sortUsing=cmp): """Returns a TestSuite instance built from all of the test functions in the given test case class whose names begin with the given prefix. The cases are sorted by their function names using the supplied comparison function, which defaults to 'cmp'. """ cases = map(testCaseClass, getTestCaseNames(testCaseClass, prefix, sortUsing)) return TestSuite(cases) def createTestInstance(name, module=None): """Finds tests by their name, optionally only within the given module. Return the newly-constructed test, ready to run. If the name contains a ':' then the portion of the name after the colon is used to find a specific test case within the test case class named before the colon. Examples: findTest('examples.listtests.suite') -- returns result of calling 'suite' findTest('examples.listtests.ListTestCase:checkAppend') -- returns result of calling ListTestCase('checkAppend') findTest('examples.listtests.ListTestCase:check-') -- returns result of calling makeSuite(ListTestCase, prefix="check") """ spec = string.split(name, ':') if len(spec) > 2: raise ValueError, "illegal test name: %s" % name if len(spec) == 1: testName = spec[0] caseName = None else: testName, caseName = spec parts = string.split(testName, '.') if module is None: if len(parts) < 2: raise ValueError, "incomplete test name: %s" % name constructor = __import__(string.join(parts[:-1],'.')) parts = parts[1:] else: constructor = module for part in parts: constructor = getattr(constructor, part) if not callable(constructor): raise ValueError, "%s is not a callable object" % constructor if caseName: if caseName[-1] == '-': prefix = caseName[:-1] if not prefix: raise ValueError, "prefix too short: %s" % name test = makeSuite(constructor, prefix=prefix) else: test = constructor(caseName) else: test = constructor() if not hasattr(test,"countTestCases"): raise TypeError, \ "object %s found with spec %s is not a test" % (test, name) return test
3,498
def writeln(self, *args): if args: apply(self.write, args) self.write(os.linesep)
def writeln(self, *args): if args: apply(self.write, args) self.write(self.linesep)
3,499