Whitespace normalization. Ugh, we really need to do this more often.

You might want to review this change as it's my first time.  Be gentle. :-)
This commit is contained in:
Neal Norwitz 2007-04-25 06:30:05 +00:00
parent e47c508850
commit 0d4c06e06e
38 changed files with 386 additions and 387 deletions

View File

@ -234,7 +234,7 @@ c_voidp = c_void_p # backwards compatibility (to a bug)
_check_size(c_void_p)
class c_bool(_SimpleCData):
_type_ = "t"
_type_ = "t"
# This cache maps types to pointers to them.
_pointer_type_cache = {}

View File

@ -69,7 +69,7 @@ class NumberTestCase(unittest.TestCase):
for t, (l, h) in zip(signed_types, signed_ranges):
self.failUnlessEqual(t(l).value, l)
self.failUnlessEqual(t(h).value, h)
def test_bool_values(self):
from operator import truth
for t, v in zip(bool_types, bool_values):
@ -178,7 +178,7 @@ class NumberTestCase(unittest.TestCase):
a[0] = '?'
self.failUnlessEqual(v.value, a[0])
# array does not support c_bool / 't'
# def test_bool_from_address(self):
# from ctypes import c_bool

View File

@ -2631,7 +2631,7 @@ class Context(object):
1) before use.
If the increased precision needed for the intermediate calculations
exceeds the capabilities of the implementation then an Invalid
exceeds the capabilities of the implementation then an Invalid
operation condition is raised.
If, when raising to a negative power, an underflow occurs during the
@ -2725,7 +2725,7 @@ class Context(object):
The result is the residue of the dividend after the operation of
calculating integer division as described for divide-integer, rounded
to precision digits if necessary. The sign of the result, if
to precision digits if necessary. The sign of the result, if
non-zero, is the same as that of the original dividend.
This operation will fail under the same conditions as integer division
@ -2929,7 +2929,7 @@ def _normalize(op1, op2, shouldround = 0, prec = 0):
if numdigits > (other_len + prec + 1 - tmp_len):
# If the difference in adjusted exps is > prec+1, we know
# other is insignificant, so might as well put a 1 after the
# precision (since this is only for addition). Also stops
# precision (since this is only for addition). Also stops
# use of massive longs.
extend = prec + 2 - tmp_len
@ -3098,7 +3098,7 @@ del re
def _string2exact(s):
"""Return sign, n, p s.t.
Float string value == -1**sign * n * 10**p exactly
"""
m = _parser(s)

View File

@ -84,7 +84,7 @@ class FTP:
meaning that no timeout will be set on any ftp socket(s)
If a timeout is passed, then this is now the default timeout for all ftp
socket operations for this instance.
Then use self.connect() with optional host and port argument.
To download a file, use ftp.retrlines('RETR ' + filename),
@ -112,7 +112,7 @@ class FTP:
self.timeout = timeout
if host:
self.connect(host)
if user:
if user:
self.login(user, passwd, acct)
def connect(self, host='', port=0, timeout=None):

View File

@ -1149,7 +1149,7 @@ see no sign that the breakpoint was reached.
def _runscript(self, filename):
# The script has to run in __main__ namespace (or imports from
# __main__ will break).
#
#
# So we clear up the __main__ and set several special variables
# (this gets rid of pdb's globals and cleans old variables on restarts).
import __main__
@ -1158,7 +1158,7 @@ see no sign that the breakpoint was reached.
"__file__" : filename,
"__builtins__": __builtins__,
})
# When bdb sets tracing, a number of call and line events happens
# BEFORE debugger even reaches user's code (and the exact sequence of
# events depends on python version). So we take special measures to
@ -1168,7 +1168,7 @@ see no sign that the breakpoint was reached.
self.mainpyfile = self.canonic(filename)
self._user_requested_quit = 0
statement = 'execfile( "%s")' % filename
self.run(statement)
self.run(statement)
# Simplified interface

View File

@ -388,10 +388,10 @@ def relpath(path, start=curdir):
if not path:
raise ValueError("no path specified")
start_list = abspath(start).split(sep)
path_list = abspath(path).split(sep)
# Work out how much of the filepath is shared by start and path.
i = len(commonprefix([start_list, path_list]))

View File

@ -24,7 +24,7 @@ inet_ntoa() -- convert 32-bit packed format IP to string (123.45.67.89)
ssl() -- secure socket layer support (only available if configured)
socket.getdefaulttimeout() -- get the default timeout value
socket.setdefaulttimeout() -- set the default timeout value
create_connection() -- connects to an address, with an optional timeout
create_connection() -- connects to an address, with an optional timeout
[*] not available on all platforms!
@ -418,12 +418,12 @@ class _fileobject(object):
def create_connection(address, timeout=None):
"""Connect to address (host, port) with an optional timeout.
Provides access to socketobject timeout for higher-level
protocols. Passing a timeout will set the timeout on the
Provides access to socketobject timeout for higher-level
protocols. Passing a timeout will set the timeout on the
socket instance (if not present, or passed as None, the
default global timeout setting will be used).
"""
msg = "getaddrinfo returns an empty list"
host, port = address
for res in getaddrinfo(host, port, 0, SOCK_STREAM):
@ -435,7 +435,7 @@ def create_connection(address, timeout=None):
sock.settimeout(timeout)
sock.connect(sa)
return sock
except error, msg:
if sock is not None:
sock.close()

View File

@ -38,9 +38,9 @@ if _os.name == 'mac':
import Carbon.Folders as _Folders
try:
from cStringIO import StringIO as _StringIO
from cStringIO import StringIO as _StringIO
except:
from StringIO import StringIO as _StringIO
from StringIO import StringIO as _StringIO
try:
import fcntl as _fcntl
@ -510,7 +510,7 @@ class SpooledTemporaryFile:
newfile.seek(file.tell(), 0)
self._rolled = True
# file protocol
def __iter__(self):
return self._file.__iter__()

View File

@ -44,7 +44,7 @@ class TestDifflibLongestMatch(unittest.TestCase):
self.assertEquals(i, l)
self.assertEquals(aptr, 1)
self.assertEquals(bptr, 0)
def test_main():
test_support.run_unittest(TestDifflibLongestMatch)

View File

@ -1096,9 +1096,9 @@ class MixinStrStringUserStringTest:
self.checkequal('Abc', 'abc', 'translate', table)
self.checkequal('xyz', 'xyz', 'translate', table)
self.checkequal('yz', 'xyz', 'translate', table, 'x')
self.checkequal('yx', 'zyzzx', 'translate', None, 'z')
self.checkequal('yx', 'zyzzx', 'translate', None, 'z')
self.checkequal('zyzzx', 'zyzzx', 'translate', None, '')
self.checkequal('zyzzx', 'zyzzx', 'translate', None)
self.checkequal('zyzzx', 'zyzzx', 'translate', None)
self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip')
self.checkraises(ValueError, 'xyz', 'translate', 'too short')

View File

@ -1248,7 +1248,7 @@ def slots():
c.abc = 5
vereq(c.abc, 5)
# _unicode_to_string used to modify slots in certain circumstances
# _unicode_to_string used to modify slots in certain circumstances
slots = (unicode("foo"), unicode("bar"))
class C(object):
__slots__ = slots
@ -1263,7 +1263,7 @@ def slots():
except (TypeError, UnicodeEncodeError):
pass
else:
raise TestFailed, "[unichr(128)] slots not caught"
raise TestFailed, "[unichr(128)] slots not caught"
# Test leaks
class Counted(object):

View File

@ -27,7 +27,7 @@ def writeTmp(i, lines, mode='w'): # opening in text mode is the default
def remove_tempfiles(*names):
for name in names:
safe_unlink(name)
class BufferSizesTests(unittest.TestCase):
def test_buffer_sizes(self):
# First, run the tests with default and teeny buffer size.
@ -40,10 +40,10 @@ class BufferSizesTests(unittest.TestCase):
self.buffer_size_test(t1, t2, t3, t4, bs, round)
finally:
remove_tempfiles(t1, t2, t3, t4)
def buffer_size_test(self, t1, t2, t3, t4, bs=0, round=0):
pat = re.compile(r'LINE (\d+) OF FILE (\d+)')
start = 1 + round*6
if verbose:
print '%s. Simple iteration (bs=%s)' % (start+0, bs)
@ -117,7 +117,7 @@ class BufferSizesTests(unittest.TestCase):
self.assertNotEqual(m, None)
self.assertEqual(int(m.group(1)), fi.filelineno())
fi.close()
class FileInputTests(unittest.TestCase):
def test_zero_byte_files(self):
try:
@ -126,13 +126,13 @@ class FileInputTests(unittest.TestCase):
t3 = writeTmp(3, ["The only line there is.\n"])
t4 = writeTmp(4, [""])
fi = FileInput(files=(t1, t2, t3, t4))
line = fi.readline()
self.assertEqual(line, 'The only line there is.\n')
self.assertEqual(fi.lineno(), 1)
self.assertEqual(fi.filelineno(), 1)
self.assertEqual(fi.filename(), t3)
line = fi.readline()
self.failIf(line)
self.assertEqual(fi.lineno(), 1)
@ -220,6 +220,6 @@ class FileInputTests(unittest.TestCase):
def test_main():
run_unittest(BufferSizesTests, FileInputTests)
if __name__ == "__main__":
test_main()

View File

@ -24,7 +24,7 @@ def server(evt):
evt.set()
class GeneralTests(TestCase):
def setUp(self):
ftplib.FTP.port = 9091
self.evt = threading.Event()
@ -41,13 +41,13 @@ class GeneralTests(TestCase):
# connects
ftp = ftplib.FTP("localhost")
ftp.sock.close()
def testTimeoutDefault(self):
# default
ftp = ftplib.FTP("localhost")
self.assertTrue(ftp.sock.gettimeout() is None)
ftp.sock.close()
def testTimeoutValue(self):
# a value
ftp = ftplib.FTP("localhost", timeout=30)

