desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Given the lines of a source string (including prompts and
leading indentation), check to make sure that every prompt is
followed by a space character. If any line is not followed by
a space character, then raise ValueError.'
| def _check_prompt_blank(self, lines, indent, name, lineno):
| for (i, line) in enumerate(lines):
if ((len(line) >= (indent + 4)) and (line[(indent + 3)] != ' ')):
raise ValueError(('line %r of the docstring for %s lacks blank after %s: %r' % (((lineno + i) + 1), name, line[indent:(indent + 3)], line)))
|
'Check that every line in the given list starts with the given
prefix; if any line does not, then raise a ValueError.'
| def _check_prefix(self, lines, prefix, name, lineno):
| for (i, line) in enumerate(lines):
if (line and (not line.startswith(prefix))):
raise ValueError(('line %r of the docstring for %s has inconsistent leading whitespace: %r' % (((lineno + i) + 1), name, line)))
|
'Create a new doctest finder.
The optional argument `parser` specifies a class or
function that should be used to create new DocTest objects (or
objects that implement the same interface as DocTest). The
signature for this factory function should match the signature
of the DocTest constructor.
If the optional argument... | def __init__(self, verbose=False, parser=DocTestParser(), recurse=True, exclude_empty=True):
| self._parser = parser
self._verbose = verbose
self._recurse = recurse
self._exclude_empty = exclude_empty
|
'Return a list of the DocTests that are defined by the given
object\'s docstring, or by any of its contained objects\'
docstrings.
The optional parameter `module` is the module that contains
the given object. If the module is not specified or is None, then
the test finder will attempt to automatically determine the
co... | def find(self, obj, name=None, module=None, globs=None, extraglobs=None):
| if (name is None):
name = getattr(obj, '__name__', None)
if (name is None):
raise ValueError(("DocTestFinder.find: name must be given when obj.__name__ doesn't exist: %r" % (type(obj),)))
if (module is False):
module = None
elif (module is None)... |
'Return true if the given object is defined in the given
module.'
| def _from_module(self, module, object):
| if (module is None):
return True
elif (inspect.getmodule(object) is not None):
return (module is inspect.getmodule(object))
elif inspect.isfunction(object):
return (module.__dict__ is object.__globals__)
elif inspect.ismethoddescriptor(object):
if hasattr(object, '__objcl... |
'Find tests for the given object and any contained objects, and
add them to `tests`.'
| def _find(self, tests, obj, name, module, source_lines, globs, seen):
| if self._verbose:
print ('Finding tests in %s' % name)
if (id(obj) in seen):
return
seen[id(obj)] = 1
test = self._get_test(obj, name, module, globs, source_lines)
if (test is not None):
tests.append(test)
if (inspect.ismodule(obj) and self._recurse):
for... |
'Return a DocTest for the given object, if it defines a docstring;
otherwise, return None.'
| def _get_test(self, obj, name, module, globs, source_lines):
| if isinstance(obj, str):
docstring = obj
else:
try:
if (obj.__doc__ is None):
docstring = ''
else:
docstring = obj.__doc__
if (not isinstance(docstring, str)):
docstring = str(docstring)
except (T... |
'Return a line number of the given object\'s docstring. Note:
this method assumes that the object has a docstring.'
| def _find_lineno(self, obj, source_lines):
| lineno = None
if inspect.ismodule(obj):
lineno = 0
if inspect.isclass(obj):
if (source_lines is None):
return None
pat = re.compile(('^\\s*class\\s*%s\\b' % getattr(obj, '__name__', '-')))
for (i, line) in enumerate(source_lines):
if pat.match(line):
... |
'Create a new test runner.
Optional keyword arg `checker` is the `OutputChecker` that
should be used to compare the expected outputs and actual
outputs of doctest examples.
Optional keyword arg \'verbose\' prints lots of stuff if true,
only failures if false; by default, it\'s true iff \'-v\' is in
sys.argv.
Optional a... | def __init__(self, checker=None, verbose=None, optionflags=0):
| self._checker = (checker or OutputChecker())
if (verbose is None):
verbose = ('-v' in sys.argv)
self._verbose = verbose
self.optionflags = optionflags
self.original_optionflags = optionflags
self.tries = 0
self.failures = 0
self._name2ft = {}
self._fakeout = _SpoofOut()
|
'Report that the test runner is about to process the given
example. (Only displays a message if verbose=True)'
| def report_start(self, out, test, example):
| if self._verbose:
if example.want:
out(((('Trying:\n' + _indent(example.source)) + 'Expecting:\n') + _indent(example.want)))
else:
out((('Trying:\n' + _indent(example.source)) + 'Expecting nothing\n'))
|
'Report that the given example ran successfully. (Only
displays a message if verbose=True)'
| def report_success(self, out, test, example, got):
| if self._verbose:
out('ok\n')
|
'Report that the given example failed.'
| def report_failure(self, out, test, example, got):
| out((self._failure_header(test, example) + self._checker.output_difference(example, got, self.optionflags)))
|
'Report that the given example raised an unexpected exception.'
| def report_unexpected_exception(self, out, test, example, exc_info):
| out(((self._failure_header(test, example) + 'Exception raised:\n') + _indent(_exception_traceback(exc_info))))
|
'Run the examples in `test`. Write the outcome of each example
with one of the `DocTestRunner.report_*` methods, using the
writer function `out`. `compileflags` is the set of compiler
flags that should be used to execute examples. Return a tuple
`(f, t)`, where `t` is the number of examples tried, and `f`
is the num... | def __run(self, test, compileflags, out):
| failures = tries = 0
original_optionflags = self.optionflags
(SUCCESS, FAILURE, BOOM) = range(3)
check = self._checker.check_output
for (examplenum, example) in enumerate(test.examples):
quiet = ((self.optionflags & REPORT_ONLY_FIRST_FAILURE) and (failures > 0))
self.optionflags = or... |
'Record the fact that the given DocTest (`test`) generated `f`
failures out of `t` tried examples.'
| def __record_outcome(self, test, f, t):
| (f2, t2) = self._name2ft.get(test.name, (0, 0))
self._name2ft[test.name] = ((f + f2), (t + t2))
self.failures += f
self.tries += t
|
'Run the examples in `test`, and display the results using the
writer function `out`.
The examples are run in the namespace `test.globs`. If
`clear_globs` is true (the default), then this namespace will
be cleared after the test runs, to help with garbage
collection. If you would like to examine the namespace after
t... | def run(self, test, compileflags=None, out=None, clear_globs=True):
| self.test = test
if (compileflags is None):
compileflags = _extract_future_flags(test.globs)
save_stdout = sys.stdout
if (out is None):
encoding = save_stdout.encoding
if ((encoding is None) or (encoding.lower() == 'utf-8')):
out = save_stdout.write
else:
... |
'Print a summary of all the test cases that have been run by
this DocTestRunner, and return a tuple `(f, t)`, where `f` is
the total number of failed examples, and `t` is the total
number of tried examples.
The optional `verbose` argument controls how detailed the
summary is. If the verbosity is not specified, then th... | def summarize(self, verbose=None):
| if (verbose is None):
verbose = self._verbose
notests = []
passed = []
failed = []
totalt = totalf = 0
for x in self._name2ft.items():
(name, (f, t)) = x
assert (f <= t)
totalt += t
totalf += f
if (t == 0):
notests.append(name)
... |
'Convert string to hex-escaped ASCII string.'
| def _toAscii(self, s):
| return str(s.encode('ASCII', 'backslashreplace'), 'ASCII')
|
'Return True iff the actual output from an example (`got`)
matches the expected output (`want`). These strings are
always considered to match if they are identical; but
depending on what option flags the test runner is using,
several non-exact match types are also possible. See the
documentation for `TestRunner` for ... | def check_output(self, want, got, optionflags):
| got = self._toAscii(got)
want = self._toAscii(want)
if (got == want):
return True
if (not (optionflags & DONT_ACCEPT_TRUE_FOR_1)):
if ((got, want) == ('True\n', '1\n')):
return True
if ((got, want) == ('False\n', '0\n')):
return True
if (not (optionfla... |
'Return a string describing the differences between the
expected output for a given example (`example`) and the actual
output (`got`). `optionflags` is the set of option flags used
to compare `want` and `got`.'
| def output_difference(self, example, got, optionflags):
| want = example.want
if (not (optionflags & DONT_ACCEPT_BLANKLINE)):
got = re.sub('(?m)^[ ]*(?=\n)', BLANKLINE_MARKER, got)
if self._do_a_fancy_diff(want, got, optionflags):
want_lines = want.splitlines(keepends=True)
got_lines = got.splitlines(keepends=True)
if (optionflag... |
'Run the test case without results and without catching exceptions
The unit test framework includes a debug method on test cases
and test suites to support post-mortem debugging. The test code
is run in such a way that errors are not caught. This way a
caller can catch the errors and initiate post-mortem debugging.
T... | def debug(self):
| self.setUp()
runner = DebugRunner(optionflags=self._dt_optionflags, checker=self._dt_checker, verbose=False)
runner.run(self._dt_test, clear_globs=False)
self.tearDown()
|
'val -> _TestClass object with associated value val.
>>> t = _TestClass(123)
>>> print(t.get())
123'
| def __init__(self, val):
| self.val = val
|
'square() -> square TestClass\'s associated value
>>> _TestClass(13).square().get()
169'
| def square(self):
| self.val = (self.val ** 2)
return self
|
'get() -> return TestClass\'s associated value.
>>> x = _TestClass(-42)
>>> print(x.get())
-42'
| def get(self):
| return self.val
|
'Dummy implementation of acquire().
For blocking calls, self.locked_status is automatically set to
True and returned appropriately based on value of
``waitflag``. If it is non-blocking, then the value is
actually checked and not set if it is already acquired. This
is all done so that threading.Condition\'s assert sta... | def acquire(self, waitflag=None, timeout=(-1)):
| if ((waitflag is None) or waitflag):
self.locked_status = True
return True
elif (not self.locked_status):
self.locked_status = True
return True
else:
if (timeout > 0):
import time
time.sleep(timeout)
return False
|
'Release the dummy lock.'
| def release(self):
| if (not self.locked_status):
raise error
self.locked_status = False
return True
|
'Builds a qualified name from a (ns_url, localname) pair'
| def _qname(self, name):
| if name[0]:
if ('http://www.w3.org/XML/1998/namespace' == name[0]):
return ('xml:' + name[1])
prefix = self._current_context[name[0]]
if prefix:
return ((prefix + ':') + name[1])
return name[1]
|
'Parse an XML document from a URL or an InputSource.'
| def parse(self, source):
| source = saxutils.prepare_input_source(source)
self._source = source
self.reset()
self._cont_handler.setDocumentLocator(ExpatLocator(self))
xmlreader.IncrementalParser.parse(self, source)
|
'Creates an exception. The message is required, but the exception
is optional.'
| def __init__(self, msg, exception=None):
| self._msg = msg
self._exception = exception
Exception.__init__(self, msg)
|
'Return a message for this exception.'
| def getMessage(self):
| return self._msg
|
'Return the embedded exception, or None if there was none.'
| def getException(self):
| return self._exception
|
'Create a string representation of the exception.'
| def __str__(self):
| return self._msg
|
'Avoids weird error messages if someone does exception[ix] by
mistake, since Exception has __getitem__ defined.'
| def __getitem__(self, ix):
| raise AttributeError('__getitem__')
|
'Creates the exception. The exception parameter is allowed to be None.'
| def __init__(self, msg, exception, locator):
| SAXException.__init__(self, msg, exception)
self._locator = locator
self._systemId = self._locator.getSystemId()
self._colnum = self._locator.getColumnNumber()
self._linenum = self._locator.getLineNumber()
|
'The column number of the end of the text where the exception
occurred.'
| def getColumnNumber(self):
| return self._colnum
|
'The line number of the end of the text where the exception occurred.'
| def getLineNumber(self):
| return self._linenum
|
'Get the public identifier of the entity where the exception occurred.'
| def getPublicId(self):
| return self._locator.getPublicId()
|
'Get the system identifier of the entity where the exception occurred.'
| def getSystemId(self):
| return self._systemId
|
'Create a string representation of the exception.'
| def __str__(self):
| sysid = self.getSystemId()
if (sysid is None):
sysid = '<unknown>'
linenum = self.getLineNumber()
if (linenum is None):
linenum = '?'
colnum = self.getColumnNumber()
if (colnum is None):
colnum = '?'
return ('%s:%s:%s: %s' % (sysid, linenum, colnum, self._msg))
|
'Parse an XML document from a system identifier or an InputSource.'
| def parse(self, source):
| raise NotImplementedError('This method must be implemented!')
|
'Returns the current ContentHandler.'
| def getContentHandler(self):
| return self._cont_handler
|
'Registers a new object to receive document content events.'
| def setContentHandler(self, handler):
| self._cont_handler = handler
|
'Returns the current DTD handler.'
| def getDTDHandler(self):
| return self._dtd_handler
|
'Register an object to receive basic DTD-related events.'
| def setDTDHandler(self, handler):
| self._dtd_handler = handler
|
'Returns the current EntityResolver.'
| def getEntityResolver(self):
| return self._ent_handler
|
'Register an object to resolve external entities.'
| def setEntityResolver(self, resolver):
| self._ent_handler = resolver
|
'Returns the current ErrorHandler.'
| def getErrorHandler(self):
| return self._err_handler
|
'Register an object to receive error-message events.'
| def setErrorHandler(self, handler):
| self._err_handler = handler
|
'Allow an application to set the locale for errors and warnings.
SAX parsers are not required to provide localization for errors
and warnings; if they cannot support the requested locale,
however, they must raise a SAX exception. Applications may
request a locale change in the middle of a parse.'
| def setLocale(self, locale):
| raise SAXNotSupportedException('Locale support not implemented')
|
'Looks up and returns the state of a SAX2 feature.'
| def getFeature(self, name):
| raise SAXNotRecognizedException(("Feature '%s' not recognized" % name))
|
'Sets the state of a SAX2 feature.'
| def setFeature(self, name, state):
| raise SAXNotRecognizedException(("Feature '%s' not recognized" % name))
|
'Looks up and returns the value of a SAX2 property.'
| def getProperty(self, name):
| raise SAXNotRecognizedException(("Property '%s' not recognized" % name))
|
'Sets the value of a SAX2 property.'
| def setProperty(self, name, value):
| raise SAXNotRecognizedException(("Property '%s' not recognized" % name))
|
'This method gives the raw XML data in the data parameter to
the parser and makes it parse the data, emitting the
corresponding events. It is allowed for XML constructs to be
split across several calls to feed.
feed may raise SAXException.'
| def feed(self, data):
| raise NotImplementedError('This method must be implemented!')
|
'This method is called by the parse implementation to allow
the SAX 2.0 driver to prepare itself for parsing.'
| def prepareParser(self, source):
| raise NotImplementedError('prepareParser must be overridden!')
|
'This method is called when the entire XML document has been
passed to the parser through the feed method, to notify the
parser that there are no more data. This allows the parser to
do the final checks on the document and empty the internal
data buffer.
The parser will not be ready to parse another document until
the ... | def close(self):
| raise NotImplementedError('This method must be implemented!')
|
'This method is called after close has been called to reset
the parser so that it is ready to parse new documents. The
results of calling parse or feed after close without calling
reset are undefined.'
| def reset(self):
| raise NotImplementedError('This method must be implemented!')
|
'Return the column number where the current event ends.'
| def getColumnNumber(self):
| return (-1)
|
'Return the line number where the current event ends.'
| def getLineNumber(self):
| return (-1)
|
'Return the public identifier for the current event.'
| def getPublicId(self):
| return None
|
'Return the system identifier for the current event.'
| def getSystemId(self):
| return None
|
'Sets the public identifier of this InputSource.'
| def setPublicId(self, public_id):
| self.__public_id = public_id
|
'Returns the public identifier of this InputSource.'
| def getPublicId(self):
| return self.__public_id
|
'Sets the system identifier of this InputSource.'
| def setSystemId(self, system_id):
| self.__system_id = system_id
|
'Returns the system identifier of this InputSource.'
| def getSystemId(self):
| return self.__system_id
|
'Sets the character encoding of this InputSource.
The encoding must be a string acceptable for an XML encoding
declaration (see section 4.3.3 of the XML recommendation).
The encoding attribute of the InputSource is ignored if the
InputSource also contains a character stream.'
| def setEncoding(self, encoding):
| self.__encoding = encoding
|
'Get the character encoding of this InputSource.'
| def getEncoding(self):
| return self.__encoding
|
'Set the byte stream (a Python file-like object which does
not perform byte-to-character conversion) for this input
source.
The SAX parser will ignore this if there is also a character
stream specified, but it will use a byte stream in preference
to opening a URI connection itself.
If the application knows the characte... | def setByteStream(self, bytefile):
| self.__bytefile = bytefile
|
'Get the byte stream for this input source.
The getEncoding method will return the character encoding for
this byte stream, or None if unknown.'
| def getByteStream(self):
| return self.__bytefile
|
'Set the character stream for this input source. (The stream
must be a Python 2.0 Unicode-wrapped file-like that performs
conversion to Unicode strings.)
If there is a character stream specified, the SAX parser will
ignore any byte stream and will not attempt to open a URI
connection to the system identifier.'
| def setCharacterStream(self, charfile):
| self.__charfile = charfile
|
'Get the character stream for this input source.'
| def getCharacterStream(self):
| return self.__charfile
|
'Non-NS-aware implementation.
attrs should be of the form {name : value}.'
| def __init__(self, attrs):
| self._attrs = attrs
|
'NS-aware implementation.
attrs should be of the form {(ns_uri, lname): value, ...}.
qnames of the form {(ns_uri, lname): qname, ...}.'
| def __init__(self, attrs, qnames):
| self._attrs = attrs
self._qnames = qnames
|
'Handle a recoverable error.'
| def error(self, exception):
| raise exception
|
'Handle a non-recoverable error.'
| def fatalError(self, exception):
| raise exception
|
'Handle a warning.'
| def warning(self, exception):
| print exception
|
'Called by the parser to give the application a locator for
locating the origin of document events.
SAX parsers are strongly encouraged (though not absolutely
required) to supply a locator: if it does so, it must supply
the locator to the application by invoking this method before
invoking any of the other methods in t... | def setDocumentLocator(self, locator):
| self._locator = locator
|
'Resolve the system identifier of an entity and return either
the system identifier to read from as a string, or an InputSource
to read from.'
| def resolveEntity(self, publicId, systemId):
| return systemId
|
'Create a new parser object.'
| def createParser(self):
| return expat.ParserCreate()
|
'Return the parser object, creating a new one if needed.'
| def getParser(self):
| if (not self._parser):
self._parser = self.createParser()
self._intern_setdefault = self._parser.intern.setdefault
self._parser.buffer_text = True
self._parser.ordered_attributes = True
self._parser.specified_attributes = True
self.install(self._parser)
return sel... |
'Free all data structures used during DOM construction.'
| def reset(self):
| self.document = theDOMImplementation.createDocument(EMPTY_NAMESPACE, None, None)
self.curNode = self.document
self._elem_info = self.document._elem_info
self._cdata = False
|
'Install the callbacks needed to build the DOM into the parser.'
| def install(self, parser):
| parser.StartDoctypeDeclHandler = self.start_doctype_decl_handler
parser.StartElementHandler = self.first_element_handler
parser.EndElementHandler = self.end_element_handler
parser.ProcessingInstructionHandler = self.pi_handler
if self._options.entities:
parser.EntityDeclHandler = self.entity... |
'Parse a document from a file object, returning the document
node.'
| def parseFile(self, file):
| parser = self.getParser()
first_buffer = True
try:
while 1:
buffer = file.read((16 * 1024))
if (not buffer):
break
parser.Parse(buffer, 0)
if (first_buffer and self.document.documentElement):
self._setup_subset(buffer)
... |
'Parse a document from a string, returning the document node.'
| def parseString(self, string):
| parser = self.getParser()
try:
parser.Parse(string, True)
self._setup_subset(string)
except ParseEscape:
pass
doc = self.document
self.reset()
self._parser = None
return doc
|
'Load the internal subset if there might be one.'
| def _setup_subset(self, buffer):
| if self.document.doctype:
extractor = InternalSubsetExtractor()
extractor.parseString(buffer)
subset = extractor.getSubset()
self.document.doctype.internalSubset = subset
|
'Parse a document fragment from a file object, returning the
fragment node.'
| def parseFile(self, file):
| return self.parseString(file.read())
|
'Parse a document fragment from a string, returning the
fragment node.'
| def parseString(self, string):
| self._source = string
parser = self.getParser()
doctype = self.originalDocument.doctype
ident = ''
if doctype:
subset = (doctype.internalSubset or self._getDeclarations())
if doctype.publicId:
ident = ('PUBLIC "%s" "%s"' % (doctype.publicId, doctype.systemId))
... |
'Re-create the internal subset from the DocumentType node.
This is only needed if we don\'t already have the
internalSubset as a string.'
| def _getDeclarations(self):
| doctype = self.context.ownerDocument.doctype
s = ''
if doctype:
for i in range(doctype.notations.length):
notation = doctype.notations.item(i)
if s:
s = (s + '\n ')
s = ('%s<!NOTATION %s' % (s, notation.nodeName))
if notation.... |
'Create a new namespace-handling parser.'
| def createParser(self):
| parser = expat.ParserCreate(namespace_separator=' ')
parser.namespace_prefixes = True
return parser
|
'Insert the namespace-handlers onto the parser.'
| def install(self, parser):
| ExpatBuilder.install(self, parser)
if self._options.namespace_declarations:
parser.StartNamespaceDeclHandler = self.start_namespace_decl_handler
|
'Push this namespace declaration on our storage.'
| def start_namespace_decl_handler(self, prefix, uri):
| self._ns_ordered_prefixes.append((prefix, uri))
|
'Return string of namespace attributes from this element and
ancestors.'
| def _getNSattrs(self):
| attrs = ''
context = self.context
L = []
while context:
if hasattr(context, '_ns_prefix_uri'):
for (prefix, uri) in context._ns_prefix_uri.items():
if (prefix in L):
continue
L.append(prefix)
if prefix:
... |
'Return the internal subset as a string.'
| def getSubset(self):
| return self.subset
|
'clear(): Explicitly release parsing structures'
| def clear(self):
| self.document = None
|
'Fallback replacement for getEvent() using the
standard SAX2 interface, which means we slurp the
SAX events into memory (no performance gain, but
we are compatible to all SAX parsers).'
| def _slurp(self):
| self.parser.parse(self.stream)
self.getEvent = self._emit
return self._emit()
|
'Fallback replacement for getEvent() that emits
the events that _slurp() read previously.'
| def _emit(self):
| rc = self.pulldom.firstEvent[1][0]
self.pulldom.firstEvent[1] = self.pulldom.firstEvent[1][1]
return rc
|
'clear(): Explicitly release parsing objects'
| def clear(self):
| self.pulldom.clear()
del self.pulldom
self.parser = None
self.stream = None
|
'Returns true iff this element is declared to have an EMPTY
content model.'
| def isEmpty(self):
| return False
|
'Returns true iff the named attribute is a DTD-style ID.'
| def isId(self, aname):
| return False
|
'Returns true iff the identified attribute is a DTD-style ID.'
| def isIdNS(self, namespaceURI, localName):
| return False
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.