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) _check_size(c_void_p)
class c_bool(_SimpleCData): class c_bool(_SimpleCData):
_type_ = "t" _type_ = "t"
# This cache maps types to pointers to them. # This cache maps types to pointers to them.
_pointer_type_cache = {} _pointer_type_cache = {}

View file

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

View file

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

View file

@ -84,7 +84,7 @@ class FTP:
meaning that no timeout will be set on any ftp socket(s) 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 If a timeout is passed, then this is now the default timeout for all ftp
socket operations for this instance. socket operations for this instance.
Then use self.connect() with optional host and port argument. Then use self.connect() with optional host and port argument.
To download a file, use ftp.retrlines('RETR ' + filename), To download a file, use ftp.retrlines('RETR ' + filename),
@ -112,7 +112,7 @@ class FTP:
self.timeout = timeout self.timeout = timeout
if host: if host:
self.connect(host) self.connect(host)
if user: if user:
self.login(user, passwd, acct) self.login(user, passwd, acct)
def connect(self, host='', port=0, timeout=None): 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): def _runscript(self, filename):
# The script has to run in __main__ namespace (or imports from # The script has to run in __main__ namespace (or imports from
# __main__ will break). # __main__ will break).
# #
# So we clear up the __main__ and set several special variables # So we clear up the __main__ and set several special variables
# (this gets rid of pdb's globals and cleans old variables on restarts). # (this gets rid of pdb's globals and cleans old variables on restarts).
import __main__ import __main__
@ -1158,7 +1158,7 @@ see no sign that the breakpoint was reached.
"__file__" : filename, "__file__" : filename,
"__builtins__": __builtins__, "__builtins__": __builtins__,
}) })
# When bdb sets tracing, a number of call and line events happens # When bdb sets tracing, a number of call and line events happens
# BEFORE debugger even reaches user's code (and the exact sequence of # BEFORE debugger even reaches user's code (and the exact sequence of
# events depends on python version). So we take special measures to # 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.mainpyfile = self.canonic(filename)
self._user_requested_quit = 0 self._user_requested_quit = 0
statement = 'execfile( "%s")' % filename statement = 'execfile( "%s")' % filename
self.run(statement) self.run(statement)
# Simplified interface # Simplified interface

View file

@ -388,10 +388,10 @@ def relpath(path, start=curdir):
if not path: if not path:
raise ValueError("no path specified") raise ValueError("no path specified")
start_list = abspath(start).split(sep) start_list = abspath(start).split(sep)
path_list = abspath(path).split(sep) path_list = abspath(path).split(sep)
# Work out how much of the filepath is shared by start and path. # Work out how much of the filepath is shared by start and path.
i = len(commonprefix([start_list, path_list])) 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) ssl() -- secure socket layer support (only available if configured)
socket.getdefaulttimeout() -- get the default timeout value socket.getdefaulttimeout() -- get the default timeout value
socket.setdefaulttimeout() -- set 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! [*] not available on all platforms!
@ -418,12 +418,12 @@ class _fileobject(object):
def create_connection(address, timeout=None): def create_connection(address, timeout=None):
"""Connect to address (host, port) with an optional timeout. """Connect to address (host, port) with an optional timeout.
Provides access to socketobject timeout for higher-level Provides access to socketobject timeout for higher-level
protocols. Passing a timeout will set the timeout on the protocols. Passing a timeout will set the timeout on the
socket instance (if not present, or passed as None, the socket instance (if not present, or passed as None, the
default global timeout setting will be used). default global timeout setting will be used).
""" """
msg = "getaddrinfo returns an empty list" msg = "getaddrinfo returns an empty list"
host, port = address host, port = address
for res in getaddrinfo(host, port, 0, SOCK_STREAM): for res in getaddrinfo(host, port, 0, SOCK_STREAM):
@ -435,7 +435,7 @@ def create_connection(address, timeout=None):
sock.settimeout(timeout) sock.settimeout(timeout)
sock.connect(sa) sock.connect(sa)
return sock return sock
except error, msg: except error, msg:
if sock is not None: if sock is not None:
sock.close() sock.close()

View file

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

View file

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

View file

@ -1096,9 +1096,9 @@ class MixinStrStringUserStringTest:
self.checkequal('Abc', 'abc', 'translate', table) self.checkequal('Abc', 'abc', 'translate', table)
self.checkequal('xyz', 'xyz', 'translate', table) self.checkequal('xyz', 'xyz', 'translate', table)
self.checkequal('yz', 'xyz', 'translate', table, 'x') 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.checkequal('zyzzx', 'zyzzx', 'translate', None)
self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip') self.checkraises(ValueError, 'xyz', 'translate', 'too short', 'strip')
self.checkraises(ValueError, 'xyz', 'translate', 'too short') self.checkraises(ValueError, 'xyz', 'translate', 'too short')

View file

