desc stringlengths 3 26.7k | decl stringlengths 11 7.89k | bodies stringlengths 8 553k |
|---|---|---|
'Test combination of path fixing and windows name sanitization.'
| @unittest.skipIf((os.path.sep != '\\'), 'Requires \\ as path separator.')
def test_extract_hackers_arcnames_windows_only(self):
| windows_hacknames = [('..\\foo\\bar', 'foo/bar'), ('..\\/foo\\/bar', 'foo/bar'), ('foo/\\..\\/bar', 'foo/bar'), ('foo\\/../\\bar', 'foo/bar'), ('C:foo/bar', 'foo/bar'), ('C:/foo/bar', 'foo/bar'), ('C://foo/bar', 'foo/bar'), ('C:\\foo\\bar', 'foo/bar'), ('//conky/mountpoint/foo/bar', 'foo/bar'), ('\\\\conky\\mountpo... |
'Check that the zipfile is closed after the \'with\' block.'
| def test_close(self):
| with zipfile.ZipFile(TESTFN2, 'w') as zipfp:
for (fpath, fdata) in SMALL_TEST_DATA:
zipfp.writestr(fpath, fdata)
self.assertIsNotNone(zipfp.fp, 'zipfp is not open')
self.assertIsNone(zipfp.fp, 'zipfp is not closed')
with zipfile.ZipFile(TESTFN2, 'r') as zipf... |
'Check that the zipfile is closed if an exception is raised in the
\'with\' block.'
| def test_close_on_exception(self):
| with zipfile.ZipFile(TESTFN2, 'w') as zipfp:
for (fpath, fdata) in SMALL_TEST_DATA:
zipfp.writestr(fpath, fdata)
try:
with zipfile.ZipFile(TESTFN2, 'r') as zipfp2:
raise zipfile.BadZipFile()
except zipfile.BadZipFile:
self.assertIsNone(zipfp2.fp, 'zipfp is ... |
'Check that is_zipfile() correctly identifies non-zip files.'
| def test_is_zip_erroneous_file(self):
| with open(TESTFN, 'w') as fp:
fp.write('this is not a legal zip file\n')
self.assertFalse(zipfile.is_zipfile(TESTFN))
with open(TESTFN, 'rb') as fp:
self.assertFalse(zipfile.is_zipfile(fp))
fp = io.BytesIO()
fp.write('this is not a legal zip file\n... |
'Check that zipfiles with missing bytes at the end raise BadZipFile.'
| def test_damaged_zipfile(self):
| fp = io.BytesIO()
with zipfile.ZipFile(fp, mode='w') as zipf:
zipf.writestr('foo.txt', 'O, for a Muse of Fire!')
zipfiledata = fp.getvalue()
for N in range(len(zipfiledata)):
fp = io.BytesIO(zipfiledata[:N])
self.assertRaises(zipfile.BadZipFile, zipfile.ZipFile, fp... |
'Check that is_zipfile() correctly identifies zip files.'
| def test_is_zip_valid_file(self):
| with zipfile.ZipFile(TESTFN, mode='w') as zipf:
zipf.writestr('foo.txt', 'O, for a Muse of Fire!')
self.assertTrue(zipfile.is_zipfile(TESTFN))
with open(TESTFN, 'rb') as fp:
self.assertTrue(zipfile.is_zipfile(fp))
fp.seek(0, 0)
zip_contents = fp.read()
fp =... |
'Verify that testzip() doesn\'t swallow inappropriate exceptions.'
| def test_closed_zip_raises_RuntimeError(self):
| data = io.BytesIO()
with zipfile.ZipFile(data, mode='w') as zipf:
zipf.writestr('foo.txt', 'O, for a Muse of Fire!')
self.assertRaises(RuntimeError, zipf.read, 'foo.txt')
self.assertRaises(RuntimeError, zipf.open, 'foo.txt')
self.assertRaises(RuntimeError, zipf.testzip)
se... |
'Check that bad modes passed to ZipFile constructor are caught.'
| def test_bad_constructor_mode(self):
| self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, 'q')
|
'Check that bad modes passed to ZipFile.open are caught.'
| def test_bad_open_mode(self):
| with zipfile.ZipFile(TESTFN, mode='w') as zipf:
zipf.writestr('foo.txt', 'O, for a Muse of Fire!')
with zipfile.ZipFile(TESTFN, mode='r') as zipf:
zipf.read('foo.txt')
self.assertRaises(RuntimeError, zipf.open, 'foo.txt', 'q')
|
'Check that calling read(0) on a ZipExtFile object returns an empty
string and doesn\'t advance file pointer.'
| def test_read0(self):
| with zipfile.ZipFile(TESTFN, mode='w') as zipf:
zipf.writestr('foo.txt', 'O, for a Muse of Fire!')
with zipf.open('foo.txt') as f:
for i in range(FIXEDTEST_SIZE):
self.assertEqual(f.read(0), '')
self.assertEqual(f.read(), 'O, for a Muse... |
'Check that attempting to call open() for an item that doesn\'t
exist in the archive raises a RuntimeError.'
| def test_open_non_existent_item(self):
| with zipfile.ZipFile(TESTFN, mode='w') as zipf:
self.assertRaises(KeyError, zipf.open, 'foo.txt', 'r')
|
'Check that bad compression methods passed to ZipFile.open are
caught.'
| def test_bad_compression_mode(self):
| self.assertRaises(RuntimeError, zipfile.ZipFile, TESTFN, 'w', (-1))
|
'Check that a filename containing a null byte is properly
terminated.'
| def test_null_byte_in_filename(self):
| with zipfile.ZipFile(TESTFN, mode='w') as zipf:
zipf.writestr('foo.txt\x00qqq', 'O, for a Muse of Fire!')
self.assertEqual(zipf.namelist(), ['foo.txt'])
|
'Check that ZIP internal structure sizes are calculated correctly.'
| def test_struct_sizes(self):
| self.assertEqual(zipfile.sizeEndCentDir, 22)
self.assertEqual(zipfile.sizeCentralDir, 46)
self.assertEqual(zipfile.sizeEndCentDir64, 56)
self.assertEqual(zipfile.sizeEndCentDir64Locator, 20)
|
'Check that comments on the archive are handled properly.'
| def test_comments(self):
| with zipfile.ZipFile(TESTFN, mode='w') as zipf:
self.assertEqual(zipf.comment, '')
zipf.writestr('foo.txt', 'O, for a Muse of Fire!')
with zipfile.ZipFile(TESTFN, mode='r') as zipfr:
self.assertEqual(zipfr.comment, '')
comment = 'Bravely taking to his feet,... |
'If an extra field in the header is less than 4 bytes, skip it.'
| def test_zipfile_with_short_extra_field(self):
| zipdata = 'PK\x03\x04\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x03\x00abc\x00\x00\x00APK\x01\x02\x14\x03\x14\x00\x00\x00\x00\x00\x93\x9b\xad@\x8b\x9e\xd9\xd3\x01\x00\x00\x00\x01\x00\x00\x00\x03\x00\x02\x00\x00\x00\x00\x00\x00\x00\x00\x00\xa4\x81\x00\x00\x00\x00abc... |
'Tests that files with bad CRCs return their name from testzip.'
| def test_testzip_with_bad_crc(self):
| zipdata = self.zip_with_bad_crc
with zipfile.ZipFile(io.BytesIO(zipdata), mode='r') as zipf:
self.assertEqual('afile', zipf.testzip())
|
'Tests that files with bad CRCs raise a BadZipFile exception when read.'
| def test_read_with_bad_crc(self):
| zipdata = self.zip_with_bad_crc
with zipfile.ZipFile(io.BytesIO(zipdata), mode='r') as zipf:
self.assertRaises(zipfile.BadZipFile, zipf.read, 'afile')
with zipfile.ZipFile(io.BytesIO(zipdata), mode='r') as zipf:
with zipf.open('afile', 'r') as corrupt_file:
self.assertRaises(zipf... |
'A context manager to use around all finalization tests.'
| @classmethod
@contextlib.contextmanager
def test(cls):
| with support.disable_gc():
cls.del_calls.clear()
cls.tp_del_calls.clear()
NonGCSimpleBase._cleaning = False
try:
(yield)
if cls.errors:
raise cls.errors[0]
finally:
NonGCSimpleBase._cleaning = True
cls._cleanup()... |
'PEP 442 finalizer. Record that this was called, check the
object is in a sane state, and invoke a side effect.'
| def __del__(self):
| try:
if (not self._cleaning):
self.del_calls.append(id(self))
self.check_sanity()
self.side_effect()
except Exception as e:
self.errors.append(e)
|
'Resurrect self by storing self in a class-wide list.'
| def side_effect(self):
| self.survivors.append(self)
|
'Explicitly break the reference cycle.'
| def side_effect(self):
| self.ref = None
|
'Explicitly break the reference cycle.'
| def side_effect(self):
| self.suicided = True
self.left = None
self.right = None
|
'Legacy (pre-PEP 442) finalizer, mapped to a tp_del slot.'
| def __tp_del__(self):
| try:
if (not self._cleaning):
self.tp_del_calls.append(id(self))
self.check_sanity()
self.side_effect()
except Exception as e:
self.errors.append(e)
|
'Resurrect self by storing self in a class-wide list.'
| def side_effect(self):
| self.survivors.append(self)
|
'Create a new DocTest containing the given examples. The
DocTest\'s globals are initialized with a copy of `globs`.'
| def __init__(self, examples, globs, name, filename, lineno, docstring):
| assert (not isinstance(examples, str)), 'DocTest no longer accepts str; use DocTestParser instead'
self.examples = examples
self.docstring = docstring
self.globs = globs.copy()
self.name = name
self.filename = filename
self.lineno = lineno
|
'Divide the given string into examples and intervening text,
and return them as a list of alternating Examples and strings.
Line numbers for the Examples are 0-based. The optional
argument `name` is a name identifying this string, and is only
used for error messages.'
| def parse(self, string, name='<string>'):
| string = string.expandtabs()
min_indent = self._min_indent(string)
if (min_indent > 0):
string = '\n'.join([l[min_indent:] for l in string.split('\n')])
output = []
(charno, lineno) = (0, 0)
for m in self._EXAMPLE_RE.finditer(string):
output.append(string[charno:m.start()])
... |
'Extract all doctest examples from the given string, and
collect them into a `DocTest` object.
`globs`, `name`, `filename`, and `lineno` are attributes for
the new `DocTest` object. See the documentation for `DocTest`
for more information.'
| def get_doctest(self, string, globs, name, filename, lineno):
| return DocTest(self.get_examples(string, name), globs, name, filename, lineno, string)
|
'Extract all doctest examples from the given string, and return
them as a list of `Example` objects. Line numbers are
0-based, because it\'s most common in doctests that nothing
interesting appears on the same line as opening triple-quote,
and so the first interesting line is called "line 1" then.
The optional argumen... | def get_examples(self, string, name='<string>'):
| return [x for x in self.parse(string, name) if isinstance(x, Example)]
|
'Given a regular expression match from `_EXAMPLE_RE` (`m`),
return a pair `(source, want)`, where `source` is the matched
example\'s source code (with prompts and indentation stripped);
and `want` is the example\'s expected output (with indentation
stripped).
`name` is the string\'s name, and `lineno` is the line numbe... | def _parse_example(self, m, name, lineno):
| indent = len(m.group('indent'))
source_lines = m.group('source').split('\n')
self._check_prompt_blank(source_lines, indent, name, lineno)
self._check_prefix(source_lines[1:], ((' ' * indent) + '.'), name, lineno)
source = '\n'.join([sl[(indent + 4):] for sl in source_lines])
want = m.group('w... |
'Return a dictionary containing option overrides extracted from
option directives in the given source string.
`name` is the string\'s name, and `lineno` is the line number
where the example starts; both are used for error messages.'
| def _find_options(self, source, name, lineno):
| options = {}
for m in self._OPTION_DIRECTIVE_RE.finditer(source):
option_strings = m.group(1).replace(',', ' ').split()
for option in option_strings:
if ((option[0] not in '+-') or (option[1:] not in OPTIONFLAGS_BY_NAME)):
raise ValueError(('line %r of the... |
'Return the minimum indentation of any non-blank line in `s`'
| def _min_indent(self, s):
| indents = [len(indent) for indent in self._INDENT_RE.findall(s)]
if (len(indents) > 0):
return min(indents)
else:
return 0
|
'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
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.