code
stringlengths 26
870k
| docstring
stringlengths 1
65.6k
| func_name
stringlengths 1
194
| language
stringclasses 1
value | repo
stringlengths 8
68
| path
stringlengths 5
194
| url
stringlengths 46
254
| license
stringclasses 4
values |
---|---|---|---|---|---|---|---|
def insertBefore(self, new, ref):
"""
Make the given L{Node} C{new} a child of this node which comes before
the L{Node} C{ref}.
@param new: A L{Node} which will become a child of this node.
@param ref: A L{Node} which is already a child of this node which
C{new} will be inserted before.
@raise TypeError: If C{new} or C{ref} is not a C{Node} instance.
@return: C{new}
"""
if not isinstance(new, Node) or not isinstance(ref, Node):
raise TypeError("expected Node instance")
i = self.childNodes.index(ref)
new.parentNode = self
self.childNodes.insert(i, new)
return new | Make the given L{Node} C{new} a child of this node which comes before
the L{Node} C{ref}.
@param new: A L{Node} which will become a child of this node.
@param ref: A L{Node} which is already a child of this node which
C{new} will be inserted before.
@raise TypeError: If C{new} or C{ref} is not a C{Node} instance.
@return: C{new} | insertBefore | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def removeChild(self, child):
"""
Remove the given L{Node} from this node's children.
@param child: A L{Node} which is a child of this node which will no
longer be a child of this node after this method is called.
@raise TypeError: If C{child} is not a C{Node} instance.
@return: C{child}
"""
if not isinstance(child, Node):
raise TypeError("expected Node instance")
if child in self.childNodes:
self.childNodes.remove(child)
child.parentNode = None
return child | Remove the given L{Node} from this node's children.
@param child: A L{Node} which is a child of this node which will no
longer be a child of this node after this method is called.
@raise TypeError: If C{child} is not a C{Node} instance.
@return: C{child} | removeChild | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def replaceChild(self, newChild, oldChild):
"""
Replace a L{Node} which is already a child of this node with a
different node.
@param newChild: A L{Node} which will be made a child of this node.
@param oldChild: A L{Node} which is a child of this node which will
give up its position to C{newChild}.
@raise TypeError: If C{newChild} or C{oldChild} is not a C{Node}
instance.
@raise ValueError: If C{oldChild} is not a child of this C{Node}.
"""
if not isinstance(newChild, Node) or not isinstance(oldChild, Node):
raise TypeError("expected Node instance")
if oldChild.parentNode is not self:
raise ValueError("oldChild is not a child of this node")
self.childNodes[self.childNodes.index(oldChild)] = newChild
oldChild.parentNode = None
newChild.parentNode = self | Replace a L{Node} which is already a child of this node with a
different node.
@param newChild: A L{Node} which will be made a child of this node.
@param oldChild: A L{Node} which is a child of this node which will
give up its position to C{newChild}.
@raise TypeError: If C{newChild} or C{oldChild} is not a C{Node}
instance.
@raise ValueError: If C{oldChild} is not a child of this C{Node}. | replaceChild | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def appendChild(self, child):
"""
Make the given L{Node} the I{document element} of this L{Document}.
@param child: The L{Node} to make into this L{Document}'s document
element.
@raise ValueError: If this document already has a document element.
"""
if self.childNodes:
raise ValueError("Only one element per document.")
Node.appendChild(self, child) | Make the given L{Node} the I{document element} of this L{Document}.
@param child: The L{Node} to make into this L{Document}'s document
element.
@raise ValueError: If this document already has a document element. | appendChild | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def isEqualToNode(self, other):
"""
Compare this text to C{text}. If the underlying values and the C{raw}
flag are the same, return C{True}, otherwise return C{False}.
"""
return (
CharacterData.isEqualToNode(self, other) and
self.raw == other.raw) | Compare this text to C{text}. If the underlying values and the C{raw}
flag are the same, return C{True}, otherwise return C{False}. | isEqualToNode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def isEqualToNode(self, other):
"""
Compare this element to C{other}. If the C{nodeName}, C{namespace},
C{attributes}, and C{childNodes} are all the same, return C{True},
otherwise return C{False}.
"""
return (
self.nodeName.lower() == other.nodeName.lower() and
self.namespace == other.namespace and
self.attributes == other.attributes and
Node.isEqualToNode(self, other)) | Compare this element to C{other}. If the C{nodeName}, C{namespace},
C{attributes}, and C{childNodes} are all the same, return C{True},
otherwise return C{False}. | isEqualToNode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def writexml(self, stream, indent='', addindent='', newl='', strip=0,
nsprefixes={}, namespace=''):
"""
Serialize this L{Element} to the given stream.
@param stream: A file-like object to which this L{Element} will be
written.
@param nsprefixes: A C{dict} mapping namespace URIs as C{str} to
prefixes as C{str}. This defines the prefixes which are already in
scope in the document at the point at which this L{Element} exists.
This is essentially an implementation detail for namespace support.
Applications should not try to use it.
@param namespace: The namespace URI as a C{str} which is the default at
the point in the document at which this L{Element} exists. This is
essentially an implementation detail for namespace support.
Applications should not try to use it.
"""
# write beginning
ALLOWSINGLETON = ('img', 'br', 'hr', 'base', 'meta', 'link', 'param',
'area', 'input', 'col', 'basefont', 'isindex',
'frame')
BLOCKELEMENTS = ('html', 'head', 'body', 'noscript', 'ins', 'del',
'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'script',
'ul', 'ol', 'dl', 'pre', 'hr', 'blockquote',
'address', 'p', 'div', 'fieldset', 'table', 'tr',
'form', 'object', 'fieldset', 'applet', 'map')
FORMATNICELY = ('tr', 'ul', 'ol', 'head')
# this should never be necessary unless people start
# changing .tagName on the fly(?)
if not self.preserveCase:
self.endTagName = self.tagName
w = _streamWriteWrapper(stream)
if self.nsprefixes:
newprefixes = self.nsprefixes.copy()
for ns in nsprefixes.keys():
if ns in newprefixes:
del newprefixes[ns]
else:
newprefixes = {}
begin = ['<']
if self.tagName in BLOCKELEMENTS:
begin = [newl, indent] + begin
bext = begin.extend
writeattr = lambda _atr, _val: bext((' ', _atr, '="', escape(_val), '"'))
# Make a local for tracking what end tag will be used. If namespace
# prefixes are involved, this will be changed to account for that
# before it's actually used.
endTagName = self.endTagName
if namespace != self.namespace and self.namespace is not None:
# If the current default namespace is not the namespace of this tag
# (and this tag has a namespace at all) then we'll write out
# something related to namespaces.
if self.namespace in nsprefixes:
# This tag's namespace already has a prefix bound to it. Use
# that prefix.
prefix = nsprefixes[self.namespace]
bext(prefix + ':' + self.tagName)
# Also make sure we use it for the end tag.
endTagName = prefix + ':' + self.endTagName
else:
# This tag's namespace has no prefix bound to it. Change the
# default namespace to this tag's namespace so we don't need
# prefixes. Alternatively, we could add a new prefix binding.
# I'm not sure why the code was written one way rather than the
# other. -exarkun
bext(self.tagName)
writeattr("xmlns", self.namespace)
# The default namespace just changed. Make sure any children
# know about this.
namespace = self.namespace
else:
# This tag has no namespace or its namespace is already the default
# namespace. Nothing extra to do here.
bext(self.tagName)
j = ''.join
for attr, val in sorted(self.attributes.items()):
if isinstance(attr, tuple):
ns, key = attr
if ns in nsprefixes:
prefix = nsprefixes[ns]
else:
prefix = next(genprefix)
newprefixes[ns] = prefix
assert val is not None
writeattr(prefix + ':' + key, val)
else:
assert val is not None
writeattr(attr, val)
if newprefixes:
for ns, prefix in iteritems(newprefixes):
if prefix:
writeattr('xmlns:'+prefix, ns)
newprefixes.update(nsprefixes)
downprefixes = newprefixes
else:
downprefixes = nsprefixes
w(j(begin))
if self.childNodes:
w(">")
newindent = indent + addindent
for child in self.childNodes:
if self.tagName in BLOCKELEMENTS and \
self.tagName in FORMATNICELY:
w(j((newl, newindent)))
child.writexml(stream, newindent, addindent, newl, strip,
downprefixes, namespace)
if self.tagName in BLOCKELEMENTS:
w(j((newl, indent)))
w(j(('</', endTagName, '>')))
elif self.tagName.lower() not in ALLOWSINGLETON:
w(j(('></', endTagName, '>')))
else:
w(" />") | Serialize this L{Element} to the given stream.
@param stream: A file-like object to which this L{Element} will be
written.
@param nsprefixes: A C{dict} mapping namespace URIs as C{str} to
prefixes as C{str}. This defines the prefixes which are already in
scope in the document at the point at which this L{Element} exists.
This is essentially an implementation detail for namespace support.
Applications should not try to use it.
@param namespace: The namespace URI as a C{str} which is the default at
the point in the document at which this L{Element} exists. This is
essentially an implementation detail for namespace support.
Applications should not try to use it. | writexml | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def parse(readable, *args, **kwargs):
"""
Parse HTML or XML readable.
"""
if not hasattr(readable, "read"):
readable = open(readable, "rb")
mdp = MicroDOMParser(*args, **kwargs)
mdp.filename = getattr(readable, "name", "<xmlfile />")
mdp.makeConnection(None)
if hasattr(readable, "getvalue"):
mdp.dataReceived(readable.getvalue())
else:
r = readable.read(1024)
while r:
mdp.dataReceived(r)
r = readable.read(1024)
mdp.connectionLost(None)
if not mdp.documents:
raise ParseError(mdp.filename, 0, 0, "No top-level Nodes in document")
if mdp.beExtremelyLenient:
if len(mdp.documents) == 1:
d = mdp.documents[0]
if not isinstance(d, Element):
el = Element("html")
el.appendChild(d)
d = el
else:
d = Element("html")
for child in mdp.documents:
d.appendChild(child)
else:
d = mdp.documents[0]
doc = Document(d)
doc.doctype = mdp._mddoctype
return doc | Parse HTML or XML readable. | parse | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def parseXML(readable):
"""
Parse an XML readable object.
"""
return parse(readable, caseInsensitive=0, preserveCase=1) | Parse an XML readable object. | parseXML | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def parseXMLString(st):
"""
Parse an XML readable object.
"""
return parseString(st, caseInsensitive=0, preserveCase=1) | Parse an XML readable object. | parseXMLString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/microdom.py | MIT |
def opt_port(self, port):
"""
(DEPRECATED: use --listen)
Strports description of port to start the server on
"""
msg = deprecate.getDeprecationWarningString(
self.opt_port, incremental.Version('Twisted', 18, 4, 0))
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
self['port'] = port | (DEPRECATED: use --listen)
Strports description of port to start the server on | opt_port | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def opt_https(self, port):
"""
(DEPRECATED: use --listen)
Port to listen on for Secure HTTP.
"""
msg = deprecate.getDeprecationWarningString(
self.opt_https, incremental.Version('Twisted', 18, 4, 0))
warnings.warn(msg, category=DeprecationWarning, stacklevel=2)
self['https'] = port | (DEPRECATED: use --listen)
Port to listen on for Secure HTTP. | opt_https | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def opt_listen(self, port):
"""
Add an strports description of port to start the server on.
[default: tcp:8080]
"""
self['ports'].append(port) | Add an strports description of port to start the server on.
[default: tcp:8080] | opt_listen | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def opt_index(self, indexName):
"""
Add the name of a file used to check for directory indexes.
[default: index, index.html]
"""
self['indexes'].append(indexName) | Add the name of a file used to check for directory indexes.
[default: index, index.html] | opt_index | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def opt_user(self):
"""
Makes a server with ~/public_html and ~/.twistd-web-pb support for
users.
"""
self['root'] = distrib.UserDirectory() | Makes a server with ~/public_html and ~/.twistd-web-pb support for
users. | opt_user | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def opt_path(self, path):
"""
<path> is either a specific file or a directory to be set as the root
of the web server. Use this if you have a directory full of HTML, cgi,
epy, or rpy files or any other files that you want to be served up raw.
"""
self['root'] = static.File(os.path.abspath(path))
self['root'].processors = {
'.epy': script.PythonScript,
'.rpy': script.ResourceScript,
}
self['root'].processors['.cgi'] = twcgi.CGIScript | <path> is either a specific file or a directory to be set as the root
of the web server. Use this if you have a directory full of HTML, cgi,
epy, or rpy files or any other files that you want to be served up raw. | opt_path | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def opt_processor(self, proc):
"""
`ext=class' where `class' is added as a Processor for files ending
with `ext'.
"""
if not isinstance(self['root'], static.File):
raise usage.UsageError(
"You can only use --processor after --path.")
ext, klass = proc.split('=', 1)
self['root'].processors[ext] = reflect.namedClass(klass) | `ext=class' where `class' is added as a Processor for files ending
with `ext'. | opt_processor | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def opt_class(self, className):
"""
Create a Resource subclass with a zero-argument constructor.
"""
classObj = reflect.namedClass(className)
self['root'] = classObj() | Create a Resource subclass with a zero-argument constructor. | opt_class | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def opt_resource_script(self, name):
"""
An .rpy file to be used as the root resource of the webserver.
"""
self['root'] = script.ResourceScriptWrapper(name) | An .rpy file to be used as the root resource of the webserver. | opt_resource_script | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def opt_wsgi(self, name):
"""
The FQPN of a WSGI application object to serve as the root resource of
the webserver.
"""
try:
application = reflect.namedAny(name)
except (AttributeError, ValueError):
raise usage.UsageError("No such WSGI application: %r" % (name,))
pool = threadpool.ThreadPool()
reactor.callWhenRunning(pool.start)
reactor.addSystemEventTrigger('after', 'shutdown', pool.stop)
self['root'] = wsgi.WSGIResource(reactor, pool, application) | The FQPN of a WSGI application object to serve as the root resource of
the webserver. | opt_wsgi | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def opt_mime_type(self, defaultType):
"""
Specify the default mime-type for static files.
"""
if not isinstance(self['root'], static.File):
raise usage.UsageError(
"You can only use --mime_type after --path.")
self['root'].defaultType = defaultType | Specify the default mime-type for static files. | opt_mime_type | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def opt_allow_ignore_ext(self):
"""
Specify whether or not a request for 'foo' should return 'foo.ext'
"""
if not isinstance(self['root'], static.File):
raise usage.UsageError("You can only use --allow_ignore_ext "
"after --path.")
self['root'].ignoreExt('*') | Specify whether or not a request for 'foo' should return 'foo.ext' | opt_allow_ignore_ext | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def opt_ignore_ext(self, ext):
"""
Specify an extension to ignore. These will be processed in order.
"""
if not isinstance(self['root'], static.File):
raise usage.UsageError("You can only use --ignore_ext "
"after --path.")
self['root'].ignoreExt(ext) | Specify an extension to ignore. These will be processed in order. | opt_ignore_ext | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def opt_add_header(self, header):
"""
Specify an additional header to be included in all responses. Specified
as "HeaderName: HeaderValue".
"""
name, value = header.split(':', 1)
self['extraHeaders'].append((name.strip(), value.strip())) | Specify an additional header to be included in all responses. Specified
as "HeaderName: HeaderValue". | opt_add_header | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def postOptions(self):
"""
Set up conditional defaults and check for dependencies.
If SSL is not available but an HTTPS server was configured, raise a
L{UsageError} indicating that this is not possible.
If no server port was supplied, select a default appropriate for the
other options supplied.
"""
if self['port'] is not None:
self['ports'].append(self['port'])
if self['https'] is not None:
try:
reflect.namedModule('OpenSSL.SSL')
except ImportError:
raise usage.UsageError("SSL support not installed")
sslStrport = 'ssl:port={}:privateKey={}:certKey={}'.format(
self['https'],
self['privkey'],
self['certificate'],
)
self['ports'].append(sslStrport)
if len(self['ports']) == 0:
if self['personal']:
path = os.path.expanduser(
os.path.join('~', distrib.UserDirectory.userSocketName))
self['ports'].append('unix:' + path)
else:
self['ports'].append('tcp:8080') | Set up conditional defaults and check for dependencies.
If SSL is not available but an HTTPS server was configured, raise a
L{UsageError} indicating that this is not possible.
If no server port was supplied, select a default appropriate for the
other options supplied. | postOptions | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def makePersonalServerFactory(site):
"""
Create and return a factory which will respond to I{distrib} requests
against the given site.
@type site: L{twisted.web.server.Site}
@rtype: L{twisted.internet.protocol.Factory}
"""
return pb.PBServerFactory(distrib.ResourcePublisher(site)) | Create and return a factory which will respond to I{distrib} requests
against the given site.
@type site: L{twisted.web.server.Site}
@rtype: L{twisted.internet.protocol.Factory} | makePersonalServerFactory | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/tap.py | MIT |
def getChallenge(self, request):
"""
Return a challenge including the HTTP authentication realm with which
this factory was created.
"""
return {'realm': self.authenticationRealm} | Return a challenge including the HTTP authentication realm with which
this factory was created. | getChallenge | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/basic.py | MIT |
def decode(self, response, request):
"""
Parse the base64-encoded, colon-separated username and password into a
L{credentials.UsernamePassword} instance.
"""
try:
creds = binascii.a2b_base64(response + b'===')
except binascii.Error:
raise error.LoginFailed('Invalid credentials')
creds = creds.split(b':', 1)
if len(creds) == 2:
return credentials.UsernamePassword(*creds)
else:
raise error.LoginFailed('Invalid credentials') | Parse the base64-encoded, colon-separated username and password into a
L{credentials.UsernamePassword} instance. | decode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/basic.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/basic.py | MIT |
def render(self, request):
"""
Send www-authenticate headers to the client
"""
def ensureBytes(s):
return s.encode('ascii') if isinstance(s, unicode) else s
def generateWWWAuthenticate(scheme, challenge):
l = []
for k, v in challenge.items():
k = ensureBytes(k)
v = ensureBytes(v)
l.append(k + b"=" + quoteString(v))
return b" ".join([scheme, b", ".join(l)])
def quoteString(s):
return b'"' + s.replace(b'\\', b'\\\\').replace(b'"', b'\\"') + b'"'
request.setResponseCode(401)
for fact in self._credentialFactories:
challenge = fact.getChallenge(request)
request.responseHeaders.addRawHeader(
b'www-authenticate',
generateWWWAuthenticate(fact.scheme, challenge))
if request.method == b'HEAD':
return b''
return b'Unauthorized' | Send www-authenticate headers to the client | render | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | MIT |
def getChildWithDefault(self, path, request):
"""
Disable resource dispatch
"""
return self | Disable resource dispatch | getChildWithDefault | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | MIT |
def __init__(self, portal, credentialFactories):
"""
Initialize a session wrapper
@type portal: C{Portal}
@param portal: The portal that will authenticate the remote client
@type credentialFactories: C{Iterable}
@param credentialFactories: The portal that will authenticate the
remote client based on one submitted C{ICredentialFactory}
"""
self._portal = portal
self._credentialFactories = credentialFactories | Initialize a session wrapper
@type portal: C{Portal}
@param portal: The portal that will authenticate the remote client
@type credentialFactories: C{Iterable}
@param credentialFactories: The portal that will authenticate the
remote client based on one submitted C{ICredentialFactory} | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | MIT |
def _authorizedResource(self, request):
"""
Get the L{IResource} which the given request is authorized to receive.
If the proper authorization headers are present, the resource will be
requested from the portal. If not, an anonymous login attempt will be
made.
"""
authheader = request.getHeader(b'authorization')
if not authheader:
return util.DeferredResource(self._login(Anonymous()))
factory, respString = self._selectParseHeader(authheader)
if factory is None:
return UnauthorizedResource(self._credentialFactories)
try:
credentials = factory.decode(respString, request)
except error.LoginFailed:
return UnauthorizedResource(self._credentialFactories)
except:
self._log.failure("Unexpected failure from credentials factory")
return ErrorPage(500, None, None)
else:
return util.DeferredResource(self._login(credentials)) | Get the L{IResource} which the given request is authorized to receive.
If the proper authorization headers are present, the resource will be
requested from the portal. If not, an anonymous login attempt will be
made. | _authorizedResource | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | MIT |
def render(self, request):
"""
Find the L{IResource} avatar suitable for the given request, if
possible, and render it. Otherwise, perhaps render an error page
requiring authorization or describing an internal server failure.
"""
return self._authorizedResource(request).render(request) | Find the L{IResource} avatar suitable for the given request, if
possible, and render it. Otherwise, perhaps render an error page
requiring authorization or describing an internal server failure. | render | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | MIT |
def getChildWithDefault(self, path, request):
"""
Inspect the Authorization HTTP header, and return a deferred which,
when fired after successful authentication, will return an authorized
C{Avatar}. On authentication failure, an C{UnauthorizedResource} will
be returned, essentially halting further dispatch on the wrapped
resource and all children
"""
# Don't consume any segments of the request - this class should be
# transparent!
request.postpath.insert(0, request.prepath.pop())
return self._authorizedResource(request) | Inspect the Authorization HTTP header, and return a deferred which,
when fired after successful authentication, will return an authorized
C{Avatar}. On authentication failure, an C{UnauthorizedResource} will
be returned, essentially halting further dispatch on the wrapped
resource and all children | getChildWithDefault | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | MIT |
def _login(self, credentials):
"""
Get the L{IResource} avatar for the given credentials.
@return: A L{Deferred} which will be called back with an L{IResource}
avatar or which will errback if authentication fails.
"""
d = self._portal.login(credentials, None, IResource)
d.addCallbacks(self._loginSucceeded, self._loginFailed)
return d | Get the L{IResource} avatar for the given credentials.
@return: A L{Deferred} which will be called back with an L{IResource}
avatar or which will errback if authentication fails. | _login | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | MIT |
def getChildWithDefault(self, name, request):
"""
Pass through the lookup to the wrapped resource, wrapping
the result in L{ResourceWrapper} to ensure C{logout} is
called when rendering of the child is complete.
"""
return ResourceWrapper(self.resource.getChildWithDefault(name, request)) | Pass through the lookup to the wrapped resource, wrapping
the result in L{ResourceWrapper} to ensure C{logout} is
called when rendering of the child is complete. | _loginSucceeded.getChildWithDefault | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | MIT |
def render(self, request):
"""
Hook into response generation so that when rendering has
finished completely (with or without error), C{logout} is
called.
"""
request.notifyFinish().addBoth(lambda ign: logout())
return super(ResourceWrapper, self).render(request) | Hook into response generation so that when rendering has
finished completely (with or without error), C{logout} is
called. | _loginSucceeded.render | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | MIT |
def _loginSucceeded(self, args):
"""
Handle login success by wrapping the resulting L{IResource} avatar
so that the C{logout} callback will be invoked when rendering is
complete.
"""
interface, avatar, logout = args
class ResourceWrapper(proxyForInterface(IResource, 'resource')):
"""
Wrap an L{IResource} so that whenever it or a child of it
completes rendering, the cred logout hook will be invoked.
An assumption is made here that exactly one L{IResource} from
among C{avatar} and all of its children will be rendered. If
more than one is rendered, C{logout} will be invoked multiple
times and probably earlier than desired.
"""
def getChildWithDefault(self, name, request):
"""
Pass through the lookup to the wrapped resource, wrapping
the result in L{ResourceWrapper} to ensure C{logout} is
called when rendering of the child is complete.
"""
return ResourceWrapper(self.resource.getChildWithDefault(name, request))
def render(self, request):
"""
Hook into response generation so that when rendering has
finished completely (with or without error), C{logout} is
called.
"""
request.notifyFinish().addBoth(lambda ign: logout())
return super(ResourceWrapper, self).render(request)
return ResourceWrapper(avatar) | Handle login success by wrapping the resulting L{IResource} avatar
so that the C{logout} callback will be invoked when rendering is
complete. | _loginSucceeded | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | MIT |
def _loginFailed(self, result):
"""
Handle login failure by presenting either another challenge (for
expected authentication/authorization-related failures) or a server
error page (for anything else).
"""
if result.check(error.Unauthorized, error.LoginFailed):
return UnauthorizedResource(self._credentialFactories)
else:
self._log.failure(
"HTTPAuthSessionWrapper.getChildWithDefault encountered "
"unexpected error",
failure=result,
)
return ErrorPage(500, None, None) | Handle login failure by presenting either another challenge (for
expected authentication/authorization-related failures) or a server
error page (for anything else). | _loginFailed | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | MIT |
def _selectParseHeader(self, header):
"""
Choose an C{ICredentialFactory} from C{_credentialFactories}
suitable to use to decode the given I{Authenticate} header.
@return: A two-tuple of a factory and the remaining portion of the
header value to be decoded or a two-tuple of L{None} if no
factory can decode the header value.
"""
elements = header.split(b' ')
scheme = elements[0].lower()
for fact in self._credentialFactories:
if fact.scheme == scheme:
return (fact, b' '.join(elements[1:]))
return (None, None) | Choose an C{ICredentialFactory} from C{_credentialFactories}
suitable to use to decode the given I{Authenticate} header.
@return: A two-tuple of a factory and the remaining portion of the
header value to be decoded or a two-tuple of L{None} if no
factory can decode the header value. | _selectParseHeader | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/wrapper.py | MIT |
def __init__(self, algorithm, authenticationRealm):
"""
Create the digest credential factory that this object wraps.
"""
self.digest = credentials.DigestCredentialFactory(algorithm,
authenticationRealm) | Create the digest credential factory that this object wraps. | __init__ | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/digest.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/digest.py | MIT |
def getChallenge(self, request):
"""
Generate the challenge for use in the WWW-Authenticate header
@param request: The L{IRequest} to with access was denied and for the
response to which this challenge is being generated.
@return: The L{dict} that can be used to generate a WWW-Authenticate
header.
"""
return self.digest.getChallenge(request.getClientAddress().host) | Generate the challenge for use in the WWW-Authenticate header
@param request: The L{IRequest} to with access was denied and for the
response to which this challenge is being generated.
@return: The L{dict} that can be used to generate a WWW-Authenticate
header. | getChallenge | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/digest.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/digest.py | MIT |
def decode(self, response, request):
"""
Create a L{twisted.cred.credentials.DigestedCredentials} object
from the given response and request.
@see: L{ICredentialFactory.decode}
"""
return self.digest.decode(response,
request.method,
request.getClientAddress().host) | Create a L{twisted.cred.credentials.DigestedCredentials} object
from the given response and request.
@see: L{ICredentialFactory.decode} | decode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/digest.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/_auth/digest.py | MIT |
def proto(*a, **kw):
"""
Produce a new tag for testing.
"""
return Tag('hello')(*a, **kw) | Produce a new tag for testing. | proto | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | MIT |
def test_fillSlots(self):
"""
L{Tag.fillSlots} returns self.
"""
tag = proto()
self.assertIdentical(tag, tag.fillSlots(test='test')) | L{Tag.fillSlots} returns self. | test_fillSlots | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | MIT |
def test_cloneShallow(self):
"""
L{Tag.clone} copies all attributes and children of a tag, including its
render attribute. If the shallow flag is C{False}, that's where it
stops.
"""
innerList = ["inner list"]
tag = proto("How are you", innerList,
hello="world", render="aSampleMethod")
tag.fillSlots(foo='bar')
tag.filename = "foo/bar"
tag.lineNumber = 6
tag.columnNumber = 12
clone = tag.clone(deep=False)
self.assertEqual(clone.attributes['hello'], 'world')
self.assertNotIdentical(clone.attributes, tag.attributes)
self.assertEqual(clone.children, ["How are you", innerList])
self.assertNotIdentical(clone.children, tag.children)
self.assertIdentical(clone.children[1], innerList)
self.assertEqual(tag.slotData, clone.slotData)
self.assertNotIdentical(tag.slotData, clone.slotData)
self.assertEqual(clone.filename, "foo/bar")
self.assertEqual(clone.lineNumber, 6)
self.assertEqual(clone.columnNumber, 12)
self.assertEqual(clone.render, "aSampleMethod") | L{Tag.clone} copies all attributes and children of a tag, including its
render attribute. If the shallow flag is C{False}, that's where it
stops. | test_cloneShallow | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | MIT |
def test_cloneDeep(self):
"""
L{Tag.clone} copies all attributes and children of a tag, including its
render attribute. In its normal operating mode (where the deep flag is
C{True}, as is the default), it will clone all sub-lists and sub-tags.
"""
innerTag = proto("inner")
innerList = ["inner list"]
tag = proto("How are you", innerTag, innerList,
hello="world", render="aSampleMethod")
tag.fillSlots(foo='bar')
tag.filename = "foo/bar"
tag.lineNumber = 6
tag.columnNumber = 12
clone = tag.clone()
self.assertEqual(clone.attributes['hello'], 'world')
self.assertNotIdentical(clone.attributes, tag.attributes)
self.assertNotIdentical(clone.children, tag.children)
# sanity check
self.assertIdentical(tag.children[1], innerTag)
# clone should have sub-clone
self.assertNotIdentical(clone.children[1], innerTag)
# sanity check
self.assertIdentical(tag.children[2], innerList)
# clone should have sub-clone
self.assertNotIdentical(clone.children[2], innerList)
self.assertEqual(tag.slotData, clone.slotData)
self.assertNotIdentical(tag.slotData, clone.slotData)
self.assertEqual(clone.filename, "foo/bar")
self.assertEqual(clone.lineNumber, 6)
self.assertEqual(clone.columnNumber, 12)
self.assertEqual(clone.render, "aSampleMethod") | L{Tag.clone} copies all attributes and children of a tag, including its
render attribute. In its normal operating mode (where the deep flag is
C{True}, as is the default), it will clone all sub-lists and sub-tags. | test_cloneDeep | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | MIT |
def test_clear(self):
"""
L{Tag.clear} removes all children from a tag, but leaves its attributes
in place.
"""
tag = proto("these are", "children", "cool", andSoIs='this-attribute')
tag.clear()
self.assertEqual(tag.children, [])
self.assertEqual(tag.attributes, {'andSoIs': 'this-attribute'}) | L{Tag.clear} removes all children from a tag, but leaves its attributes
in place. | test_clear | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | MIT |
def test_suffix(self):
"""
L{Tag.__call__} accepts Python keywords with a suffixed underscore as
the DOM attribute of that literal suffix.
"""
proto = Tag('div')
tag = proto()
tag(class_='a')
self.assertEqual(tag.attributes, {'class': 'a'}) | L{Tag.__call__} accepts Python keywords with a suffixed underscore as
the DOM attribute of that literal suffix. | test_suffix | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | MIT |
def test_commentReprPy2(self):
"""
L{Comment.__repr__} returns a value which makes it easy to see what's
in the comment.
"""
self.assertEqual(repr(Comment(u"hello there")),
"Comment(u'hello there')") | L{Comment.__repr__} returns a value which makes it easy to see what's
in the comment. | test_commentReprPy2 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | MIT |
def test_cdataReprPy2(self):
"""
L{CDATA.__repr__} returns a value which makes it easy to see what's in
the comment.
"""
self.assertEqual(repr(CDATA(u"test data")),
"CDATA(u'test data')") | L{CDATA.__repr__} returns a value which makes it easy to see what's in
the comment. | test_cdataReprPy2 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | MIT |
def test_commentReprPy3(self):
"""
L{Comment.__repr__} returns a value which makes it easy to see what's
in the comment.
"""
self.assertEqual(repr(Comment(u"hello there")),
"Comment('hello there')") | L{Comment.__repr__} returns a value which makes it easy to see what's
in the comment. | test_commentReprPy3 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | MIT |
def test_cdataReprPy3(self):
"""
L{CDATA.__repr__} returns a value which makes it easy to see what's in
the comment.
"""
self.assertEqual(repr(CDATA(u"test data")),
"CDATA('test data')") | L{CDATA.__repr__} returns a value which makes it easy to see what's in
the comment. | test_cdataReprPy3 | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | MIT |
def test_charrefRepr(self):
"""
L{CharRef.__repr__} returns a value which makes it easy to see what
character is referred to.
"""
snowman = ord(u"\N{SNOWMAN}")
self.assertEqual(repr(CharRef(snowman)), "CharRef(9731)") | L{CharRef.__repr__} returns a value which makes it easy to see what
character is referred to. | test_charrefRepr | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_stan.py | MIT |
def assertDeprecationWarningOf(method):
"""
Check that a deprecation warning is present.
"""
warningsShown = self.flushWarnings([self.test_deprecation])
self.assertEqual(len(warningsShown), 1)
self.assertIdentical(
warningsShown[0]['category'], DeprecationWarning)
self.assertEqual(
warningsShown[0]['message'],
'twisted.web.html.%s was deprecated in Twisted 15.3.0; '
'please use twisted.web.template instead' % (
method,),
) | Check that a deprecation warning is present. | test_deprecation.assertDeprecationWarningOf | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_html.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_html.py | MIT |
def test_deprecation(self):
"""
Calls to L{twisted.web.html} members emit a deprecation warning.
"""
def assertDeprecationWarningOf(method):
"""
Check that a deprecation warning is present.
"""
warningsShown = self.flushWarnings([self.test_deprecation])
self.assertEqual(len(warningsShown), 1)
self.assertIdentical(
warningsShown[0]['category'], DeprecationWarning)
self.assertEqual(
warningsShown[0]['message'],
'twisted.web.html.%s was deprecated in Twisted 15.3.0; '
'please use twisted.web.template instead' % (
method,),
)
html.PRE('')
assertDeprecationWarningOf('PRE')
html.UL([])
assertDeprecationWarningOf('UL')
html.linkList([])
assertDeprecationWarningOf('linkList')
html.output(lambda: None)
assertDeprecationWarningOf('output') | Calls to L{twisted.web.html} members emit a deprecation warning. | test_deprecation | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_html.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_html.py | MIT |
def test_nestedTags(self):
"""
Test that nested tags flatten correctly.
"""
return self.assertFlattensTo(
tags.html(tags.body('42'), hi='there'),
b'<html hi="there"><body>42</body></html>') | Test that nested tags flatten correctly. | test_nestedTags | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeString(self):
"""
Test that strings will be flattened and escaped correctly.
"""
return gatherResults([
self.assertFlattensTo('one', b'one'),
self.assertFlattensTo('<abc&&>123', b'<abc&&>123'),
]) | Test that strings will be flattened and escaped correctly. | test_serializeString | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeSelfClosingTags(self):
"""
The serialized form of a self-closing tag is C{'<tagName />'}.
"""
return self.assertFlattensTo(tags.img(), b'<img />') | The serialized form of a self-closing tag is C{'<tagName />'}. | test_serializeSelfClosingTags | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeAttribute(self):
"""
The serialized form of attribute I{a} with value I{b} is C{'a="b"'}.
"""
self.assertFlattensImmediately(tags.img(src='foo'),
b'<img src="foo" />') | The serialized form of attribute I{a} with value I{b} is C{'a="b"'}. | test_serializeAttribute | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializedMultipleAttributes(self):
"""
Multiple attributes are separated by a single space in their serialized
form.
"""
tag = tags.img()
tag.attributes = OrderedDict([("src", "foo"), ("name", "bar")])
self.assertFlattensImmediately(tag, b'<img src="foo" name="bar" />') | Multiple attributes are separated by a single space in their serialized
form. | test_serializedMultipleAttributes | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def checkAttributeSanitization(self, wrapData, wrapTag):
"""
Common implementation of L{test_serializedAttributeWithSanitization}
and L{test_serializedDeferredAttributeWithSanitization},
L{test_serializedAttributeWithTransparentTag}.
@param wrapData: A 1-argument callable that wraps around the
attribute's value so other tests can customize it.
@param wrapData: callable taking L{bytes} and returning something
flattenable
@param wrapTag: A 1-argument callable that wraps around the outer tag
so other tests can customize it.
@type wrapTag: callable taking L{Tag} and returning L{Tag}.
"""
self.assertFlattensImmediately(
wrapTag(tags.img(src=wrapData("<>&\""))),
b'<img src="<>&"" />') | Common implementation of L{test_serializedAttributeWithSanitization}
and L{test_serializedDeferredAttributeWithSanitization},
L{test_serializedAttributeWithTransparentTag}.
@param wrapData: A 1-argument callable that wraps around the
attribute's value so other tests can customize it.
@param wrapData: callable taking L{bytes} and returning something
flattenable
@param wrapTag: A 1-argument callable that wraps around the outer tag
so other tests can customize it.
@type wrapTag: callable taking L{Tag} and returning L{Tag}. | checkAttributeSanitization | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializedAttributeWithSanitization(self):
"""
Attribute values containing C{"<"}, C{">"}, C{"&"}, or C{'"'} have
C{"<"}, C{">"}, C{"&"}, or C{"""} substituted for those
bytes in the serialized output.
"""
self.checkAttributeSanitization(passthru, passthru) | Attribute values containing C{"<"}, C{">"}, C{"&"}, or C{'"'} have
C{"<"}, C{">"}, C{"&"}, or C{"""} substituted for those
bytes in the serialized output. | test_serializedAttributeWithSanitization | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializedDeferredAttributeWithSanitization(self):
"""
Like L{test_serializedAttributeWithSanitization}, but when the contents
of the attribute are in a L{Deferred
<twisted.internet.defer.Deferred>}.
"""
self.checkAttributeSanitization(succeed, passthru) | Like L{test_serializedAttributeWithSanitization}, but when the contents
of the attribute are in a L{Deferred
<twisted.internet.defer.Deferred>}. | test_serializedDeferredAttributeWithSanitization | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializedAttributeWithSlotWithSanitization(self):
"""
Like L{test_serializedAttributeWithSanitization} but with a slot.
"""
toss = []
self.checkAttributeSanitization(
lambda value: toss.append(value) or slot("stuff"),
lambda tag: tag.fillSlots(stuff=toss.pop())
) | Like L{test_serializedAttributeWithSanitization} but with a slot. | test_serializedAttributeWithSlotWithSanitization | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializedAttributeWithTransparentTag(self):
"""
Attribute values which are supplied via the value of a C{t:transparent}
tag have the same substitution rules to them as values supplied
directly.
"""
self.checkAttributeSanitization(tags.transparent, passthru) | Attribute values which are supplied via the value of a C{t:transparent}
tag have the same substitution rules to them as values supplied
directly. | test_serializedAttributeWithTransparentTag | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializedAttributeWithTransparentTagWithRenderer(self):
"""
Like L{test_serializedAttributeWithTransparentTag}, but when the
attribute is rendered by a renderer on an element.
"""
class WithRenderer(Element):
def __init__(self, value, loader):
self.value = value
super(WithRenderer, self).__init__(loader)
@renderer
def stuff(self, request, tag):
return self.value
toss = []
self.checkAttributeSanitization(
lambda value: toss.append(value) or
tags.transparent(render="stuff"),
lambda tag: WithRenderer(toss.pop(), TagLoader(tag))
) | Like L{test_serializedAttributeWithTransparentTag}, but when the
attribute is rendered by a renderer on an element. | test_serializedAttributeWithTransparentTagWithRenderer | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializedAttributeWithRenderable(self):
"""
Like L{test_serializedAttributeWithTransparentTag}, but when the
attribute is a provider of L{IRenderable} rather than a transparent
tag.
"""
@implementer(IRenderable)
class Arbitrary(object):
def __init__(self, value):
self.value = value
def render(self, request):
return self.value
self.checkAttributeSanitization(Arbitrary, passthru) | Like L{test_serializedAttributeWithTransparentTag}, but when the
attribute is a provider of L{IRenderable} rather than a transparent
tag. | test_serializedAttributeWithRenderable | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def checkTagAttributeSerialization(self, wrapTag):
"""
Common implementation of L{test_serializedAttributeWithTag} and
L{test_serializedAttributeWithDeferredTag}.
@param wrapTag: A 1-argument callable that wraps around the attribute's
value so other tests can customize it.
@param wrapTag: callable taking L{Tag} and returning something
flattenable
"""
innerTag = tags.a('<>&"')
outerTag = tags.img(src=wrapTag(innerTag))
outer = self.assertFlattensImmediately(
outerTag,
b'<img src="<a>&lt;&gt;&amp;"</a>" />')
inner = self.assertFlattensImmediately(
innerTag, b'<a><>&"</a>')
# Since the above quoting is somewhat tricky, validate it by making sure
# that the main use-case for tag-within-attribute is supported here: if
# we serialize a tag, it is quoted *such that it can be parsed out again
# as a tag*.
self.assertXMLEqual(XML(outer).attrib['src'], inner) | Common implementation of L{test_serializedAttributeWithTag} and
L{test_serializedAttributeWithDeferredTag}.
@param wrapTag: A 1-argument callable that wraps around the attribute's
value so other tests can customize it.
@param wrapTag: callable taking L{Tag} and returning something
flattenable | checkTagAttributeSerialization | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializedAttributeWithTag(self):
"""
L{Tag} objects which are serialized within the context of an attribute
are serialized such that the text content of the attribute may be
parsed to retrieve the tag.
"""
self.checkTagAttributeSerialization(passthru) | L{Tag} objects which are serialized within the context of an attribute
are serialized such that the text content of the attribute may be
parsed to retrieve the tag. | test_serializedAttributeWithTag | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializedAttributeWithDeferredTag(self):
"""
Like L{test_serializedAttributeWithTag}, but when the L{Tag} is in a
L{Deferred <twisted.internet.defer.Deferred>}.
"""
self.checkTagAttributeSerialization(succeed) | Like L{test_serializedAttributeWithTag}, but when the L{Tag} is in a
L{Deferred <twisted.internet.defer.Deferred>}. | test_serializedAttributeWithDeferredTag | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializedAttributeWithTagWithAttribute(self):
"""
Similar to L{test_serializedAttributeWithTag}, but for the additional
complexity where the tag which is the attribute value itself has an
attribute value which contains bytes which require substitution.
"""
flattened = self.assertFlattensImmediately(
tags.img(src=tags.a(href='<>&"')),
b'<img src="<a href='
b'"&lt;&gt;&amp;&quot;">'
b'</a>" />')
# As in checkTagAttributeSerialization, belt-and-suspenders:
self.assertXMLEqual(XML(flattened).attrib['src'],
b'<a href="<>&""></a>') | Similar to L{test_serializedAttributeWithTag}, but for the additional
complexity where the tag which is the attribute value itself has an
attribute value which contains bytes which require substitution. | test_serializedAttributeWithTagWithAttribute | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeComment(self):
"""
Test that comments are correctly flattened and escaped.
"""
return self.assertFlattensTo(Comment('foo bar'), b'<!--foo bar-->'), | Test that comments are correctly flattened and escaped. | test_serializeComment | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_commentEscaping(self):
"""
The data in a L{Comment} is escaped and mangled in the flattened output
so that the result is a legal SGML and XML comment.
SGML comment syntax is complicated and hard to use. This rule is more
restrictive, and more compatible:
Comments start with <!-- and end with --> and never contain -- or >.
Also by XML syntax, a comment may not end with '-'.
@see: U{http://www.w3.org/TR/REC-xml/#sec-comments}
"""
def verifyComment(c):
self.assertTrue(
c.startswith(b'<!--'),
"%r does not start with the comment prefix" % (c,))
self.assertTrue(
c.endswith(b'-->'),
"%r does not end with the comment suffix" % (c,))
# If it is shorter than 7, then the prefix and suffix overlap
# illegally.
self.assertTrue(
len(c) >= 7,
"%r is too short to be a legal comment" % (c,))
content = c[4:-3]
self.assertNotIn(b'--', content)
self.assertNotIn(b'>', content)
if content:
self.assertNotEqual(content[-1], b'-')
results = []
for c in [
'',
'foo---bar',
'foo---bar-',
'foo>bar',
'foo-->bar',
'----------------',
]:
d = flattenString(None, Comment(c))
d.addCallback(verifyComment)
results.append(d)
return gatherResults(results) | The data in a L{Comment} is escaped and mangled in the flattened output
so that the result is a legal SGML and XML comment.
SGML comment syntax is complicated and hard to use. This rule is more
restrictive, and more compatible:
Comments start with <!-- and end with --> and never contain -- or >.
Also by XML syntax, a comment may not end with '-'.
@see: U{http://www.w3.org/TR/REC-xml/#sec-comments} | test_commentEscaping | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeCDATA(self):
"""
Test that CDATA is correctly flattened and escaped.
"""
return gatherResults([
self.assertFlattensTo(CDATA('foo bar'), b'<![CDATA[foo bar]]>'),
self.assertFlattensTo(
CDATA('foo ]]> bar'),
b'<![CDATA[foo ]]]]><![CDATA[> bar]]>'),
]) | Test that CDATA is correctly flattened and escaped. | test_serializeCDATA | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeUnicode(self):
"""
Test that unicode is encoded correctly in the appropriate places, and
raises an error when it occurs in inappropriate place.
"""
snowman = u'\N{SNOWMAN}'
return gatherResults([
self.assertFlattensTo(snowman, b'\xe2\x98\x83'),
self.assertFlattensTo(tags.p(snowman), b'<p>\xe2\x98\x83</p>'),
self.assertFlattensTo(Comment(snowman), b'<!--\xe2\x98\x83-->'),
self.assertFlattensTo(CDATA(snowman), b'<![CDATA[\xe2\x98\x83]]>'),
self.assertFlatteningRaises(
Tag(snowman), UnicodeEncodeError),
self.assertFlatteningRaises(
Tag('p', attributes={snowman: ''}), UnicodeEncodeError),
]) | Test that unicode is encoded correctly in the appropriate places, and
raises an error when it occurs in inappropriate place. | test_serializeUnicode | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeCharRef(self):
"""
A character reference is flattened to a string using the I{&#NNNN;}
syntax.
"""
ref = CharRef(ord(u"\N{SNOWMAN}"))
return self.assertFlattensTo(ref, b"☃") | A character reference is flattened to a string using the I{&#NNNN;}
syntax. | test_serializeCharRef | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeDeferred(self):
"""
Test that a deferred is substituted with the current value in the
callback chain when flattened.
"""
return self.assertFlattensTo(succeed('two'), b'two') | Test that a deferred is substituted with the current value in the
callback chain when flattened. | test_serializeDeferred | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeSameDeferredTwice(self):
"""
Test that the same deferred can be flattened twice.
"""
d = succeed('three')
return gatherResults([
self.assertFlattensTo(d, b'three'),
self.assertFlattensTo(d, b'three'),
]) | Test that the same deferred can be flattened twice. | test_serializeSameDeferredTwice | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeCoroutine(self):
"""
Test that a coroutine returning a value is substituted with the that
value when flattened.
"""
from textwrap import dedent
namespace = {}
exec(dedent(
"""
async def coro(x):
return x
"""
), namespace)
coro = namespace["coro"]
return self.assertFlattensTo(coro('four'), b'four') | Test that a coroutine returning a value is substituted with the that
value when flattened. | test_serializeCoroutine | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeCoroutineWithAwait(self):
"""
Test that a coroutine returning an awaited deferred value is
substituted with that value when flattened.
"""
from textwrap import dedent
namespace = dict(succeed=succeed)
exec(dedent(
"""
async def coro(x):
return await succeed(x)
"""
), namespace)
coro = namespace["coro"]
return self.assertFlattensTo(coro('four'), b'four') | Test that a coroutine returning an awaited deferred value is
substituted with that value when flattened. | test_serializeCoroutineWithAwait | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeIRenderable(self):
"""
Test that flattening respects all of the IRenderable interface.
"""
@implementer(IRenderable)
class FakeElement(object):
def render(ign,ored):
return tags.p(
'hello, ',
tags.transparent(render='test'), ' - ',
tags.transparent(render='test'))
def lookupRenderMethod(ign, name):
self.assertEqual(name, 'test')
return lambda ign, node: node('world')
return gatherResults([
self.assertFlattensTo(FakeElement(), b'<p>hello, world - world</p>'),
]) | Test that flattening respects all of the IRenderable interface. | test_serializeIRenderable | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeSlots(self):
"""
Test that flattening a slot will use the slot value from the tag.
"""
t1 = tags.p(slot('test'))
t2 = t1.clone()
t2.fillSlots(test='hello, world')
return gatherResults([
self.assertFlatteningRaises(t1, UnfilledSlot),
self.assertFlattensTo(t2, b'<p>hello, world</p>'),
]) | Test that flattening a slot will use the slot value from the tag. | test_serializeSlots | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_serializeDeferredSlots(self):
"""
Test that a slot with a deferred as its value will be flattened using
the value from the deferred.
"""
t = tags.p(slot('test'))
t.fillSlots(test=succeed(tags.em('four>')))
return self.assertFlattensTo(t, b'<p><em>four></em></p>') | Test that a slot with a deferred as its value will be flattened using
the value from the deferred. | test_serializeDeferredSlots | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_unknownTypeRaises(self):
"""
Test that flattening an unknown type of thing raises an exception.
"""
return self.assertFlatteningRaises(None, UnsupportedType) | Test that flattening an unknown type of thing raises an exception. | test_unknownTypeRaises | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_renderable(self):
"""
If a L{FlattenerError} is created with an L{IRenderable} provider root,
the repr of that object is included in the string representation of the
exception.
"""
@implementer(IRenderable)
class Renderable(object):
def __repr__(self):
return "renderable repr"
self.assertEqual(
str(FlattenerError(
RuntimeError("reason"), [Renderable()], [])),
"Exception while flattening:\n"
" renderable repr\n"
"RuntimeError: reason\n") | If a L{FlattenerError} is created with an L{IRenderable} provider root,
the repr of that object is included in the string representation of the
exception. | test_renderable | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_tag(self):
"""
If a L{FlattenerError} is created with a L{Tag} instance with source
location information, the source location is included in the string
representation of the exception.
"""
tag = Tag(
'div', filename='/foo/filename.xhtml', lineNumber=17, columnNumber=12)
self.assertEqual(
str(FlattenerError(RuntimeError("reason"), [tag], [])),
"Exception while flattening:\n"
" File \"/foo/filename.xhtml\", line 17, column 12, in \"div\"\n"
"RuntimeError: reason\n") | If a L{FlattenerError} is created with a L{Tag} instance with source
location information, the source location is included in the string
representation of the exception. | test_tag | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_tagWithoutLocation(self):
"""
If a L{FlattenerError} is created with a L{Tag} instance without source
location information, only the tagName is included in the string
representation of the exception.
"""
self.assertEqual(
str(FlattenerError(RuntimeError("reason"), [Tag('span')], [])),
"Exception while flattening:\n"
" Tag <span>\n"
"RuntimeError: reason\n") | If a L{FlattenerError} is created with a L{Tag} instance without source
location information, only the tagName is included in the string
representation of the exception. | test_tagWithoutLocation | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def test_traceback(self):
"""
If a L{FlattenerError} is created with traceback frames, they are
included in the string representation of the exception.
"""
# Try to be realistic in creating the data passed in for the traceback
# frames.
def f():
g()
def g():
raise RuntimeError("reason")
try:
f()
except RuntimeError as e:
# Get the traceback, minus the info for *this* frame
tbinfo = traceback.extract_tb(sys.exc_info()[2])[1:]
exc = e
else:
self.fail("f() must raise RuntimeError")
self.assertEqual(
str(FlattenerError(exc, [], tbinfo)),
"Exception while flattening:\n"
" File \"%s\", line %d, in f\n"
" g()\n"
" File \"%s\", line %d, in g\n"
" raise RuntimeError(\"reason\")\n"
"RuntimeError: reason\n" % (
HERE, f.__code__.co_firstlineno + 1,
HERE, g.__code__.co_firstlineno + 1)) | If a L{FlattenerError} is created with traceback frames, they are
included in the string representation of the exception. | test_traceback | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_flatten.py | MIT |
def request(self, request):
"""
Capture the given request for later inspection.
@return: A L{Deferred} which this code will never fire.
"""
result = Deferred()
self.requests.append((request, result))
return result | Capture the given request for later inspection.
@return: A L{Deferred} which this code will never fire. | request | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def _termination(self):
"""
This method can be used as the C{terminationPredicateFactory} for a
L{Cooperator}. It returns a predicate which immediately returns
C{False}, indicating that no more work should be done this iteration.
This has the result of only allowing one iteration of a cooperative
task to be run per L{Cooperator} iteration.
"""
return lambda: True | This method can be used as the C{terminationPredicateFactory} for a
L{Cooperator}. It returns a predicate which immediately returns
C{False}, indicating that no more work should be done this iteration.
This has the result of only allowing one iteration of a cooperative
task to be run per L{Cooperator} iteration. | _termination | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def setUp(self):
"""
Create a L{Cooperator} hooked up to an easily controlled, deterministic
scheduler to use with L{FileBodyProducer}.
"""
self._scheduled = []
self.cooperator = task.Cooperator(
self._termination, self._scheduled.append) | Create a L{Cooperator} hooked up to an easily controlled, deterministic
scheduler to use with L{FileBodyProducer}. | setUp | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_interface(self):
"""
L{FileBodyProducer} instances provide L{IBodyProducer}.
"""
self.assertTrue(verifyObject(
IBodyProducer, FileBodyProducer(BytesIO(b"")))) | L{FileBodyProducer} instances provide L{IBodyProducer}. | test_interface | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_unknownLength(self):
"""
If the L{FileBodyProducer} is constructed with a file-like object
without either a C{seek} or C{tell} method, its C{length} attribute is
set to C{UNKNOWN_LENGTH}.
"""
class HasSeek(object):
def seek(self, offset, whence):
pass
class HasTell(object):
def tell(self):
pass
producer = FileBodyProducer(HasSeek())
self.assertEqual(UNKNOWN_LENGTH, producer.length)
producer = FileBodyProducer(HasTell())
self.assertEqual(UNKNOWN_LENGTH, producer.length) | If the L{FileBodyProducer} is constructed with a file-like object
without either a C{seek} or C{tell} method, its C{length} attribute is
set to C{UNKNOWN_LENGTH}. | test_unknownLength | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_knownLength(self):
"""
If the L{FileBodyProducer} is constructed with a file-like object with
both C{seek} and C{tell} methods, its C{length} attribute is set to the
size of the file as determined by those methods.
"""
inputBytes = b"here are some bytes"
inputFile = BytesIO(inputBytes)
inputFile.seek(5)
producer = FileBodyProducer(inputFile)
self.assertEqual(len(inputBytes) - 5, producer.length)
self.assertEqual(inputFile.tell(), 5) | If the L{FileBodyProducer} is constructed with a file-like object with
both C{seek} and C{tell} methods, its C{length} attribute is set to the
size of the file as determined by those methods. | test_knownLength | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_defaultCooperator(self):
"""
If no L{Cooperator} instance is passed to L{FileBodyProducer}, the
global cooperator is used.
"""
producer = FileBodyProducer(BytesIO(b""))
self.assertEqual(task.cooperate, producer._cooperate) | If no L{Cooperator} instance is passed to L{FileBodyProducer}, the
global cooperator is used. | test_defaultCooperator | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_startProducing(self):
"""
L{FileBodyProducer.startProducing} starts writing bytes from the input
file to the given L{IConsumer} and returns a L{Deferred} which fires
when they have all been written.
"""
expectedResult = b"hello, world"
readSize = 3
output = BytesIO()
consumer = FileConsumer(output)
producer = FileBodyProducer(
BytesIO(expectedResult), self.cooperator, readSize)
complete = producer.startProducing(consumer)
for i in range(len(expectedResult) // readSize + 1):
self._scheduled.pop(0)()
self.assertEqual([], self._scheduled)
self.assertEqual(expectedResult, output.getvalue())
self.assertEqual(None, self.successResultOf(complete)) | L{FileBodyProducer.startProducing} starts writing bytes from the input
file to the given L{IConsumer} and returns a L{Deferred} which fires
when they have all been written. | test_startProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_inputClosedAtEOF(self):
"""
When L{FileBodyProducer} reaches end-of-file on the input file given to
it, the input file is closed.
"""
readSize = 4
inputBytes = b"some friendly bytes"
inputFile = BytesIO(inputBytes)
producer = FileBodyProducer(inputFile, self.cooperator, readSize)
consumer = FileConsumer(BytesIO())
producer.startProducing(consumer)
for i in range(len(inputBytes) // readSize + 2):
self._scheduled.pop(0)()
self.assertTrue(inputFile.closed) | When L{FileBodyProducer} reaches end-of-file on the input file given to
it, the input file is closed. | test_inputClosedAtEOF | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_failedReadWhileProducing(self):
"""
If a read from the input file fails while producing bytes to the
consumer, the L{Deferred} returned by
L{FileBodyProducer.startProducing} fires with a L{Failure} wrapping
that exception.
"""
class BrokenFile(object):
def read(self, count):
raise IOError("Simulated bad thing")
producer = FileBodyProducer(BrokenFile(), self.cooperator)
complete = producer.startProducing(FileConsumer(BytesIO()))
self._scheduled.pop(0)()
self.failureResultOf(complete).trap(IOError) | If a read from the input file fails while producing bytes to the
consumer, the L{Deferred} returned by
L{FileBodyProducer.startProducing} fires with a L{Failure} wrapping
that exception. | test_failedReadWhileProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
def test_stopProducing(self):
"""
L{FileBodyProducer.stopProducing} stops the underlying L{IPullProducer}
and the cooperative task responsible for calling C{resumeProducing} and
closes the input file but does not cause the L{Deferred} returned by
C{startProducing} to fire.
"""
expectedResult = b"hello, world"
readSize = 3
output = BytesIO()
consumer = FileConsumer(output)
inputFile = BytesIO(expectedResult)
producer = FileBodyProducer(
inputFile, self.cooperator, readSize)
complete = producer.startProducing(consumer)
producer.stopProducing()
self.assertTrue(inputFile.closed)
self._scheduled.pop(0)()
self.assertEqual(b"", output.getvalue())
self.assertNoResult(complete) | L{FileBodyProducer.stopProducing} stops the underlying L{IPullProducer}
and the cooperative task responsible for calling C{resumeProducing} and
closes the input file but does not cause the L{Deferred} returned by
C{startProducing} to fire. | test_stopProducing | python | wistbean/learn_python3_spider | stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | https://github.com/wistbean/learn_python3_spider/blob/master/stackoverflow/venv/lib/python3.6/site-packages/twisted/web/test/test_agent.py | MIT |
Subsets and Splits
No saved queries yet
Save your SQL queries to embed, download, and access them later. Queries will appear here once saved.