View File

@ -6,7 +6,7 @@ import weakref
### Support code
###############################################################################
# Bug 1055820 has several tests of longstanding bugs involving weakrefs and
# cyclic gc.
@ -32,9 +32,9 @@ class GC_Detector(object):
self.wr = weakref.ref(C1055820(666), it_happened)
### Tests
### Tests
###############################################################################
class GCTests(unittest.TestCase):
def test_list(self):
l = []
@ -259,7 +259,7 @@ class GCTests(unittest.TestCase):
Ouch.n = Ouch.n + 1
if Ouch.n % 17 == 0:
gc.collect()
# "trashcan" is a hack to prevent stack overflow when deallocating
# very deeply nested tuples etc. It works in part by abusing the
# type pointer and refcount fields, and that can yield horrible
@ -292,7 +292,7 @@ class GCTests(unittest.TestCase):
def __getattr__(self, someattribute):
del self.attr
raise AttributeError
a = Boom()
b = Boom()
a.attr = b
@ -321,7 +321,7 @@ class GCTests(unittest.TestCase):
if self.x > 1:
del self.attr
raise AttributeError
a = Boom2()
b = Boom2()
a.attr = b
@ -346,7 +346,7 @@ class GCTests(unittest.TestCase):
def __getattr__(self, someattribute):
del self.attr
raise AttributeError
a = Boom_New()
b = Boom_New()
a.attr = b
@ -368,7 +368,7 @@ class GCTests(unittest.TestCase):
if self.x > 1:
del self.attr
raise AttributeError
a = Boom2_New()
b = Boom2_New()
a.attr = b
@ -430,10 +430,10 @@ class GCTests(unittest.TestCase):
class GCTogglingTests(unittest.TestCase):
def setUp(self):
gc.enable()
def tearDown(self):
gc.disable()
def test_bug1055820c(self):
# Corresponds to temp2c.py in the bug report. This is pretty
# elaborate.
@ -591,6 +591,6 @@ def test_main():
assert gc.isenabled()
if not enabled:
gc.disable()
if __name__ == "__main__":
test_main()

View File

