Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/ExeBy/smexe_ro.../lib64/python2....
File: doctest.py
# Module doctest.
[0] Fix | Delete
# Released to the public domain 16-Jan-2001, by Tim Peters (tim@python.org).
[1] Fix | Delete
# Major enhancements and refactoring by:
[2] Fix | Delete
# Jim Fulton
[3] Fix | Delete
# Edward Loper
[4] Fix | Delete
[5] Fix | Delete
# Provided as-is; use at your own risk; no warranty; no promises; enjoy!
[6] Fix | Delete
[7] Fix | Delete
r"""Module doctest -- a framework for running examples in docstrings.
[8] Fix | Delete
[9] Fix | Delete
In simplest use, end each module M to be tested with:
[10] Fix | Delete
[11] Fix | Delete
def _test():
[12] Fix | Delete
import doctest
[13] Fix | Delete
doctest.testmod()
[14] Fix | Delete
[15] Fix | Delete
if __name__ == "__main__":
[16] Fix | Delete
_test()
[17] Fix | Delete
[18] Fix | Delete
Then running the module as a script will cause the examples in the
[19] Fix | Delete
docstrings to get executed and verified:
[20] Fix | Delete
[21] Fix | Delete
python M.py
[22] Fix | Delete
[23] Fix | Delete
This won't display anything unless an example fails, in which case the
[24] Fix | Delete
failing example(s) and the cause(s) of the failure(s) are printed to stdout
[25] Fix | Delete
(why not stderr? because stderr is a lame hack <0.2 wink>), and the final
[26] Fix | Delete
line of output is "Test failed.".
[27] Fix | Delete
[28] Fix | Delete
Run it with the -v switch instead:
[29] Fix | Delete
[30] Fix | Delete
python M.py -v
[31] Fix | Delete
[32] Fix | Delete
and a detailed report of all examples tried is printed to stdout, along
[33] Fix | Delete
with assorted summaries at the end.
[34] Fix | Delete
[35] Fix | Delete
You can force verbose mode by passing "verbose=True" to testmod, or prohibit
[36] Fix | Delete
it by passing "verbose=False". In either of those cases, sys.argv is not
[37] Fix | Delete
examined by testmod.
[38] Fix | Delete
[39] Fix | Delete
There are a variety of other ways to run doctests, including integration
[40] Fix | Delete
with the unittest framework, and support for running non-Python text
[41] Fix | Delete
files containing doctests. There are also many ways to override parts
[42] Fix | Delete
of doctest's default behaviors. See the Library Reference Manual for
[43] Fix | Delete
details.
[44] Fix | Delete
"""
[45] Fix | Delete
[46] Fix | Delete
__docformat__ = 'reStructuredText en'
[47] Fix | Delete
[48] Fix | Delete
__all__ = [
[49] Fix | Delete
# 0, Option Flags
[50] Fix | Delete
'register_optionflag',
[51] Fix | Delete
'DONT_ACCEPT_TRUE_FOR_1',
[52] Fix | Delete
'DONT_ACCEPT_BLANKLINE',
[53] Fix | Delete
'NORMALIZE_WHITESPACE',
[54] Fix | Delete
'ELLIPSIS',
[55] Fix | Delete
'SKIP',
[56] Fix | Delete
'IGNORE_EXCEPTION_DETAIL',
[57] Fix | Delete
'COMPARISON_FLAGS',
[58] Fix | Delete
'REPORT_UDIFF',
[59] Fix | Delete
'REPORT_CDIFF',
[60] Fix | Delete
'REPORT_NDIFF',
[61] Fix | Delete
'REPORT_ONLY_FIRST_FAILURE',
[62] Fix | Delete
'REPORTING_FLAGS',
[63] Fix | Delete
# 1. Utility Functions
[64] Fix | Delete
# 2. Example & DocTest
[65] Fix | Delete
'Example',
[66] Fix | Delete
'DocTest',
[67] Fix | Delete
# 3. Doctest Parser
[68] Fix | Delete
'DocTestParser',
[69] Fix | Delete
# 4. Doctest Finder
[70] Fix | Delete
'DocTestFinder',
[71] Fix | Delete
# 5. Doctest Runner
[72] Fix | Delete
'DocTestRunner',
[73] Fix | Delete
'OutputChecker',
[74] Fix | Delete
'DocTestFailure',
[75] Fix | Delete
'UnexpectedException',
[76] Fix | Delete
'DebugRunner',
[77] Fix | Delete
# 6. Test Functions
[78] Fix | Delete
'testmod',
[79] Fix | Delete
'testfile',
[80] Fix | Delete
'run_docstring_examples',
[81] Fix | Delete
# 7. Tester
[82] Fix | Delete
'Tester',
[83] Fix | Delete
# 8. Unittest Support
[84] Fix | Delete
'DocTestSuite',
[85] Fix | Delete
'DocFileSuite',
[86] Fix | Delete
'set_unittest_reportflags',
[87] Fix | Delete
# 9. Debugging Support
[88] Fix | Delete
'script_from_examples',
[89] Fix | Delete
'testsource',
[90] Fix | Delete
'debug_src',
[91] Fix | Delete
'debug',
[92] Fix | Delete
]
[93] Fix | Delete
[94] Fix | Delete
import __future__
[95] Fix | Delete
[96] Fix | Delete
import sys, traceback, inspect, linecache, os, re
[97] Fix | Delete
import unittest, difflib, pdb, tempfile
[98] Fix | Delete
import warnings
[99] Fix | Delete
from StringIO import StringIO
[100] Fix | Delete
from collections import namedtuple
[101] Fix | Delete
[102] Fix | Delete
TestResults = namedtuple('TestResults', 'failed attempted')
[103] Fix | Delete
[104] Fix | Delete
# There are 4 basic classes:
[105] Fix | Delete
# - Example: a <source, want> pair, plus an intra-docstring line number.
[106] Fix | Delete
# - DocTest: a collection of examples, parsed from a docstring, plus
[107] Fix | Delete
# info about where the docstring came from (name, filename, lineno).
[108] Fix | Delete
# - DocTestFinder: extracts DocTests from a given object's docstring and
[109] Fix | Delete
# its contained objects' docstrings.
[110] Fix | Delete
# - DocTestRunner: runs DocTest cases, and accumulates statistics.
[111] Fix | Delete
#
[112] Fix | Delete
# So the basic picture is:
[113] Fix | Delete
#
[114] Fix | Delete
# list of:
[115] Fix | Delete
# +------+ +---------+ +-------+
[116] Fix | Delete
# |object| --DocTestFinder-> | DocTest | --DocTestRunner-> |results|
[117] Fix | Delete
# +------+ +---------+ +-------+
[118] Fix | Delete
# | Example |
[119] Fix | Delete
# | ... |
[120] Fix | Delete
# | Example |
[121] Fix | Delete
# +---------+
[122] Fix | Delete
[123] Fix | Delete
# Option constants.
[124] Fix | Delete
[125] Fix | Delete
OPTIONFLAGS_BY_NAME = {}
[126] Fix | Delete
def register_optionflag(name):
[127] Fix | Delete
# Create a new flag unless `name` is already known.
[128] Fix | Delete
return OPTIONFLAGS_BY_NAME.setdefault(name, 1 << len(OPTIONFLAGS_BY_NAME))
[129] Fix | Delete
[130] Fix | Delete
DONT_ACCEPT_TRUE_FOR_1 = register_optionflag('DONT_ACCEPT_TRUE_FOR_1')
[131] Fix | Delete
DONT_ACCEPT_BLANKLINE = register_optionflag('DONT_ACCEPT_BLANKLINE')
[132] Fix | Delete
NORMALIZE_WHITESPACE = register_optionflag('NORMALIZE_WHITESPACE')
[133] Fix | Delete
ELLIPSIS = register_optionflag('ELLIPSIS')
[134] Fix | Delete
SKIP = register_optionflag('SKIP')
[135] Fix | Delete
IGNORE_EXCEPTION_DETAIL = register_optionflag('IGNORE_EXCEPTION_DETAIL')
[136] Fix | Delete
[137] Fix | Delete
COMPARISON_FLAGS = (DONT_ACCEPT_TRUE_FOR_1 |
[138] Fix | Delete
DONT_ACCEPT_BLANKLINE |
[139] Fix | Delete
NORMALIZE_WHITESPACE |
[140] Fix | Delete
ELLIPSIS |
[141] Fix | Delete
SKIP |
[142] Fix | Delete
IGNORE_EXCEPTION_DETAIL)
[143] Fix | Delete
[144] Fix | Delete
REPORT_UDIFF = register_optionflag('REPORT_UDIFF')
[145] Fix | Delete
REPORT_CDIFF = register_optionflag('REPORT_CDIFF')
[146] Fix | Delete
REPORT_NDIFF = register_optionflag('REPORT_NDIFF')
[147] Fix | Delete
REPORT_ONLY_FIRST_FAILURE = register_optionflag('REPORT_ONLY_FIRST_FAILURE')
[148] Fix | Delete
[149] Fix | Delete
REPORTING_FLAGS = (REPORT_UDIFF |
[150] Fix | Delete
REPORT_CDIFF |
[151] Fix | Delete
REPORT_NDIFF |
[152] Fix | Delete
REPORT_ONLY_FIRST_FAILURE)
[153] Fix | Delete
[154] Fix | Delete
# Special string markers for use in `want` strings:
[155] Fix | Delete
BLANKLINE_MARKER = '<BLANKLINE>'
[156] Fix | Delete
ELLIPSIS_MARKER = '...'
[157] Fix | Delete
[158] Fix | Delete
######################################################################
[159] Fix | Delete
## Table of Contents
[160] Fix | Delete
######################################################################
[161] Fix | Delete
# 1. Utility Functions
[162] Fix | Delete
# 2. Example & DocTest -- store test cases
[163] Fix | Delete
# 3. DocTest Parser -- extracts examples from strings
[164] Fix | Delete
# 4. DocTest Finder -- extracts test cases from objects
[165] Fix | Delete
# 5. DocTest Runner -- runs test cases
[166] Fix | Delete
# 6. Test Functions -- convenient wrappers for testing
[167] Fix | Delete
# 7. Tester Class -- for backwards compatibility
[168] Fix | Delete
# 8. Unittest Support
[169] Fix | Delete
# 9. Debugging Support
[170] Fix | Delete
# 10. Example Usage
[171] Fix | Delete
[172] Fix | Delete
######################################################################
[173] Fix | Delete
## 1. Utility Functions
[174] Fix | Delete
######################################################################
[175] Fix | Delete
[176] Fix | Delete
def _extract_future_flags(globs):
[177] Fix | Delete
"""
[178] Fix | Delete
Return the compiler-flags associated with the future features that
[179] Fix | Delete
have been imported into the given namespace (globs).
[180] Fix | Delete
"""
[181] Fix | Delete
flags = 0
[182] Fix | Delete
for fname in __future__.all_feature_names:
[183] Fix | Delete
feature = globs.get(fname, None)
[184] Fix | Delete
if feature is getattr(__future__, fname):
[185] Fix | Delete
flags |= feature.compiler_flag
[186] Fix | Delete
return flags
[187] Fix | Delete
[188] Fix | Delete
def _normalize_module(module, depth=2):
[189] Fix | Delete
"""
[190] Fix | Delete
Return the module specified by `module`. In particular:
[191] Fix | Delete
- If `module` is a module, then return module.
[192] Fix | Delete
- If `module` is a string, then import and return the
[193] Fix | Delete
module with that name.
[194] Fix | Delete
- If `module` is None, then return the calling module.
[195] Fix | Delete
The calling module is assumed to be the module of
[196] Fix | Delete
the stack frame at the given depth in the call stack.
[197] Fix | Delete
"""
[198] Fix | Delete
if inspect.ismodule(module):
[199] Fix | Delete
return module
[200] Fix | Delete
elif isinstance(module, (str, unicode)):
[201] Fix | Delete
return __import__(module, globals(), locals(), ["*"])
[202] Fix | Delete
elif module is None:
[203] Fix | Delete
return sys.modules[sys._getframe(depth).f_globals['__name__']]
[204] Fix | Delete
else:
[205] Fix | Delete
raise TypeError("Expected a module, string, or None")
[206] Fix | Delete
[207] Fix | Delete
def _load_testfile(filename, package, module_relative):
[208] Fix | Delete
if module_relative:
[209] Fix | Delete
package = _normalize_module(package, 3)
[210] Fix | Delete
filename = _module_relative_path(package, filename)
[211] Fix | Delete
if hasattr(package, '__loader__'):
[212] Fix | Delete
if hasattr(package.__loader__, 'get_data'):
[213] Fix | Delete
file_contents = package.__loader__.get_data(filename)
[214] Fix | Delete
# get_data() opens files as 'rb', so one must do the equivalent
[215] Fix | Delete
# conversion as universal newlines would do.
[216] Fix | Delete
return file_contents.replace(os.linesep, '\n'), filename
[217] Fix | Delete
with open(filename, 'U') as f:
[218] Fix | Delete
return f.read(), filename
[219] Fix | Delete
[220] Fix | Delete
# Use sys.stdout encoding for output.
[221] Fix | Delete
_encoding = getattr(sys.__stdout__, 'encoding', None) or 'utf-8'
[222] Fix | Delete
[223] Fix | Delete
def _indent(s, indent=4):
[224] Fix | Delete
"""
[225] Fix | Delete
Add the given number of space characters to the beginning of
[226] Fix | Delete
every non-blank line in `s`, and return the result.
[227] Fix | Delete
If the string `s` is Unicode, it is encoded using the stdout
[228] Fix | Delete
encoding and the `backslashreplace` error handler.
[229] Fix | Delete
"""
[230] Fix | Delete
if isinstance(s, unicode):
[231] Fix | Delete
s = s.encode(_encoding, 'backslashreplace')
[232] Fix | Delete
# This regexp matches the start of non-blank lines:
[233] Fix | Delete
return re.sub('(?m)^(?!$)', indent*' ', s)
[234] Fix | Delete
[235] Fix | Delete
def _exception_traceback(exc_info):
[236] Fix | Delete
"""
[237] Fix | Delete
Return a string containing a traceback message for the given
[238] Fix | Delete
exc_info tuple (as returned by sys.exc_info()).
[239] Fix | Delete
"""
[240] Fix | Delete
# Get a traceback message.
[241] Fix | Delete
excout = StringIO()
[242] Fix | Delete
exc_type, exc_val, exc_tb = exc_info
[243] Fix | Delete
traceback.print_exception(exc_type, exc_val, exc_tb, file=excout)
[244] Fix | Delete
return excout.getvalue()
[245] Fix | Delete
[246] Fix | Delete
# Override some StringIO methods.
[247] Fix | Delete
class _SpoofOut(StringIO):
[248] Fix | Delete
def getvalue(self):
[249] Fix | Delete
result = StringIO.getvalue(self)
[250] Fix | Delete
# If anything at all was written, make sure there's a trailing
[251] Fix | Delete
# newline. There's no way for the expected output to indicate
[252] Fix | Delete
# that a trailing newline is missing.
[253] Fix | Delete
if result and not result.endswith("\n"):
[254] Fix | Delete
result += "\n"
[255] Fix | Delete
# Prevent softspace from screwing up the next test case, in
[256] Fix | Delete
# case they used print with a trailing comma in an example.
[257] Fix | Delete
if hasattr(self, "softspace"):
[258] Fix | Delete
del self.softspace
[259] Fix | Delete
return result
[260] Fix | Delete
[261] Fix | Delete
def truncate(self, size=None):
[262] Fix | Delete
StringIO.truncate(self, size)
[263] Fix | Delete
if hasattr(self, "softspace"):
[264] Fix | Delete
del self.softspace
[265] Fix | Delete
if not self.buf:
[266] Fix | Delete
# Reset it to an empty string, to make sure it's not unicode.
[267] Fix | Delete
self.buf = ''
[268] Fix | Delete
[269] Fix | Delete
# Worst-case linear-time ellipsis matching.
[270] Fix | Delete
def _ellipsis_match(want, got):
[271] Fix | Delete
"""
[272] Fix | Delete
Essentially the only subtle case:
[273] Fix | Delete
>>> _ellipsis_match('aa...aa', 'aaa')
[274] Fix | Delete
False
[275] Fix | Delete
"""
[276] Fix | Delete
if ELLIPSIS_MARKER not in want:
[277] Fix | Delete
return want == got
[278] Fix | Delete
[279] Fix | Delete
# Find "the real" strings.
[280] Fix | Delete
ws = want.split(ELLIPSIS_MARKER)
[281] Fix | Delete
assert len(ws) >= 2
[282] Fix | Delete
[283] Fix | Delete
# Deal with exact matches possibly needed at one or both ends.
[284] Fix | Delete
startpos, endpos = 0, len(got)
[285] Fix | Delete
w = ws[0]
[286] Fix | Delete
if w: # starts with exact match
[287] Fix | Delete
if got.startswith(w):
[288] Fix | Delete
startpos = len(w)
[289] Fix | Delete
del ws[0]
[290] Fix | Delete
else:
[291] Fix | Delete
return False
[292] Fix | Delete
w = ws[-1]
[293] Fix | Delete
if w: # ends with exact match
[294] Fix | Delete
if got.endswith(w):
[295] Fix | Delete
endpos -= len(w)
[296] Fix | Delete
del ws[-1]
[297] Fix | Delete
else:
[298] Fix | Delete
return False
[299] Fix | Delete
[300] Fix | Delete
if startpos > endpos:
[301] Fix | Delete
# Exact end matches required more characters than we have, as in
[302] Fix | Delete
# _ellipsis_match('aa...aa', 'aaa')
[303] Fix | Delete
return False
[304] Fix | Delete
[305] Fix | Delete
# For the rest, we only need to find the leftmost non-overlapping
[306] Fix | Delete
# match for each piece. If there's no overall match that way alone,
[307] Fix | Delete
# there's no overall match period.
[308] Fix | Delete
for w in ws:
[309] Fix | Delete
# w may be '' at times, if there are consecutive ellipses, or
[310] Fix | Delete
# due to an ellipsis at the start or end of `want`. That's OK.
[311] Fix | Delete
# Search for an empty string succeeds, and doesn't change startpos.
[312] Fix | Delete
startpos = got.find(w, startpos, endpos)
[313] Fix | Delete
if startpos < 0:
[314] Fix | Delete
return False
[315] Fix | Delete
startpos += len(w)
[316] Fix | Delete
[317] Fix | Delete
return True
[318] Fix | Delete
[319] Fix | Delete
def _comment_line(line):
[320] Fix | Delete
"Return a commented form of the given line"
[321] Fix | Delete
line = line.rstrip()
[322] Fix | Delete
if line:
[323] Fix | Delete
return '# '+line
[324] Fix | Delete
else:
[325] Fix | Delete
return '#'
[326] Fix | Delete
[327] Fix | Delete
def _strip_exception_details(msg):
[328] Fix | Delete
# Support for IGNORE_EXCEPTION_DETAIL.
[329] Fix | Delete
# Get rid of everything except the exception name; in particular, drop
[330] Fix | Delete
# the possibly dotted module path (if any) and the exception message (if
[331] Fix | Delete
# any). We assume that a colon is never part of a dotted name, or of an
[332] Fix | Delete
# exception name.
[333] Fix | Delete
# E.g., given
[334] Fix | Delete
# "foo.bar.MyError: la di da"
[335] Fix | Delete
# return "MyError"
[336] Fix | Delete
# Or for "abc.def" or "abc.def:\n" return "def".
[337] Fix | Delete
[338] Fix | Delete
start, end = 0, len(msg)
[339] Fix | Delete
# The exception name must appear on the first line.
[340] Fix | Delete
i = msg.find("\n")
[341] Fix | Delete
if i >= 0:
[342] Fix | Delete
end = i
[343] Fix | Delete
# retain up to the first colon (if any)
[344] Fix | Delete
i = msg.find(':', 0, end)
[345] Fix | Delete
if i >= 0:
[346] Fix | Delete
end = i
[347] Fix | Delete
# retain just the exception name
[348] Fix | Delete
i = msg.rfind('.', 0, end)
[349] Fix | Delete
if i >= 0:
[350] Fix | Delete
start = i+1
[351] Fix | Delete
return msg[start: end]
[352] Fix | Delete
[353] Fix | Delete
class _OutputRedirectingPdb(pdb.Pdb):
[354] Fix | Delete
"""
[355] Fix | Delete
A specialized version of the python debugger that redirects stdout
[356] Fix | Delete
to a given stream when interacting with the user. Stdout is *not*
[357] Fix | Delete
redirected when traced code is executed.
[358] Fix | Delete
"""
[359] Fix | Delete
def __init__(self, out):
[360] Fix | Delete
self.__out = out
[361] Fix | Delete
self.__debugger_used = False
[362] Fix | Delete
pdb.Pdb.__init__(self, stdout=out)
[363] Fix | Delete
# still use input() to get user input
[364] Fix | Delete
self.use_rawinput = 1
[365] Fix | Delete
[366] Fix | Delete
def set_trace(self, frame=None):
[367] Fix | Delete
self.__debugger_used = True
[368] Fix | Delete
if frame is None:
[369] Fix | Delete
frame = sys._getframe().f_back
[370] Fix | Delete
pdb.Pdb.set_trace(self, frame)
[371] Fix | Delete
[372] Fix | Delete
def set_continue(self):
[373] Fix | Delete
# Calling set_continue unconditionally would break unit test
[374] Fix | Delete
# coverage reporting, as Bdb.set_continue calls sys.settrace(None).
[375] Fix | Delete
if self.__debugger_used:
[376] Fix | Delete
pdb.Pdb.set_continue(self)
[377] Fix | Delete
[378] Fix | Delete
def trace_dispatch(self, *args):
[379] Fix | Delete
# Redirect stdout to the given stream.
[380] Fix | Delete
save_stdout = sys.stdout
[381] Fix | Delete
sys.stdout = self.__out
[382] Fix | Delete
# Call Pdb's trace dispatch method.
[383] Fix | Delete
try:
[384] Fix | Delete
return pdb.Pdb.trace_dispatch(self, *args)
[385] Fix | Delete
finally:
[386] Fix | Delete
sys.stdout = save_stdout
[387] Fix | Delete
[388] Fix | Delete
# [XX] Normalize with respect to os.path.pardir?
[389] Fix | Delete
def _module_relative_path(module, path):
[390] Fix | Delete
if not inspect.ismodule(module):
[391] Fix | Delete
raise TypeError, 'Expected a module: %r' % module
[392] Fix | Delete
if path.startswith('/'):
[393] Fix | Delete
raise ValueError, 'Module-relative files may not have absolute paths'
[394] Fix | Delete
[395] Fix | Delete
# Find the base directory for the path.
[396] Fix | Delete
if hasattr(module, '__file__'):
[397] Fix | Delete
# A normal module/package
[398] Fix | Delete
basedir = os.path.split(module.__file__)[0]
[399] Fix | Delete
elif module.__name__ == '__main__':
[400] Fix | Delete
# An interactive session.
[401] Fix | Delete
if len(sys.argv)>0 and sys.argv[0] != '':
[402] Fix | Delete
basedir = os.path.split(sys.argv[0])[0]
[403] Fix | Delete
else:
[404] Fix | Delete
basedir = os.curdir
[405] Fix | Delete
else:
[406] Fix | Delete
# A module w/o __file__ (this includes builtins)
[407] Fix | Delete
raise ValueError("Can't resolve paths relative to the module " +
[408] Fix | Delete
module + " (it has no __file__)")
[409] Fix | Delete
[410] Fix | Delete
# Combine the base directory and the path.
[411] Fix | Delete
return os.path.join(basedir, *(path.split('/')))
[412] Fix | Delete
[413] Fix | Delete
######################################################################
[414] Fix | Delete
## 2. Example & DocTest
[415] Fix | Delete
######################################################################
[416] Fix | Delete
## - An "example" is a <source, want> pair, where "source" is a
[417] Fix | Delete
## fragment of source code, and "want" is the expected output for
[418] Fix | Delete
## "source." The Example class also includes information about
[419] Fix | Delete
## where the example was extracted from.
[420] Fix | Delete
##
[421] Fix | Delete
## - A "doctest" is a collection of examples, typically extracted from
[422] Fix | Delete
## a string (such as an object's docstring). The DocTest class also
[423] Fix | Delete
## includes information about where the string was extracted from.
[424] Fix | Delete
[425] Fix | Delete
class Example:
[426] Fix | Delete
"""
[427] Fix | Delete
A single doctest example, consisting of source code and expected
[428] Fix | Delete
output. `Example` defines the following attributes:
[429] Fix | Delete
[430] Fix | Delete
- source: A single Python statement, always ending with a newline.
[431] Fix | Delete
The constructor adds a newline if needed.
[432] Fix | Delete
[433] Fix | Delete
- want: The expected output from running the source code (either
[434] Fix | Delete
from stdout, or a traceback in case of exception). `want` ends
[435] Fix | Delete
with a newline unless it's empty, in which case it's an empty
[436] Fix | Delete
string. The constructor adds a newline if needed.
[437] Fix | Delete
[438] Fix | Delete
- exc_msg: The exception message generated by the example, if
[439] Fix | Delete
the example is expected to generate an exception; or `None` if
[440] Fix | Delete
it is not expected to generate an exception. This exception
[441] Fix | Delete
message is compared against the return value of
[442] Fix | Delete
`traceback.format_exception_only()`. `exc_msg` ends with a
[443] Fix | Delete
newline unless it's `None`. The constructor adds a newline
[444] Fix | Delete
if needed.
[445] Fix | Delete
[446] Fix | Delete
- lineno: The line number within the DocTest string containing
[447] Fix | Delete
this Example where the Example begins. This line number is
[448] Fix | Delete
zero-based, with respect to the beginning of the DocTest.
[449] Fix | Delete
[450] Fix | Delete
- indent: The example's indentation in the DocTest string.
[451] Fix | Delete
I.e., the number of space characters that precede the
[452] Fix | Delete
example's first prompt.
[453] Fix | Delete
[454] Fix | Delete
- options: A dictionary mapping from option flags to True or
[455] Fix | Delete
False, which is used to override default options for this
[456] Fix | Delete
example. Any option flags not contained in this dictionary
[457] Fix | Delete
are left at their default value (as specified by the
[458] Fix | Delete
DocTestRunner's optionflags). By default, no options are set.
[459] Fix | Delete
"""
[460] Fix | Delete
def __init__(self, source, want, exc_msg=None, lineno=0, indent=0,
[461] Fix | Delete
options=None):
[462] Fix | Delete
# Normalize inputs.
[463] Fix | Delete
if not source.endswith('\n'):
[464] Fix | Delete
source += '\n'
[465] Fix | Delete
if want and not want.endswith('\n'):
[466] Fix | Delete
want += '\n'
[467] Fix | Delete
if exc_msg is not None and not exc_msg.endswith('\n'):
[468] Fix | Delete
exc_msg += '\n'
[469] Fix | Delete
# Store properties.
[470] Fix | Delete
self.source = source
[471] Fix | Delete
self.want = want
[472] Fix | Delete
self.lineno = lineno
[473] Fix | Delete
self.indent = indent
[474] Fix | Delete
if options is None: options = {}
[475] Fix | Delete
self.options = options
[476] Fix | Delete
self.exc_msg = exc_msg
[477] Fix | Delete
[478] Fix | Delete
def __eq__(self, other):
[479] Fix | Delete
if type(self) is not type(other):
[480] Fix | Delete
return NotImplemented
[481] Fix | Delete
[482] Fix | Delete
return self.source == other.source and \
[483] Fix | Delete
self.want == other.want and \
[484] Fix | Delete
self.lineno == other.lineno and \
[485] Fix | Delete
self.indent == other.indent and \
[486] Fix | Delete
self.options == other.options and \
[487] Fix | Delete
self.exc_msg == other.exc_msg
[488] Fix | Delete
[489] Fix | Delete
def __ne__(self, other):
[490] Fix | Delete
return not self == other
[491] Fix | Delete
[492] Fix | Delete
def __hash__(self):
[493] Fix | Delete
return hash((self.source, self.want, self.lineno, self.indent,
[494] Fix | Delete
self.exc_msg))
[495] Fix | Delete
[496] Fix | Delete
[497] Fix | Delete
class DocTest:
[498] Fix | Delete
"""
[499] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function