@ -1248,7 +1248,7 @@ def slots():
c.abc = 5 c.abc = 5
vereq(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")) slots = (unicode("foo"), unicode("bar"))
class C(object): class C(object):
__slots__ = slots __slots__ = slots
@ -1263,7 +1263,7 @@ def slots():
except (TypeError, UnicodeEncodeError): except (TypeError, UnicodeEncodeError):
pass pass
else: else:
raise TestFailed, "[unichr(128)] slots not caught" raise TestFailed, "[unichr(128)] slots not caught"
# Test leaks # Test leaks
class Counted(object): 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): def remove_tempfiles(*names):
for name in names: for name in names:
safe_unlink(name) safe_unlink(name)
class BufferSizesTests(unittest.TestCase): class BufferSizesTests(unittest.TestCase):
def test_buffer_sizes(self): def test_buffer_sizes(self):
# First, run the tests with default and teeny buffer size. # 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) self.buffer_size_test(t1, t2, t3, t4, bs, round)
finally: finally:
remove_tempfiles(t1, t2, t3, t4) remove_tempfiles(t1, t2, t3, t4)
def buffer_size_test(self, t1, t2, t3, t4, bs=0, round=0): def buffer_size_test(self, t1, t2, t3, t4, bs=0, round=0):
pat = re.compile(r'LINE (\d+) OF FILE (\d+)') pat = re.compile(r'LINE (\d+) OF FILE (\d+)')
start = 1 + round*6 start = 1 + round*6
if verbose: if verbose:
print '%s. Simple iteration (bs=%s)' % (start+0, bs) print '%s. Simple iteration (bs=%s)' % (start+0, bs)
@ -117,7 +117,7 @@ class BufferSizesTests(unittest.TestCase):
self.assertNotEqual(m, None) self.assertNotEqual(m, None)
self.assertEqual(int(m.group(1)), fi.filelineno()) self.assertEqual(int(m.group(1)), fi.filelineno())
fi.close() fi.close()
class FileInputTests(unittest.TestCase): class FileInputTests(unittest.TestCase):
def test_zero_byte_files(self): def test_zero_byte_files(self):
try: try:
@ -126,13 +126,13 @@ class FileInputTests(unittest.TestCase):
t3 = writeTmp(3, ["The only line there is.\n"]) t3 = writeTmp(3, ["The only line there is.\n"])
t4 = writeTmp(4, [""]) t4 = writeTmp(4, [""])
fi = FileInput(files=(t1, t2, t3, t4)) fi = FileInput(files=(t1, t2, t3, t4))
line = fi.readline() line = fi.readline()
self.assertEqual(line, 'The only line there is.\n') self.assertEqual(line, 'The only line there is.\n')
self.assertEqual(fi.lineno(), 1) self.assertEqual(fi.lineno(), 1)
self.assertEqual(fi.filelineno(), 1) self.assertEqual(fi.filelineno(), 1)
self.assertEqual(fi.filename(), t3) self.assertEqual(fi.filename(), t3)
line = fi.readline() line = fi.readline()
self.failIf(line) self.failIf(line)
self.assertEqual(fi.lineno(), 1) self.assertEqual(fi.lineno(), 1)
@ -220,6 +220,6 @@ class FileInputTests(unittest.TestCase):
def test_main(): def test_main():
run_unittest(BufferSizesTests, FileInputTests) run_unittest(BufferSizesTests, FileInputTests)
if __name__ == "__main__": if __name__ == "__main__":
test_main() test_main()

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

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

View file

@ -22,7 +22,7 @@ def server(evt):
evt.set() evt.set()
class GeneralTests(TestCase): class GeneralTests(TestCase):
def setUp(self): def setUp(self):
self.evt = threading.Event() self.evt = threading.Event()
threading.Thread(target=server, args=(self.evt,)).start() threading.Thread(target=server, args=(self.evt,)).start()
@ -35,13 +35,13 @@ class GeneralTests(TestCase):
# connects # connects
telnet = telnetlib.Telnet("localhost", 9091) telnet = telnetlib.Telnet("localhost", 9091)
telnet.sock.close() telnet.sock.close()
def testTimeoutDefault(self): def testTimeoutDefault(self):
# default # default
telnet = telnetlib.Telnet("localhost", 9091) telnet = telnetlib.Telnet("localhost", 9091)
self.assertTrue(telnet.sock.gettimeout() is None) self.assertTrue(telnet.sock.gettimeout() is None)
telnet.sock.close() telnet.sock.close()
def testTimeoutValue(self): def testTimeoutValue(self):
# a value # a value
telnet = telnetlib.Telnet("localhost", 9091, timeout=30) 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) # version of .testzip would swallow this exception (and any other)
# and report that the first file in the archive was corrupt. # and report that the first file in the archive was corrupt.
self.assertRaises(RuntimeError, zipf.testzip) self.assertRaises(RuntimeError, zipf.testzip)
def tearDown(self): def tearDown(self):
support.unlink(TESTFN) support.unlink(TESTFN)
support.unlink(TESTFN2) support.unlink(TESTFN2)
@ -568,7 +568,7 @@ class TestsWithRandomBinaryFiles(unittest.TestCase):
fp = open(TESTFN, "wb") fp = open(TESTFN, "wb")
fp.write(self.data) fp.write(self.data)
fp.close() fp.close()
def tearDown(self): def tearDown(self):
support.unlink(TESTFN) support.unlink(TESTFN)
support.unlink(TESTFN2) support.unlink(TESTFN2)

View file

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

View file

@ -490,7 +490,7 @@ class HTTPErrorProcessor(BaseHandler):
def http_response(self, request, response): def http_response(self, request, response):
code, msg, hdrs = response.code, response.msg, response.info() 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. # request was successfully received, understood, and accepted.
if not (200 <= code < 300): if not (200 <= code < 300):
response = self.parent.error( response = self.parent.error(