@ -15,15 +15,15 @@ class GetoptTests(unittest.TestCase):
if self.old_posixly_correct is not sentinel:
del os.environ["POSIXLY_CORRECT"]
def tearDown(self):
def tearDown(self):
if self.old_posixly_correct is sentinel:
os.environ.pop("POSIXLY_CORRECT", None)
else:
os.environ["POSIXLY_CORRECT"] = self.old_posixly_correct
def assertError(self, *args, **kwargs):
self.assertRaises(getopt.GetoptError, *args, **kwargs)
def test_short_has_arg(self):
self.failUnless(getopt.short_has_arg('a', 'a:'))
self.failIf(getopt.short_has_arg('a', 'a'))
@ -33,15 +33,15 @@ class GetoptTests(unittest.TestCase):
has_arg, option = getopt.long_has_args('abc', ['abc='])
self.failUnless(has_arg)
self.assertEqual(option, 'abc')
has_arg, option = getopt.long_has_args('abc', ['abc'])
self.failIf(has_arg)
self.assertEqual(option, 'abc')
has_arg, option = getopt.long_has_args('abc', ['abcd'])
self.failIf(has_arg)
self.assertEqual(option, 'abcd')
self.assertError(getopt.long_has_args, 'abc', ['def'])
self.assertError(getopt.long_has_args, 'abc', [])
self.assertError(getopt.long_has_args, 'abc', ['abcd','abcde'])
@ -50,23 +50,23 @@ class GetoptTests(unittest.TestCase):
opts, args = getopt.do_shorts([], 'a', 'a', [])
self.assertEqual(opts, [('-a', '')])
self.assertEqual(args, [])
opts, args = getopt.do_shorts([], 'a1', 'a:', [])
self.assertEqual(opts, [('-a', '1')])
self.assertEqual(args, [])
#opts, args = getopt.do_shorts([], 'a=1', 'a:', [])
#self.assertEqual(opts, [('-a', '1')])
#self.assertEqual(args, [])
opts, args = getopt.do_shorts([], 'a', 'a:', ['1'])
self.assertEqual(opts, [('-a', '1')])
self.assertEqual(args, [])
opts, args = getopt.do_shorts([], 'a', 'a:', ['1', '2'])
self.assertEqual(opts, [('-a', '1')])
self.assertEqual(args, ['2'])
self.assertError(getopt.do_shorts, [], 'a1', 'a', [])
self.assertError(getopt.do_shorts, [], 'a', 'a:', [])
@ -74,26 +74,26 @@ class GetoptTests(unittest.TestCase):
opts, args = getopt.do_longs([], 'abc', ['abc'], [])
self.assertEqual(opts, [('--abc', '')])
self.assertEqual(args, [])
opts, args = getopt.do_longs([], 'abc=1', ['abc='], [])
self.assertEqual(opts, [('--abc', '1')])
self.assertEqual(args, [])
opts, args = getopt.do_longs([], 'abc=1', ['abcd='], [])
self.assertEqual(opts, [('--abcd', '1')])
self.assertEqual(args, [])
opts, args = getopt.do_longs([], 'abc', ['ab', 'abc', 'abcd'], [])
self.assertEqual(opts, [('--abc', '')])
self.assertEqual(args, [])
# Much like the preceding, except with a non-alpha character ("-") in
# option name that precedes "="; failed in
# http://python.org/sf/126863
opts, args = getopt.do_longs([], 'foo=42', ['foo-bar', 'foo=',], [])
self.assertEqual(opts, [('--foo', '42')])
self.assertEqual(args, [])
self.assertError(getopt.do_longs, [], 'abc=1', ['abc'], [])
self.assertError(getopt.do_longs, [], 'abc', ['abc='], [])
@ -117,18 +117,18 @@ class GetoptTests(unittest.TestCase):
def test_gnu_getopt(self):
# Test handling of GNU style scanning mode.
cmdline = ['-a', 'arg1', '-b', '1', '--alpha', '--beta=2']
# GNU style
opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
self.assertEqual(args, ['arg1'])
self.assertEqual(opts, [('-a', ''), ('-b', '1'),
('--alpha', ''), ('--beta', '2')])
# Posix style via +
opts, args = getopt.gnu_getopt(cmdline, '+ab:', ['alpha', 'beta='])
self.assertEqual(opts, [('-a', '')])
self.assertEqual(args, ['arg1', '-b', '1', '--alpha', '--beta=2'])
# Posix style via POSIXLY_CORRECT
os.environ["POSIXLY_CORRECT"] = "1"
opts, args = getopt.gnu_getopt(cmdline, 'ab:', ['alpha', 'beta='])
@ -166,7 +166,7 @@ class GetoptTests(unittest.TestCase):
>>> args
['a1', 'a2']
"""
import new
m = new.module("libreftest", s)
run_doctest(m, verbose)
@ -174,6 +174,6 @@ class GetoptTests(unittest.TestCase):
def test_main():
run_unittest(GetoptTests)
if __name__ == "__main__":
test_main()

View File

@ -154,7 +154,7 @@ PORT = 50003
HOST = "localhost"
class TimeoutTest(TestCase):
def setUp(self):
self.serv = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
self.serv.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
@ -175,7 +175,7 @@ class TimeoutTest(TestCase):
httpConn.connect()
self.assertTrue(httpConn.sock.gettimeout() is None)
httpConn.close()
# a value
httpConn = httplib.HTTPConnection(HOST, PORT, timeout=30)
httpConn.connect()

View File

@ -50,6 +50,6 @@ class TrueDivisionTests(unittest.TestCase):
def test_main():
run_unittest(TrueDivisionTests)
if __name__ == "__main__":
test_main()

View File

@ -72,25 +72,25 @@ class MinidomTest(unittest.TestCase):
# are needed
print len(Node.allnodes)
Node.allnodes = {}
def confirm(self, test, testname = "Test"):
self.assertTrue(test, testname)
def checkWholeText(self, node, s):
t = node.wholeText
self.confirm(t == s, "looking for %s, found %s" % (repr(s), repr(t)))
def testParseFromFile(self):
dom = parse(StringIO(open(tstfile).read()))
dom.unlink()
self.confirm(isinstance(dom,Document))
def testGetElementsByTagName(self):
dom = parse(tstfile)
self.confirm(dom.getElementsByTagName("LI") == \
dom.documentElement.getElementsByTagName("LI"))
dom.unlink()
def testInsertBefore(self):
dom = parseString("<doc><foo/></doc>")
root = dom.documentElement
@ -129,11 +129,11 @@ class MinidomTest(unittest.TestCase):
and root.childNodes.item(3) is nelem
and nelem2.nextSibling is nelem
and nelem.previousSibling is nelem2
and root.toxml() ==
and root.toxml() ==
"<doc><element/><foo/><bar/><element/></doc>"
, "testInsertBefore -- node properly placed in tree")
dom.unlink()
def _create_fragment_test_nodes(self):
dom = parseString("<doc/>")
orig = dom.createTextNode("original")
@ -146,11 +146,11 @@ class MinidomTest(unittest.TestCase):
frag.appendChild(c2)
frag.appendChild(c3)
return dom, orig, c1, c2, c3, frag
def testInsertBeforeFragment(self):
dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
dom.documentElement.insertBefore(frag, None)
self.confirm(tuple(dom.documentElement.childNodes) ==
self.confirm(tuple(dom.documentElement.childNodes) ==
(orig, c1, c2, c3),
"insertBefore(<fragment>, None)")
frag.unlink()
@ -158,28 +158,28 @@ class MinidomTest(unittest.TestCase):
dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
dom.documentElement.insertBefore(frag, orig)
self.confirm(tuple(dom.documentElement.childNodes) ==
self.confirm(tuple(dom.documentElement.childNodes) ==
(c1, c2, c3, orig),
"insertBefore(<fragment>, orig)")
frag.unlink()
dom.unlink()
def testAppendChild(self):
dom = parse(tstfile)
dom.documentElement.appendChild(dom.createComment(u"Hello"))
self.confirm(dom.documentElement.childNodes[-1].nodeName == "#comment")
self.confirm(dom.documentElement.childNodes[-1].data == "Hello")
dom.unlink()
def testAppendChildFragment(self):
dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
dom.documentElement.appendChild(frag)
self.confirm(tuple(dom.documentElement.childNodes) ==
self.confirm(tuple(dom.documentElement.childNodes) ==
(orig, c1, c2, c3),
"appendChild(<fragment>)")
frag.unlink()
dom.unlink()
def testReplaceChildFragment(self):
dom, orig, c1, c2, c3, frag = self._create_fragment_test_nodes()
dom.documentElement.replaceChild(frag, orig)
@ -188,28 +188,28 @@ class MinidomTest(unittest.TestCase):
"replaceChild(<fragment>)")
frag.unlink()
dom.unlink()
def testLegalChildren(self):
dom = Document()
elem = dom.createElement('element')
text = dom.createTextNode('text')
self.assertRaises(xml.dom.HierarchyRequestErr, dom.appendChild, text)
dom.appendChild(elem)
self.assertRaises(xml.dom.HierarchyRequestErr, dom.insertBefore, text,
self.assertRaises(xml.dom.HierarchyRequestErr, dom.insertBefore, text,
elem)
self.assertRaises(xml.dom.HierarchyRequestErr, dom.replaceChild, text,
self.assertRaises(xml.dom.HierarchyRequestErr, dom.replaceChild, text,
elem)
nodemap = elem.attributes
self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItem,
self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItem,
text)
self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItemNS,
self.assertRaises(xml.dom.HierarchyRequestErr, nodemap.setNamedItemNS,
text)
elem.appendChild(text)
dom.unlink()
def testNamedNodeMapSetItem(self):
dom = Document()
elem = dom.createElement('element')
@ -226,24 +226,24 @@ class MinidomTest(unittest.TestCase):
"NamedNodeMap.__setitem__() sets nodeValue")
elem.unlink()
dom.unlink()
def testNonZero(self):
dom = parse(tstfile)
self.confirm(dom)# should not be zero
dom.appendChild(dom.createComment("foo"))
self.confirm(not dom.childNodes[-1].childNodes)
dom.unlink()
def testUnlink(self):
dom = parse(tstfile)
dom.unlink()
def testElement(self):
dom = Document()
dom.appendChild(dom.createElement("abc"))
self.confirm(dom.documentElement)
dom.unlink()
def testAAA(self):
dom = parseString("<abc/>")
el = dom.documentElement
@ -255,7 +255,7 @@ class MinidomTest(unittest.TestCase):
self.confirm(a.ownerElement is dom.documentElement,
"setAttribute() sets ownerElement")
dom.unlink()
def testAAB(self):
dom = parseString("<abc/>")
el = dom.documentElement
@ -263,49 +263,49 @@ class MinidomTest(unittest.TestCase):
el.setAttribute("spam", "jam2")
self.confirm(el.toxml() == '<abc spam="jam2"/>', "testAAB")
dom.unlink()
def testAddAttr(self):
dom = Document()
child = dom.appendChild(dom.createElement("abc"))
child.setAttribute("def", "ghi")
self.confirm(child.getAttribute("def") == "ghi")
self.confirm(child.attributes["def"].value == "ghi")
child.setAttribute("jkl", "mno")
self.confirm(child.getAttribute("jkl") == "mno")
self.confirm(child.attributes["jkl"].value == "mno")
self.confirm(len(child.attributes) == 2)
child.setAttribute("def", "newval")
self.confirm(child.getAttribute("def") == "newval")
self.confirm(child.attributes["def"].value == "newval")
self.confirm(len(child.attributes) == 2)
dom.unlink()
def testDeleteAttr(self):
dom = Document()
child = dom.appendChild(dom.createElement("abc"))
self.confirm(len(child.attributes) == 0)
child.setAttribute("def", "ghi")
self.confirm(len(child.attributes) == 1)
del child.attributes["def"]
self.confirm(len(child.attributes) == 0)
dom.unlink()
def testRemoveAttr(self):
dom = Document()
child = dom.appendChild(dom.createElement("abc"))
child.setAttribute("def", "ghi")
self.confirm(len(child.attributes) == 1)
child.removeAttribute("def")
self.confirm(len(child.attributes) == 0)
dom.unlink()
def testRemoveAttrNS(self):
dom = Document()
child = dom.appendChild(
@ -317,7 +317,7 @@ class MinidomTest(unittest.TestCase):
child.removeAttributeNS("http://www.python.org", "abcattr")
self.confirm(len(child.attributes) == 1)
dom.unlink()
def testRemoveAttributeNode(self):
dom = Document()
child = dom.appendChild(dom.createElement("foo"))
@ -328,7 +328,7 @@ class MinidomTest(unittest.TestCase):
self.confirm(len(child.attributes) == 0
and child.getAttributeNode("spam") is None)
dom.unlink()
def testChangeAttr(self):
dom = parseString("<abc/>")
el = dom.documentElement
@ -366,26 +366,26 @@ class MinidomTest(unittest.TestCase):
and el.attributes["spam2"].nodeValue == "bam2"
and el.getAttribute("spam2") == "bam2")
dom.unlink()
def testGetAttrList(self):
pass
def testGetAttrValues(self): pass
def testGetAttrLength(self): pass
def testGetAttribute(self): pass
def testGetAttributeNS(self): pass
def testGetAttributeNode(self): pass
def testGetElementsByTagNameNS(self):
d="""<foo xmlns:minidom='http://pyxml.sf.net/minidom'>
<minidom:myelem/>
</foo>"""
dom = parseString(d)
elems = dom.getElementsByTagNameNS("http://pyxml.sf.net/minidom",
elems = dom.getElementsByTagNameNS("http://pyxml.sf.net/minidom",
"myelem")
self.confirm(len(elems) == 1
and elems[0].namespaceURI == "http://pyxml.sf.net/minidom"
@ -394,12 +394,12 @@ class MinidomTest(unittest.TestCase):
and elems[0].tagName == "minidom:myelem"
and elems[0].nodeName == "minidom:myelem")
dom.unlink()
def get_empty_nodelist_from_elements_by_tagName_ns_helper(self, doc, nsuri,
def get_empty_nodelist_from_elements_by_tagName_ns_helper(self, doc, nsuri,
lname):
nodelist = doc.getElementsByTagNameNS(nsuri, lname)
self.confirm(len(nodelist) == 0)
def testGetEmptyNodeListFromElementsByTagNameNS(self):
doc = parseString('<doc/>')
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
@ -408,7 +408,7 @@ class MinidomTest(unittest.TestCase):
doc, '*', 'splat')
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, 'http://xml.python.org/namespaces/a', '*')
doc = parseString('<doc xmlns="http://xml.python.org/splat"><e/></doc>')
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, "http://xml.python.org/splat", "not-there")
@ -416,7 +416,7 @@ class MinidomTest(unittest.TestCase):
doc, "*", "not-there")
self.get_empty_nodelist_from_elements_by_tagName_ns_helper(
doc, "http://somewhere.else.net/not-there", "e")
def testElementReprAndStr(self):
dom = Document()
el = dom.appendChild(dom.createElement("abc"))
@ -424,7 +424,7 @@ class MinidomTest(unittest.TestCase):
string2 = str(el)
self.confirm(string1 == string2)
dom.unlink()
def testElementReprAndStrUnicode(self):
dom = Document()
el = dom.appendChild(dom.createElement(u"abc"))
@ -432,7 +432,7 @@ class MinidomTest(unittest.TestCase):
string2 = str(el)
self.confirm(string1 == string2)
dom.unlink()
def testElementReprAndStrUnicodeNS(self):
dom = Document()
el = dom.appendChild(
@ -442,30 +442,30 @@ class MinidomTest(unittest.TestCase):
self.confirm(string1 == string2)
self.confirm(string1.find("slash:abc") != -1)
dom.unlink()
def testAttributeRepr(self):
dom = Document()
el = dom.appendChild(dom.createElement(u"abc"))
node = el.setAttribute("abc", "def")
self.confirm(str(node) == repr(node))
dom.unlink()
def testTextNodeRepr(self): pass
def testWriteXML(self):
str = '<?xml version="1.0" ?><a b="c"/>'
dom = parseString(str)
domstr = dom.toxml()
dom.unlink()
self.confirm(str == domstr)
def testAltNewline(self):
str = '<?xml version="1.0" ?>\n<a b="c"/>\n'
dom = parseString(str)
domstr = dom.toprettyxml(newl="\r\n")
dom.unlink()
self.confirm(domstr == str.replace("\n", "\r\n"))
def testProcessingInstruction(self):
dom = parseString('<e><?mypi \t\n data \t\n ?></e>')
pi = dom.documentElement.firstChild
@ -480,15 +480,15 @@ class MinidomTest(unittest.TestCase):
and pi.lastChild is None
and pi.localName is None
and pi.namespaceURI == xml.dom.EMPTY_NAMESPACE)
def testProcessingInstructionRepr(self): pass
def testTextRepr(self): pass
def testWriteText(self): pass
def testDocumentElement(self): pass
def testTooManyDocumentElements(self):
doc = parseString("<doc/>")
elem = doc.createElement("extra")
@ -496,27 +496,27 @@ class MinidomTest(unittest.TestCase):
self.assertRaises(xml.dom.HierarchyRequestErr, doc.appendChild, elem)
elem.unlink()
doc.unlink()
def testCreateElementNS(self): pass
def testCreateAttributeNS(self): pass
def testParse(self): pass
def testParseString(self): pass
def testComment(self): pass
def testAttrListItem(self): pass
def testAttrListItems(self): pass
def testAttrListItemNS(self): pass
def testAttrListKeys(self): pass
def testAttrListKeysNS(self): pass
def testRemoveNamedItem(self):
doc = parseString("<doc a=''/>")
e = doc.documentElement
@ -525,7 +525,7 @@ class MinidomTest(unittest.TestCase):
a2 = attrs.removeNamedItem("a")
self.confirm(a1.isSameNode(a2))
self.assertRaises(xml.dom.NotFoundErr, attrs.removeNamedItem, "a")
def testRemoveNamedItemNS(self):
doc = parseString("<doc xmlns:a='http://xml.python.org/' a:b=''/>")
e = doc.documentElement
@ -533,33 +533,33 @@ class MinidomTest(unittest.TestCase):
a1 = e.getAttributeNodeNS("http://xml.python.org/", "b")
a2 = attrs.removeNamedItemNS("http://xml.python.org/", "b")
self.confirm(a1.isSameNode(a2))
self.assertRaises(xml.dom.NotFoundErr, attrs.removeNamedItemNS,
self.assertRaises(xml.dom.NotFoundErr, attrs.removeNamedItemNS,
"http://xml.python.org/", "b")
def testAttrListValues(self): pass
def testAttrListLength(self): pass
def testAttrList__getitem__(self): pass
def testAttrList__setitem__(self): pass
def testSetAttrValueandNodeValue(self): pass
def testParseElement(self): pass
def testParseAttributes(self): pass
def testParseElementNamespaces(self): pass
def testParseAttributeNamespaces(self): pass
def testParseProcessingInstructions(self): pass
def testChildNodes(self): pass
def testFirstChild(self): pass
def testHasChildNodes(self): pass
def _testCloneElementCopiesAttributes(self, e1, e2, test):
@ -581,7 +581,7 @@ class MinidomTest(unittest.TestCase):
, "clone of attribute node has proper attribute values")
self.confirm(a2.ownerElement is e2,
"clone of attribute node correctly owned")
def _setupCloneElement(self, deep):
dom = parseString("<doc attr='value'><foo/></doc>")
root = dom.documentElement
@ -593,7 +593,7 @@ class MinidomTest(unittest.TestCase):
root.setAttribute("attr", "NEW VALUE")
root.setAttribute("added", "VALUE")
return dom, clone
def testCloneElementShallow(self):
dom, clone = self._setupCloneElement(0)
self.confirm(len(clone.childNodes) == 0
@ -602,7 +602,7 @@ class MinidomTest(unittest.TestCase):
and clone.toxml() == '<doc attr="value"/>'
, "testCloneElementShallow")
dom.unlink()
def testCloneElementDeep(self):
dom, clone = self._setupCloneElement(1)
self.confirm(len(clone.childNodes) == 1
@ -711,25 +711,25 @@ class MinidomTest(unittest.TestCase):
doc1 = parseString("<doc/>")
doc2 = parseString("<doc/>")
self.assertRaises(xml.dom.NotSupportedErr, doc1.importNode, doc2, deep)
def testImportDocumentShallow(self):
self.check_import_document(0, "testImportDocumentShallow")
def testImportDocumentDeep(self):
self.check_import_document(1, "testImportDocumentDeep")
def testImportDocumentTypeShallow(self):
src = create_doc_with_doctype()
target = create_doc_without_doctype()
self.assertRaises(xml.dom.NotSupportedErr, target.importNode,
self.assertRaises(xml.dom.NotSupportedErr, target.importNode,
src.doctype, 0)
def testImportDocumentTypeDeep(self):
src = create_doc_with_doctype()
target = create_doc_without_doctype()
self.assertRaises(xml.dom.NotSupportedErr, target.importNode,
self.assertRaises(xml.dom.NotSupportedErr, target.importNode,
src.doctype, 1)
# Testing attribute clones uses a helper, and should always be deep,
# even if the argument to cloneNode is false.
def check_clone_attribute(self, deep, testName):
@ -745,13 +745,13 @@ class MinidomTest(unittest.TestCase):
testName + ": ownerDocument does not match")
self.confirm(clone.specified,
testName + ": cloned attribute must have specified == True")
def testCloneAttributeShallow(self):
self.check_clone_attribute(0, "testCloneAttributeShallow")
def testCloneAttributeDeep(self):
self.check_clone_attribute(1, "testCloneAttributeDeep")
def check_clone_pi(self, deep, testName):
doc = parseString("<?target data?><doc/>")
pi = doc.firstChild
@ -759,10 +759,10 @@ class MinidomTest(unittest.TestCase):
clone = pi.cloneNode(deep)
self.confirm(clone.target == pi.target
and clone.data == pi.data)
def testClonePIShallow(self):
self.check_clone_pi(0, "testClonePIShallow")
def testClonePIDeep(self):
self.check_clone_pi(1, "testClonePIDeep")
@ -772,7 +772,7 @@ class MinidomTest(unittest.TestCase):
root.appendChild(doc.createTextNode("first"))
root.appendChild(doc.createTextNode("second"))
self.confirm(len(root.childNodes) == 2
and root.childNodes.length == 2,
and root.childNodes.length == 2,
"testNormalize -- preparation")
doc.normalize()
self.confirm(len(root.childNodes) == 1
@ -781,7 +781,7 @@ class MinidomTest(unittest.TestCase):
and root.firstChild.data == "firstsecond"
, "testNormalize -- result")
doc.unlink()
doc = parseString("<doc/>")
root = doc.documentElement
root.appendChild(doc.createTextNode(""))
@ -790,21 +790,21 @@ class MinidomTest(unittest.TestCase):
and root.childNodes.length == 0,
"testNormalize -- single empty node removed")
doc.unlink()
def testSiblings(self):
doc = parseString("<doc><?pi?>text?<elm/></doc>")
root = doc.documentElement
(pi, text, elm) = root.childNodes
self.confirm(pi.nextSibling is text and
pi.previousSibling is None and
text.nextSibling is elm and
text.previousSibling is pi and
elm.nextSibling is None and
elm.previousSibling is text, "testSiblings")
doc.unlink()
def testParents(self):
doc = parseString(
"<doc><elm1><elm2/><elm2><elm3/></elm2></elm1></doc>")
@ -812,14 +812,14 @@ class MinidomTest(unittest.TestCase):
elm1 = root.childNodes[0]
(elm2a, elm2b) = elm1.childNodes
elm3 = elm2b.childNodes[0]
self.confirm(root.parentNode is doc and
elm1.parentNode is root and
elm2a.parentNode is elm1 and
elm2b.parentNode is elm1 and
elm3.parentNode is elm2b, "testParents")
doc.unlink()
def testNodeListItem(self):
doc = parseString("<doc><e/><e/></doc>")
children = doc.childNodes
@ -831,10 +831,10 @@ class MinidomTest(unittest.TestCase):
and docelem.childNodes.item(0).childNodes.item(0) is None,
"test NodeList.item()")
doc.unlink()
def testSAX2DOM(self):
from xml.dom import pulldom
sax2dom = pulldom.SAX2DOM()
sax2dom.startDocument()
sax2dom.startElement("doc", {})
@ -845,12 +845,12 @@ class MinidomTest(unittest.TestCase):
sax2dom.characters("text")
sax2dom.endElement("doc")
sax2dom.endDocument()
doc = sax2dom.document
root = doc.documentElement
(text1, elm1, text2) = root.childNodes
text3 = elm1.childNodes[0]
self.confirm(text1.previousSibling is None and
text1.nextSibling is elm1 and
elm1.previousSibling is text1 and
@ -859,28 +859,28 @@ class MinidomTest(unittest.TestCase):
text2.nextSibling is None and
text3.previousSibling is None and
text3.nextSibling is None, "testSAX2DOM - siblings")
self.confirm(root.parentNode is doc and
text1.parentNode is root and
elm1.parentNode is root and
text2.parentNode is root and
text3.parentNode is elm1, "testSAX2DOM - parents")
doc.unlink()
def testEncodings(self):
doc = parseString('<foo>&#x20ac;</foo>')
self.confirm(doc.toxml() == u'<?xml version="1.0" ?><foo>\u20ac</foo>'
and doc.toxml('utf-8') ==
and doc.toxml('utf-8') ==
'<?xml version="1.0" encoding="utf-8"?><foo>\xe2\x82\xac</foo>'
and doc.toxml('iso-8859-15') ==
and doc.toxml('iso-8859-15') ==
'<?xml version="1.0" encoding="iso-8859-15"?><foo>\xa4</foo>',
"testEncodings - encoding EURO SIGN")
# Verify that character decoding errors throw exceptions instead
# Verify that character decoding errors throw exceptions instead
# of crashing
self.assertRaises(UnicodeDecodeError, parseString,
self.assertRaises(UnicodeDecodeError, parseString,
'<fran\xe7ais>Comment \xe7a va ? Tr\xe8s bien ?</fran\xe7ais>')
doc.unlink()
class UserDataHandler:
@ -889,7 +889,7 @@ class MinidomTest(unittest.TestCase):
dst.setUserData(key, data + 1, self)
src.setUserData(key, None, None)
self.called = 1
def testUserData(self):
dom = Document()
n = dom.createElement('e')
@ -903,7 +903,7 @@ class MinidomTest(unittest.TestCase):
n.setUserData("foo", None, None)
self.confirm(n.getUserData("foo") is None)
self.confirm(n.getUserData("bar") == 13)
handler = self.UserDataHandler()
n.setUserData("bar", 12, handler)
c = n.cloneNode(1)
@ -916,18 +916,18 @@ class MinidomTest(unittest.TestCase):
def checkRenameNodeSharedConstraints(self, doc, node):
# Make sure illegal NS usage is detected:
self.assertRaises(xml.dom.NamespaceErr, doc.renameNode, node,
self.assertRaises(xml.dom.NamespaceErr, doc.renameNode, node,
"http://xml.python.org/ns", "xmlns:foo")
doc2 = parseString("<doc/>")
self.assertRaises(xml.dom.WrongDocumentErr, doc2.renameNode, node,
self.assertRaises(xml.dom.WrongDocumentErr, doc2.renameNode, node,
xml.dom.EMPTY_NAMESPACE, "foo")
def testRenameAttribute(self):
doc = parseString("<doc a='v'/>")
elem = doc.documentElement
attrmap = elem.attributes
attr = elem.attributes['a']
# Simple renaming
attr = doc.renameNode(attr, xml.dom.EMPTY_NAMESPACE, "b")
self.confirm(attr.name == "b"
@ -941,7 +941,7 @@ class MinidomTest(unittest.TestCase):
and attrmap["b"].isSameNode(attr)
and attr.ownerDocument.isSameNode(doc)
and attr.ownerElement.isSameNode(elem))
# Rename to have a namespace, no prefix
attr = doc.renameNode(attr, "http://xml.python.org/ns", "c")
self.confirm(attr.name == "c"
@ -957,7 +957,7 @@ class MinidomTest(unittest.TestCase):
"http://xml.python.org/ns", "c").isSameNode(attr)
and attrmap["c"].isSameNode(attr)
and attrmap[("http://xml.python.org/ns", "c")].isSameNode(attr))
# Rename to have a namespace, with prefix
attr = doc.renameNode(attr, "http://xml.python.org/ns2", "p:d")
self.confirm(attr.name == "p:d"
@ -976,7 +976,7 @@ class MinidomTest(unittest.TestCase):
"http://xml.python.org/ns2", "d").isSameNode(attr)
and attrmap["p:d"].isSameNode(attr)
and attrmap[("http://xml.python.org/ns2", "d")].isSameNode(attr))
# Rename back to a simple non-NS node
attr = doc.renameNode(attr, xml.dom.EMPTY_NAMESPACE, "e")
self.confirm(attr.name == "e"
@ -994,15 +994,15 @@ class MinidomTest(unittest.TestCase):
and elem.getAttributeNode("e").isSameNode(attr)
and attrmap["e"].isSameNode(attr))
self.assertRaises(xml.dom.NamespaceErr, doc.renameNode, attr,
self.assertRaises(xml.dom.NamespaceErr, doc.renameNode, attr,
"http://xml.python.org/ns", "xmlns")
self.checkRenameNodeSharedConstraints(doc, attr)
doc.unlink()
def testRenameElement(self):
doc = parseString("<doc/>")
elem = doc.documentElement
# Simple renaming
elem = doc.renameNode(elem, xml.dom.EMPTY_NAMESPACE, "a")
self.confirm(elem.tagName == "a"
@ -1011,7 +1011,7 @@ class MinidomTest(unittest.TestCase):
and elem.namespaceURI == xml.dom.EMPTY_NAMESPACE
and elem.prefix is None
and elem.ownerDocument.isSameNode(doc))
# Rename to have a namespace, no prefix
elem = doc.renameNode(elem, "http://xml.python.org/ns", "b")
self.confirm(elem.tagName == "b"
@ -1020,7 +1020,7 @@ class MinidomTest(unittest.TestCase):
and elem.namespaceURI == "http://xml.python.org/ns"
and elem.prefix is None
and elem.ownerDocument.isSameNode(doc))
# Rename to have a namespace, with prefix
elem = doc.renameNode(elem, "http://xml.python.org/ns2", "p:c")
self.confirm(elem.tagName == "p:c"
@ -1029,7 +1029,7 @@ class MinidomTest(unittest.TestCase):
and elem.namespaceURI == "http://xml.python.org/ns2"
and elem.prefix == "p"
and elem.ownerDocument.isSameNode(doc))
# Rename back to a simple non-NS node
elem = doc.renameNode(elem, xml.dom.EMPTY_NAMESPACE, "d")
self.confirm(elem.tagName == "d"
@ -1038,17 +1038,17 @@ class MinidomTest(unittest.TestCase):
and elem.namespaceURI == xml.dom.EMPTY_NAMESPACE
and elem.prefix is None
and elem.ownerDocument.isSameNode(doc))
self.checkRenameNodeSharedConstraints(doc, elem)
doc.unlink()
def testRenameOther(self):
# We have to create a comment node explicitly since not all DOM
# builders used with minidom add comments to the DOM.
doc = xml.dom.minidom.getDOMImplementation().createDocument(
xml.dom.EMPTY_NAMESPACE, "e", None)
node = doc.createComment("comment")
self.assertRaises(xml.dom.NotSupportedErr, doc.renameNode, node,
self.assertRaises(xml.dom.NotSupportedErr, doc.renameNode, node,
xml.dom.EMPTY_NAMESPACE, "foo")
doc.unlink()
@ -1057,13 +1057,13 @@ class MinidomTest(unittest.TestCase):
elem = doc.documentElement
text = elem.childNodes[0]
self.assertEquals(text.nodeType, Node.TEXT_NODE)
self.checkWholeText(text, "a")
elem.appendChild(doc.createTextNode("b"))
self.checkWholeText(text, "ab")
elem.insertBefore(doc.createCDATASection("c"), text)
self.checkWholeText(text, "cab")
# make sure we don't cross other nodes
splitter = doc.createComment("comment")
elem.appendChild(splitter)
@ -1071,23 +1071,23 @@ class MinidomTest(unittest.TestCase):
elem.appendChild(text2)
self.checkWholeText(text, "cab")
self.checkWholeText(text2, "d")
x = doc.createElement("x")
elem.replaceChild(x, splitter)
splitter = x
self.checkWholeText(text, "cab")
self.checkWholeText(text2, "d")
x = doc.createProcessingInstruction("y", "z")
elem.replaceChild(x, splitter)
splitter = x
self.checkWholeText(text, "cab")
self.checkWholeText(text2, "d")
elem.removeChild(splitter)
self.checkWholeText(text, "cabd")
self.checkWholeText(text2, "cabd")
def testPatch1094164(self):
doc = parseString("<doc><e/></doc>")
elem = doc.documentElement
@ -1096,7 +1096,7 @@ class MinidomTest(unittest.TestCase):
# Check that replacing a child with itself leaves the tree unchanged
elem.replaceChild(e, e)
self.confirm(e.parentNode is elem, "After replaceChild()")
def testReplaceWholeText(self):
def setup():
doc = parseString("<doc>a<e/>d</doc>")
@ -1107,25 +1107,25 @@ class MinidomTest(unittest.TestCase):
elem.insertBefore(doc.createTextNode("b"), splitter)
elem.insertBefore(doc.createCDATASection("c"), text1)
return doc, elem, text1, splitter, text2
doc, elem, text1, splitter, text2 = setup()
text = text1.replaceWholeText("new content")
self.checkWholeText(text, "new content")
self.checkWholeText(text2, "d")
self.confirm(len(elem.childNodes) == 3)
doc, elem, text1, splitter, text2 = setup()
text = text2.replaceWholeText("new content")
self.checkWholeText(text, "new content")
self.checkWholeText(text1, "cab")
self.confirm(len(elem.childNodes) == 5)
doc, elem, text1, splitter, text2 = setup()
text = text1.replaceWholeText("")
self.checkWholeText(text2, "d")
self.confirm(text is None
and len(elem.childNodes) == 2)
def testSchemaType(self):
doc = parseString(
"<!DOCTYPE doc [\n"
@ -1158,7 +1158,7 @@ class MinidomTest(unittest.TestCase):
t = a.schemaType
self.confirm(hasattr(t, "name")
and t.namespace == xml.dom.EMPTY_NAMESPACE)
def testSetIdAttribute(self):
doc = parseString("<doc a1='v' a2='w'/>")
e = doc.documentElement
@ -1189,7 +1189,7 @@ class MinidomTest(unittest.TestCase):
doc.renameNode(a2, xml.dom.EMPTY_NAMESPACE, "an")
self.confirm(e.isSameNode(doc.getElementById("w"))
and a2.isId)
def testSetIdAttributeNS(self):
NS1 = "http://xml.python.org/ns1"
NS2 = "http://xml.python.org/ns2"
@ -1309,6 +1309,6 @@ class MinidomTest(unittest.TestCase):
def test_main():
run_unittest(MinidomTest)
if __name__ == "__main__":
test_main()

View File

@ -56,6 +56,6 @@ class ModuleTests(unittest.TestCase):
def test_main():
run_unittest(ModuleTests)
if __name__ == '__main__':
test_main()

View File

@ -29,7 +29,7 @@ def unistr(data):
if x > sys.maxunicode:
raise RangeError
return u"".join([unichr(x) for x in data])
class NormalizationTest(unittest.TestCase):
def test_main(self):
part1_data = {}

View File

@ -281,7 +281,7 @@ class WalkTests(unittest.TestCase):
from os.path import join
# Build:
# TESTFN/
# TESTFN/
# TEST1/ a file kid and two directory kids
# tmp1
# SUB1/ a file kid and a directory kid

View File

@ -45,7 +45,7 @@ class Popen2Test(unittest.TestCase):
inst.wait()
popen2._cleanup()
self.assertFalse(popen2._active, "_active not empty")
reap_children()
reap_children()
def validate_output(self, teststr, expected_out, r, w, e=None):
w.write(teststr)
@ -57,7 +57,7 @@ class Popen2Test(unittest.TestCase):
if e is not None:
got = e.read()
self.assertFalse(got, "unexpected %r on stderr" % got)
def test_popen2(self):
r, w = popen2.popen2(self.cmd)
self.validate_output(self.teststr, self.expected, r, w)
@ -84,7 +84,7 @@ class Popen2Test(unittest.TestCase):
w, r, e = os.popen3(self.cmd)
self.validate_output(self.teststr, self.expected, r, w, e)
def test_main():
run_unittest(Popen2Test)

View File

@ -25,7 +25,7 @@ def server(evt):
evt.set()
class GeneralTests(TestCase):
def setUp(self):
self.evt = threading.Event()
threading.Thread(target=server, args=(self.evt,)).start()
@ -38,13 +38,13 @@ class GeneralTests(TestCase):
# connects
pop = poplib.POP3("localhost", 9091)
pop.sock.close()
def testTimeoutDefault(self):
# default
pop = poplib.POP3("localhost", 9091)
self.assertTrue(pop.sock.gettimeout() is None)
pop.sock.close()
def testTimeoutValue(self):
# a value
pop = poplib.POP3("localhost", 9091, timeout=30)

View File

@ -19,12 +19,12 @@ class SetAttributeTest(unittest.TestCase):
[2, 1],
[0, 0],
]
def test_returns_unicode(self):
for x, y in self.set_get_pairs:
self.parser.returns_unicode = x
self.assertEquals(self.parser.returns_unicode, y)
def test_ordered_attributes(self):
for x, y in self.set_get_pairs:
self.parser.ordered_attributes = x
@ -64,57 +64,57 @@ class ParseTest(unittest.TestCase):
class Outputter:
def __init__(self):
self.out = []
def StartElementHandler(self, name, attrs):
self.out.append('Start element: ' + repr(name) + ' ' +
self.out.append('Start element: ' + repr(name) + ' ' +
sortdict(attrs))
def EndElementHandler(self, name):
self.out.append('End element: ' + repr(name))
def CharacterDataHandler(self, data):
data = data.strip()
if data:
self.out.append('Character data: ' + repr(data))
def ProcessingInstructionHandler(self, target, data):
self.out.append('PI: ' + repr(target) + ' ' + repr(data))
def StartNamespaceDeclHandler(self, prefix, uri):
self.out.append('NS decl: ' + repr(prefix) + ' ' + repr(uri))
def EndNamespaceDeclHandler(self, prefix):
self.out.append('End of NS decl: ' + repr(prefix))
def StartCdataSectionHandler(self):
self.out.append('Start of CDATA section')
def EndCdataSectionHandler(self):
self.out.append('End of CDATA section')
def CommentHandler(self, text):
self.out.append('Comment: ' + repr(text))
def NotationDeclHandler(self, *args):
name, base, sysid, pubid = args
self.out.append('Notation declared: %s' %(args,))
def UnparsedEntityDeclHandler(self, *args):
entityName, base, systemId, publicId, notationName = args
self.out.append('Unparsed entity decl: %s' %(args,))
def NotStandaloneHandler(self, userData):
self.out.append('Not standalone')
return 1
def ExternalEntityRefHandler(self, *args):
context, base, sysId, pubId = args
self.out.append('External entity ref: %s' %(args[1:],))
return 1
def DefaultHandler(self, userData):
pass
def DefaultHandlerExpand(self, userData):
pass
@ -129,7 +129,7 @@ class ParseTest(unittest.TestCase):
#'NotStandaloneHandler',
'ExternalEntityRefHandler'
]
def test_utf8(self):
out = self.Outputter()
@ -138,7 +138,7 @@ class ParseTest(unittest.TestCase):
setattr(parser, name, getattr(out, name))
parser.returns_unicode = 0
parser.Parse(data, 1)
# Verify output
op = out.out
self.assertEquals(op[0], 'PI: \'xml-stylesheet\' \'href="stylesheet.css"\'')
@ -166,7 +166,7 @@ class ParseTest(unittest.TestCase):
parser.returns_unicode = 1
for name in self.handler_names:
setattr(parser, name, getattr(out, name))
parser.Parse(data, 1)
op = out.out
@ -196,7 +196,7 @@ class ParseTest(unittest.TestCase):
for name in self.handler_names:
setattr(parser, name, getattr(out, name))
file = StringIO.StringIO(data)
parser.ParseFile(file)
op = out.out
@ -226,15 +226,15 @@ class NamespaceSeparatorTest(unittest.TestCase):
expat.ParserCreate()
expat.ParserCreate(namespace_separator=None)
expat.ParserCreate(namespace_separator=' ')
def test_illegal(self):
try:
expat.ParserCreate(namespace_separator=42)
self.fail()
except TypeError, e:
self.assertEquals(str(e),
self.assertEquals(str(e),
'ParserCreate() argument 2 must be string or None, not int')
try:
expat.ParserCreate(namespace_separator='too long')
self.fail()
@ -277,7 +277,7 @@ class BufferTextTest(unittest.TestCase):
self.parser = expat.ParserCreate()
self.parser.buffer_text = 1
self.parser.CharacterDataHandler = self.CharacterDataHandler
def check(self, expected, label):
self.assertEquals(self.stuff, expected,
"%s\nstuff = %r\nexpected = %r"
@ -307,12 +307,12 @@ class BufferTextTest(unittest.TestCase):
def test_default_to_disabled(self):
parser = expat.ParserCreate()
self.assertFalse(parser.buffer_text)
def test_buffering_enabled(self):
# Make sure buffering is turned on
self.assertTrue(self.parser.buffer_text)
self.parser.Parse("<a>1<b/>2<c/>3</a>", 1)
self.assertEquals(self.stuff, ['123'],
self.assertEquals(self.stuff, ['123'],
"buffered text not properly collapsed")
def test1(self):
@ -320,10 +320,10 @@ class BufferTextTest(unittest.TestCase):
# XXX like, but it tests what we need to concisely.
self.setHandlers(["StartElementHandler"])
self.parser.Parse("<a>1<b buffer-text='no'/>2\n3<c buffer-text='yes'/>4\n5</a>", 1)
self.assertEquals(self.stuff,
self.assertEquals(self.stuff,
["<a>", "1", "<b>", "2", "\n", "3", "<c>", "4\n5"],
"buffering control not reacting as expected")
def test2(self):
self.parser.Parse("<a>1<b/>&lt;2&gt;<c/>&#32;\n&#x20;3</a>", 1)
self.assertEquals(self.stuff, ["1<2> \n 3"],
@ -339,7 +339,7 @@ class BufferTextTest(unittest.TestCase):
self.setHandlers(["StartElementHandler", "EndElementHandler"])
self.parser.CharacterDataHandler = None
self.parser.Parse("<a>1<b/>2<c/>3</a>", 1)
self.assertEquals(self.stuff,
self.assertEquals(self.stuff,
["<a>", "<b>", "</b>", "<c>", "</c>", "</a>"])
def test5(self):
@ -349,11 +349,11 @@ class BufferTextTest(unittest.TestCase):
["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "3", "</a>"])
def test6(self):
self.setHandlers(["CommentHandler", "EndElementHandler",
self.setHandlers(["CommentHandler", "EndElementHandler",
"StartElementHandler"])
self.parser.Parse("<a>1<b/>2<c></c>345</a> ", 1)
self.assertEquals(self.stuff,
["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "345", "</a>"],
self.assertEquals(self.stuff,
["<a>", "1", "<b>", "</b>", "2", "<c>", "</c>", "345", "</a>"],
"buffered text not properly split")
def test7(self):
@ -399,7 +399,7 @@ class PositionTest(unittest.TestCase):
self.assertTrue(self.upto < len(self.expected_list),
'too many parser events')
expected = self.expected_list[self.upto]
self.assertEquals(pos, expected,
self.assertEquals(pos, expected,
'Expected position %s, got position %s' %(pos, expected))
self.upto += 1
@ -422,16 +422,16 @@ class sf1296433Test(unittest.TestCase):
xml = "<?xml version='1.0' encoding='iso8859'?><s>%s</s>" % ('a' * 1025)
# this one doesn't crash
#xml = "<?xml version='1.0'?><s>%s</s>" % ('a' * 10000)
class SpecificException(Exception):
pass
def handler(text):
raise SpecificException
parser = expat.ParserCreate()
parser.CharacterDataHandler = handler
self.assertRaises(Exception, parser.Parse, xml)

View File

@ -607,7 +607,7 @@ class ReTests(unittest.TestCase):
for typecode in 'cbBuhHiIlLfd':
a = array.array(typecode)
self.assertEqual(re.compile("bla").match(a), None)
self.assertEqual(re.compile("").match(a).groups(), ())
self.assertEqual(re.compile("").match(a).groups(), ())
def run_re_tests():
from test.re_tests import benchmarks, tests, SUCCEED, FAIL, SYNTAX_ERROR

View File

@ -36,7 +36,7 @@ class XmlTestBase(unittest.TestCase):
self.assertEquals(attrs.get("attrs", 25), 25)
self.assertEquals(attrs.items(), [])
self.assertEquals(attrs.values(), [])
def verify_empty_nsattrs(self, attrs):
self.assertRaises(KeyError, attrs.getValue, (ns_uri, "attr"))
self.assertRaises(KeyError, attrs.getValueByQName, "ns:attr")
@ -70,7 +70,7 @@ class XmlTestBase(unittest.TestCase):
self.assertEquals(attrs.getNameByQName("attr"), "attr")
self.assertEquals(attrs["attr"], "val")
self.assertEquals(attrs.getQNameByName("attr"), "attr")
class MakeParserTest(unittest.TestCase):
def test_make_parser2(self):
# Creating parsers several times in a row should succeed.
@ -100,11 +100,11 @@ class SaxutilsTest(unittest.TestCase):
# ===== escape
def test_escape_basic(self):
self.assertEquals(escape("Donald Duck & Co"), "Donald Duck &amp; Co")
def test_escape_all(self):
self.assertEquals(escape("<Donald Duck & Co>"),
"&lt;Donald Duck &amp; Co&gt;")
def test_escape_extra(self):
self.assertEquals(escape("Hei på deg", {"å" : "&aring;"}),
"Hei p&aring; deg")
@ -112,35 +112,35 @@ class SaxutilsTest(unittest.TestCase):
# ===== unescape
def test_unescape_basic(self):
self.assertEquals(unescape("Donald Duck &amp; Co"), "Donald Duck & Co")
def test_unescape_all(self):
self.assertEquals(unescape("&lt;Donald Duck &amp; Co&gt;"),
self.assertEquals(unescape("&lt;Donald Duck &amp; Co&gt;"),
"<Donald Duck & Co>")
def test_unescape_extra(self):
self.assertEquals(unescape("Hei på deg", {"å" : "&aring;"}),
self.assertEquals(unescape("Hei på deg", {"å" : "&aring;"}),
"Hei p&aring; deg")
def test_unescape_amp_extra(self):
self.assertEquals(unescape("&amp;foo;", {"&foo;": "splat"}), "&foo;")
# ===== quoteattr
def test_quoteattr_basic(self):
self.assertEquals(quoteattr("Donald Duck & Co"),
self.assertEquals(quoteattr("Donald Duck & Co"),
'"Donald Duck &amp; Co"')
def test_single_quoteattr(self):
self.assertEquals(quoteattr('Includes "double" quotes'),
'\'Includes "double" quotes\'')
def test_double_quoteattr(self):
self.assertEquals(quoteattr("Includes 'single' quotes"),
"\"Includes 'single' quotes\"")
def test_single_double_quoteattr(self):
self.assertEquals(quoteattr("Includes 'single' and \"double\" quotes"),
"\"Includes 'single' and &quot;double&quot; quotes\"")
# ===== make_parser
def test_make_parser(self):
# Creating a parser should succeed - it should fall back
@ -160,19 +160,19 @@ class XmlgenTest(unittest.TestCase):
gen.startElement("doc", {})
gen.endElement("doc")
gen.endDocument()
self.assertEquals(result.getvalue(), start + "<doc></doc>")
def test_xmlgen_content(self):
result = StringIO()
gen = XMLGenerator(result)
gen.startDocument()
gen.startElement("doc", {})
gen.characters("huhei")
gen.endElement("doc")
gen.endDocument()
self.assertEquals(result.getvalue(), start + "<doc>huhei</doc>")
def test_xmlgen_pi(self):
@ -197,7 +197,7 @@ class XmlgenTest(unittest.TestCase):
gen.endElement("doc")
gen.endDocument()
self.assertEquals(result.getvalue(),
self.assertEquals(result.getvalue(),
start + "<doc>&lt;huhei&amp;</doc>")
def test_xmlgen_attr_escape(self):
@ -215,7 +215,7 @@ class XmlgenTest(unittest.TestCase):
gen.endElement("doc")
gen.endDocument()
self.assertEquals(result.getvalue(), start +
self.assertEquals(result.getvalue(), start +
("<doc a='\"'><e a=\"'\"></e>"
"<e a=\"'&quot;\"></e>"
"<e a=\"&#10;&#13;&#9;\"></e></doc>"))
@ -285,7 +285,7 @@ class XmlgenTest(unittest.TestCase):
gen.endPrefixMapping('my')
gen.endDocument()
self.assertEquals(result.getvalue(),
self.assertEquals(result.getvalue(),
start+'<my:a xmlns:my="qux" b="c"></my:a>')
@ -314,7 +314,7 @@ class XMLFilterBaseTest(unittest.TestCase):
xml_test_out = open(findfile("test"+os.extsep+"xml"+os.extsep+"out")).read()
class ExpatReaderTest(XmlTestBase):
# ===== XMLReader support
def test_expat_file(self):
@ -353,7 +353,7 @@ class ExpatReaderTest(XmlTestBase):
parser.feed('<doc></doc>')
parser.close()
self.assertEquals(handler._notations,
self.assertEquals(handler._notations,
[("GIF", "-//CompuServe//NOTATION Graphics Interchange Format 89a//EN", None)])
self.assertEquals(handler._entities, [("img", None, "expat.gif", "GIF")])
@ -378,7 +378,7 @@ class ExpatReaderTest(XmlTestBase):
parser.feed('<doc>&test;</doc>')
parser.close()
self.assertEquals(result.getvalue(), start +
self.assertEquals(result.getvalue(), start +
"<doc><entity></entity></doc>")
# ===== Attributes support
@ -433,7 +433,7 @@ class ExpatReaderTest(XmlTestBase):
self.assertEquals(attrs.getLength(), 1)
self.assertEquals(attrs.getNames(), [(ns_uri, "attr")])
self.assertTrue((attrs.getQNames() == [] or
self.assertTrue((attrs.getQNames() == [] or
attrs.getQNames() == ["ns:attr"]))
self.assertEquals(len(attrs), 1)
self.assertTrue(attrs.has_key((ns_uri, "attr")))
@ -445,101 +445,101 @@ class ExpatReaderTest(XmlTestBase):
self.assertEquals(attrs[(ns_uri, "attr")], "val")
# ===== InputSource support
def test_expat_inpsource_filename(self):
parser = create_parser()
result = StringIO()
xmlgen = XMLGenerator(result)
parser.setContentHandler(xmlgen)
parser.parse(findfile("test"+os.extsep+"xml"))
self.assertEquals(result.getvalue(), xml_test_out)
def test_expat_inpsource_sysid(self):
parser = create_parser()
result = StringIO()
xmlgen = XMLGenerator(result)
parser.setContentHandler(xmlgen)
parser.parse(InputSource(findfile("test"+os.extsep+"xml")))
self.assertEquals(result.getvalue(), xml_test_out)
def test_expat_inpsource_stream(self):
parser = create_parser()
result = StringIO()
xmlgen = XMLGenerator(result)
parser.setContentHandler(xmlgen)
inpsrc = InputSource()
inpsrc.setByteStream(open(findfile("test"+os.extsep+"xml")))
parser.parse(inpsrc)
self.assertEquals(result.getvalue(), xml_test_out)
# ===== IncrementalParser support
def test_expat_incremental(self):
result = StringIO()
xmlgen = XMLGenerator(result)
parser = create_parser()
parser.setContentHandler(xmlgen)
parser.feed("<doc>")
parser.feed("</doc>")
parser.close()
self.assertEquals(result.getvalue(), start + "<doc></doc>")
def test_expat_incremental_reset(self):
result = StringIO()
xmlgen = XMLGenerator(result)
parser = create_parser()
parser.setContentHandler(xmlgen)
parser.feed("<doc>")
parser.feed("text")
result = StringIO()
xmlgen = XMLGenerator(result)
parser.setContentHandler(xmlgen)
parser.reset()
parser.feed("<doc>")
parser.feed("text")
parser.feed("</doc>")
parser.close()
self.assertEquals(result.getvalue(), start + "<doc>text</doc>")
# ===== Locator support
def test_expat_locator_noinfo(self):
result = StringIO()
xmlgen = XMLGenerator(result)
parser = create_parser()
parser.setContentHandler(xmlgen)
parser.feed("<doc>")
parser.feed("</doc>")
parser.close()
self.assertEquals(parser.getSystemId(), None)
self.assertEquals(parser.getPublicId(), None)
self.assertEquals(parser.getLineNumber(), 1)
def test_expat_locator_withinfo(self):
result = StringIO()
xmlgen = XMLGenerator(result)
parser = create_parser()
parser.setContentHandler(xmlgen)
parser.parse(findfile("test.xml"))
self.assertEquals(parser.getSystemId(), findfile("test.xml"))
self.assertEquals(parser.getPublicId(), None)
# ===========================================================================
#
# error reporting
@ -559,12 +559,12 @@ class ErrorReportingTest(unittest.TestCase):
self.fail()
except SAXException, e:
self.assertEquals(e.getSystemId(), name)
def test_expat_incomplete(self):
parser = create_parser()
parser.setContentHandler(ContentHandler()) # do nothing
self.assertRaises(SAXParseException, parser.parse, StringIO("<foo>"))
def test_sax_parse_exception_str(self):
# pass various values from a locator to the SAXParseException to
# make sure that the __str__() doesn't fall apart when None is
@ -582,21 +582,21 @@ class ErrorReportingTest(unittest.TestCase):
# use None for both:
str(SAXParseException("message", None,
self.DummyLocator(None, None)))
class DummyLocator:
def __init__(self, lineno, colno):
self._lineno = lineno
self._colno = colno
def getPublicId(self):
return "pubid"
def getSystemId(self):
return "sysid"
def getLineNumber(self):
return self._lineno
def getColumnNumber(self):
return self._colno
@ -607,21 +607,21 @@ class ErrorReportingTest(unittest.TestCase):
# ===========================================================================
class XmlReaderTest(XmlTestBase):
# ===== AttributesImpl
def test_attrs_empty(self):
self.verify_empty_attrs(AttributesImpl({}))
def test_attrs_wattr(self):
self.verify_attrs_wattr(AttributesImpl({"attr" : "val"}))
def test_nsattrs_empty(self):
self.verify_empty_nsattrs(AttributesNSImpl({}, {}))
def test_nsattrs_wattr(self):
attrs = AttributesNSImpl({(ns_uri, "attr") : "val"},
{(ns_uri, "attr") : "ns:attr"})
self.assertEquals(attrs.getLength(), 1)
self.assertEquals(attrs.getNames(), [(ns_uri, "attr")])
self.assertEquals(attrs.getQNames(), ["ns:attr"])
@ -661,7 +661,7 @@ class XmlReaderTest(XmlTestBase):
# attempt. Keeping these tests around will help detect problems with
# other attempts to provide reliable access to the standard library's
# implementation of the XML support.
def test_sf_1511497(self):
# Bug report: http://www.python.org/sf/1511497
import sys
@ -675,7 +675,7 @@ class XmlReaderTest(XmlTestBase):
self.assertEquals(module.__name__, "xml.sax.expatreader")
finally:
sys.modules.update(old_modules)
def test_sf_1513611(self):
# Bug report: http://www.python.org/sf/1513611
sio = StringIO("invalid")
@ -693,4 +693,4 @@ def unittest_main():
XmlReaderTest)
if __name__ == "__main__":
unittest_main()
unittest_main()

View File

@ -288,7 +288,7 @@ class TestJointOps(unittest.TestCase):
self.assertEqual(sum(elem.hash_count for elem in d), n)
if hasattr(s, 'symmetric_difference_update'):
s.symmetric_difference_update(d)
self.assertEqual(sum(elem.hash_count for elem in d), n)
self.assertEqual(sum(elem.hash_count for elem in d), n)
d2 = dict.fromkeys(set(d))
self.assertEqual(sum(elem.hash_count for elem in d), n)
d3 = dict.fromkeys(frozenset(d))

View File

@ -25,7 +25,7 @@ def server(evt):
evt.set()
class GeneralTests(TestCase):
def setUp(self):
self.evt = threading.Event()
threading.Thread(target=server, args=(self.evt,)).start()
@ -38,13 +38,13 @@ class GeneralTests(TestCase):
# connects
smtp = smtplib.SMTP("localhost", 9091)
smtp.sock.close()
def testTimeoutDefault(self):
# default
smtp = smtplib.SMTP("localhost", 9091)
self.assertTrue(smtp.sock.gettimeout() is None)
smtp.sock.close()
def testTimeoutValue(self):
# a value
smtp = smtplib.SMTP("localhost", 9091, timeout=30)

View File

@ -822,7 +822,7 @@ class NetworkConnectionTest(object):
def clientSetUp(self):
self.cli = socket.create_connection((HOST, PORT))
self.serv_conn = self.cli
class BasicTCPTest2(NetworkConnectionTest, BasicTCPTest):
"""Tests that NetworkConnection does not break existing TCP functionality.
"""
@ -853,22 +853,22 @@ class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
self.cli = socket.create_connection((HOST, PORT), timeout=30)
self.assertEqual(self.cli.family, 2)
testTimeoutDefault = _justAccept
testTimeoutDefault = _justAccept
def _testTimeoutDefault(self):
self.cli = socket.create_connection((HOST, PORT))
self.assertTrue(self.cli.gettimeout() is None)
testTimeoutValueNamed = _justAccept
testTimeoutValueNamed = _justAccept
def _testTimeoutValueNamed(self):
self.cli = socket.create_connection((HOST, PORT), timeout=30)
self.assertEqual(self.cli.gettimeout(), 30)
testTimeoutValueNonamed = _justAccept
testTimeoutValueNonamed = _justAccept
def _testTimeoutValueNonamed(self):
self.cli = socket.create_connection((HOST, PORT), 30)
self.assertEqual(self.cli.gettimeout(), 30)
testTimeoutNone = _justAccept
testTimeoutNone = _justAccept
def _testTimeoutNone(self):
previous = socket.getdefaulttimeout()
socket.setdefaulttimeout(30)

View File

@ -25,12 +25,12 @@ class ConnectedTests(unittest.TestCase):
else:
print "didn't raise TypeError"
socket.RAND_add("this is a random string", 75.0)
with test_support.transient_internet():
f = urllib.urlopen('https://sf.net')
buf = f.read()
f.close()
def testTimeout(self):
def error_msg(extra_msg):
print >> sys.stderr, """\
@ -38,14 +38,14 @@ class ConnectedTests(unittest.TestCase):
test_timeout. That may be legitimate, but is not the outcome we
hoped for. If this message is seen often, test_timeout should be
changed to use a more reliable address.""" % (ADDR, extra_msg)
# A service which issues a welcome banner (without need to write
# anything).
# XXX ("gmail.org", 995) has been unreliable so far, from time to
# XXX time non-responsive for hours on end (& across all buildbot
# XXX time non-responsive for hours on end (& across all buildbot
# XXX slaves, so that's not just a local thing).
ADDR = "gmail.org", 995
s = socket.socket()
s.settimeout(30.0)
try:
@ -59,7 +59,7 @@ class ConnectedTests(unittest.TestCase):
return
else:
raise
ss = socket.ssl(s)
# Read part of return welcome banner twice.
ss.read(1)
@ -71,11 +71,11 @@ class BasicTests(unittest.TestCase):
def testRudeShutdown(self):
# Some random port to connect to.
PORT = [9934]
listener_ready = threading.Event()
listener_gone = threading.Event()
# `listener` runs in a thread. It opens a socket listening on
# `listener` runs in a thread. It opens a socket listening on
# PORT, and sits in an accept() until the main thread connects.
# Then it rudely closes the socket, and sets Event `listener_gone`
# to let the main thread know the socket is gone.
@ -87,7 +87,7 @@ class BasicTests(unittest.TestCase):
s.accept()
s = None # reclaim the socket object, which also closes it
listener_gone.set()
def connector():
listener_ready.wait()
s = socket.socket()
@ -100,7 +100,7 @@ class BasicTests(unittest.TestCase):
else:
raise test_support.TestFailed(
'connecting to closed SSL socket should have failed')
t = threading.Thread(target=listener)
t.start()
connector()
@ -153,8 +153,8 @@ class OpenSSLServer(threading.Thread):
try:
cmd = "openssl s_server -cert %s -key %s -quiet" % (cert_file, key_file)
self.s = subprocess.Popen(cmd.split(), stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
self.s = subprocess.Popen(cmd.split(), stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.STDOUT)
time.sleep(1)
except:
@ -171,7 +171,7 @@ class OpenSSLServer(threading.Thread):
self.haveServer = False
else:
self.haveServer = True
def run(self):
while self.keepServing:
time.sleep(.5)
@ -186,7 +186,7 @@ class OpenSSLServer(threading.Thread):
subprocess.TerminateProcess(int(self.s._handle), -1)
else:
os.kill(self.s.pid, 15)
def test_main():
if not hasattr(socket, "ssl"):
raise test_support.TestSkipped("socket module has no ssl support")

View File

@ -15,9 +15,9 @@ class SoftspaceTests(unittest.TestCase):
print >> f, 'f', 'g'
# In 2.2 & earlier, this printed ' a\nbc d\te\nf g\n'
self.assertEqual(f.getvalue(), 'a\nb c d\te\nf g\n')
def test_main():
run_unittest(SoftspaceTests)
if __name__ == '__main__':
test_main()

View File

@ -91,6 +91,6 @@ class StringprepTests(unittest.TestCase):
def test_main():
test_support.run_unittest(StringprepTests)
if __name__ == '__main__':
test_main()

View File

@ -376,7 +376,7 @@ leading to spurious errors.
... elif 1:
... pass
Traceback (most recent call last):
...
...
SyntaxError: can't assign to function call (<doctest test.test_syntax[44]>, line 2)
>>> if 1:
@ -384,7 +384,7 @@ leading to spurious errors.
... elif 1:
... x() = 1
Traceback (most recent call last):
...
...
SyntaxError: can't assign to function call (<doctest test.test_syntax[45]>, line 4)
>>> if 1:
@ -394,7 +394,7 @@ leading to spurious errors.
... else:
... pass
Traceback (most recent call last):
...
...
SyntaxError: can't assign to function call (<doctest test.test_syntax[46]>, line 2)
>>> if 1:
@ -404,7 +404,7 @@ leading to spurious errors.
... else:
... pass
Traceback (most recent call last):
...
...
SyntaxError: can't assign to function call (<doctest test.test_syntax[47]>, line 4)
>>> if 1:
@ -414,7 +414,7 @@ leading to spurious errors.
... else:
... x() = 1
Traceback (most recent call last):
...
...
SyntaxError: can't assign to function call (<doctest test.test_syntax[48]>, line 6)
"""

View File

@ -987,4 +987,3 @@ def test_main():
if __name__ == "__main__":
test_main()

View File

@ -22,7 +22,7 @@ def server(evt):
evt.set()
class GeneralTests(TestCase):
def setUp(self):
self.evt = threading.Event()
threading.Thread(target=server, args=(self.evt,)).start()
@ -35,13 +35,13 @@ class GeneralTests(TestCase):
# connects
telnet = telnetlib.Telnet("localhost", 9091)
telnet.sock.close()
def testTimeoutDefault(self):
# default
telnet = telnetlib.Telnet("localhost", 9091)
self.assertTrue(telnet.sock.gettimeout() is None)
telnet.sock.close()
def testTimeoutValue(self):
# a value
telnet = telnetlib.Telnet("localhost", 9091, timeout=30)

View File

@ -514,7 +514,7 @@ class OtherTests(unittest.TestCase):
# version of .testzip would swallow this exception (and any other)
# and report that the first file in the archive was corrupt.
self.assertRaises(RuntimeError, zipf.testzip)
def tearDown(self):
support.unlink(TESTFN)
support.unlink(TESTFN2)
@ -568,7 +568,7 @@ class TestsWithRandomBinaryFiles(unittest.TestCase):
fp = open(TESTFN, "wb")
fp.write(self.data)
fp.close()
def tearDown(self):
support.unlink(TESTFN)
support.unlink(TESTFN2)

View File

@ -223,13 +223,13 @@ class Timer:
def timeit(stmt="pass", setup="pass", timer=default_timer,
number=default_number):
"""Convenience function to create Timer object and call timeit method."""
return Timer(stmt, setup, timer).timeit(number)
"""Convenience function to create Timer object and call timeit method."""
return Timer(stmt, setup, timer).timeit(number)
def repeat(stmt="pass", setup="pass", timer=default_timer,
repeat=default_repeat, number=default_number):
"""Convenience function to create Timer object and call repeat method."""
return Timer(stmt, setup, timer).repeat(repeat, number)
"""Convenience function to create Timer object and call repeat method."""
return Timer(stmt, setup, timer).repeat(repeat, number)
def main(args=None):
"""Main program, used when run as a script.

View File

@ -490,7 +490,7 @@ class HTTPErrorProcessor(BaseHandler):
def http_response(self, request, response):
code, msg, hdrs = response.code, response.msg, response.info()
# According to RFC 2616, "2xx" code indicates that the client's
# According to RFC 2616, "2xx" code indicates that the client's
# request was successfully received, understood, and accepted.
if not (200 <= code < 300):
response = self.parent.error(