#9424: Replace deprecated assert* methods in the Python test suite.

This commit is contained in:
Ezio Melotti 2010-11-20 19:04:17 +00:00
parent b8bc439b20
commit b3aedd4862
170 changed files with 2388 additions and 2392 deletions

View File

@ -4,19 +4,19 @@ import unittest
class SimpleTestCase(unittest.TestCase): class SimpleTestCase(unittest.TestCase):
def test_cint(self): def test_cint(self):
x = c_int() x = c_int()
self.assertEquals(x._objects, None) self.assertEqual(x._objects, None)
x.value = 42 x.value = 42
self.assertEquals(x._objects, None) self.assertEqual(x._objects, None)
x = c_int(99) x = c_int(99)
self.assertEquals(x._objects, None) self.assertEqual(x._objects, None)
def test_ccharp(self): def test_ccharp(self):
x = c_char_p() x = c_char_p()
self.assertEquals(x._objects, None) self.assertEqual(x._objects, None)
x.value = b"abc" x.value = b"abc"
self.assertEquals(x._objects, b"abc") self.assertEqual(x._objects, b"abc")
x = c_char_p(b"spam") x = c_char_p(b"spam")
self.assertEquals(x._objects, b"spam") self.assertEqual(x._objects, b"spam")
class StructureTestCase(unittest.TestCase): class StructureTestCase(unittest.TestCase):
def test_cint_struct(self): def test_cint_struct(self):
@ -25,21 +25,21 @@ class StructureTestCase(unittest.TestCase):
("b", c_int)] ("b", c_int)]
x = X() x = X()
self.assertEquals(x._objects, None) self.assertEqual(x._objects, None)
x.a = 42 x.a = 42
x.b = 99 x.b = 99
self.assertEquals(x._objects, None) self.assertEqual(x._objects, None)
def test_ccharp_struct(self): def test_ccharp_struct(self):
class X(Structure): class X(Structure):
_fields_ = [("a", c_char_p), _fields_ = [("a", c_char_p),
("b", c_char_p)] ("b", c_char_p)]
x = X() x = X()
self.assertEquals(x._objects, None) self.assertEqual(x._objects, None)
x.a = b"spam" x.a = b"spam"
x.b = b"foo" x.b = b"foo"
self.assertEquals(x._objects, {"0": b"spam", "1": b"foo"}) self.assertEqual(x._objects, {"0": b"spam", "1": b"foo"})
def test_struct_struct(self): def test_struct_struct(self):
class POINT(Structure): class POINT(Structure):
@ -52,28 +52,28 @@ class StructureTestCase(unittest.TestCase):
r.ul.y = 1 r.ul.y = 1
r.lr.x = 2 r.lr.x = 2
r.lr.y = 3 r.lr.y = 3
self.assertEquals(r._objects, None) self.assertEqual(r._objects, None)
r = RECT() r = RECT()
pt = POINT(1, 2) pt = POINT(1, 2)
r.ul = pt r.ul = pt
self.assertEquals(r._objects, {'0': {}}) self.assertEqual(r._objects, {'0': {}})
r.ul.x = 22 r.ul.x = 22
r.ul.y = 44 r.ul.y = 44
self.assertEquals(r._objects, {'0': {}}) self.assertEqual(r._objects, {'0': {}})
r.lr = POINT() r.lr = POINT()
self.assertEquals(r._objects, {'0': {}, '1': {}}) self.assertEqual(r._objects, {'0': {}, '1': {}})
class ArrayTestCase(unittest.TestCase): class ArrayTestCase(unittest.TestCase):
def test_cint_array(self): def test_cint_array(self):
INTARR = c_int * 3 INTARR = c_int * 3
ia = INTARR() ia = INTARR()
self.assertEquals(ia._objects, None) self.assertEqual(ia._objects, None)
ia[0] = 1 ia[0] = 1
ia[1] = 2 ia[1] = 2
ia[2] = 3 ia[2] = 3
self.assertEquals(ia._objects, None) self.assertEqual(ia._objects, None)
class X(Structure): class X(Structure):
_fields_ = [("x", c_int), _fields_ = [("x", c_int),
@ -83,9 +83,9 @@ class ArrayTestCase(unittest.TestCase):
x.x = 1000 x.x = 1000
x.a[0] = 42 x.a[0] = 42
x.a[1] = 96 x.a[1] = 96
self.assertEquals(x._objects, None) self.assertEqual(x._objects, None)
x.a = ia x.a = ia
self.assertEquals(x._objects, {'1': {}}) self.assertEqual(x._objects, {'1': {}})
class PointerTestCase(unittest.TestCase): class PointerTestCase(unittest.TestCase):
def test_p_cint(self): def test_p_cint(self):

View File

@ -113,7 +113,7 @@ class ArchiveUtilTestCase(support.TempdirManager,
self.assertTrue(os.path.exists(tarball2)) self.assertTrue(os.path.exists(tarball2))
# let's compare both tarballs # let's compare both tarballs
self.assertEquals(self._tarinfo(tarball), self._tarinfo(tarball2)) self.assertEqual(self._tarinfo(tarball), self._tarinfo(tarball2))
# trying an uncompressed one # trying an uncompressed one
base_name = os.path.join(tmpdir2, 'archive') base_name = os.path.join(tmpdir2, 'archive')
@ -153,7 +153,7 @@ class ArchiveUtilTestCase(support.TempdirManager,
os.chdir(old_dir) os.chdir(old_dir)
tarball = base_name + '.tar.Z' tarball = base_name + '.tar.Z'
self.assertTrue(os.path.exists(tarball)) self.assertTrue(os.path.exists(tarball))
self.assertEquals(len(w.warnings), 1) self.assertEqual(len(w.warnings), 1)
# same test with dry_run # same test with dry_run
os.remove(tarball) os.remove(tarball)
@ -167,7 +167,7 @@ class ArchiveUtilTestCase(support.TempdirManager,
finally: finally:
os.chdir(old_dir) os.chdir(old_dir)
self.assertTrue(not os.path.exists(tarball)) self.assertTrue(not os.path.exists(tarball))
self.assertEquals(len(w.warnings), 1) self.assertEqual(len(w.warnings), 1)
@unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run') @unittest.skipUnless(ZIP_SUPPORT, 'Need zip support to run')
def test_make_zipfile(self): def test_make_zipfile(self):
@ -184,9 +184,9 @@ class ArchiveUtilTestCase(support.TempdirManager,
tarball = base_name + '.zip' tarball = base_name + '.zip'
def test_check_archive_formats(self): def test_check_archive_formats(self):
self.assertEquals(check_archive_formats(['gztar', 'xxx', 'zip']), self.assertEqual(check_archive_formats(['gztar', 'xxx', 'zip']),
'xxx') 'xxx')
self.assertEquals(check_archive_formats(['gztar', 'zip']), None) self.assertEqual(check_archive_formats(['gztar', 'zip']), None)
def test_make_archive(self): def test_make_archive(self):
tmpdir = self.mkdtemp() tmpdir = self.mkdtemp()
@ -203,7 +203,7 @@ class ArchiveUtilTestCase(support.TempdirManager,
make_archive('xxx', 'xxx', root_dir=self.mkdtemp()) make_archive('xxx', 'xxx', root_dir=self.mkdtemp())
except: except:
pass pass
self.assertEquals(os.getcwd(), current_dir) self.assertEqual(os.getcwd(), current_dir)
finally: finally:
del ARCHIVE_FORMATS['xxx'] del ARCHIVE_FORMATS['xxx']

View File

@ -24,7 +24,7 @@ class BuildTestCase(support.TempdirManager,
cmd = bdist(dist) cmd = bdist(dist)
cmd.formats = ['msi'] cmd.formats = ['msi']
cmd.ensure_finalized() cmd.ensure_finalized()
self.assertEquals(cmd.formats, ['msi']) self.assertEqual(cmd.formats, ['msi'])
# what format bdist offers ? # what format bdist offers ?
# XXX an explicit list in bdist is # XXX an explicit list in bdist is
@ -35,7 +35,7 @@ class BuildTestCase(support.TempdirManager,
formats.sort() formats.sort()
founded = list(cmd.format_command.keys()) founded = list(cmd.format_command.keys())
founded.sort() founded.sort()
self.assertEquals(founded, formats) self.assertEqual(founded, formats)
def test_suite(): def test_suite():
return unittest.makeSuite(BuildTestCase) return unittest.makeSuite(BuildTestCase)

View File

@ -69,7 +69,7 @@ class BuildDumbTestCase(support.TempdirManager,
base = base.replace(':', '-') base = base.replace(':', '-')
wanted = ['%s.zip' % base] wanted = ['%s.zip' % base]
self.assertEquals(dist_created, wanted) self.assertEqual(dist_created, wanted)
# now let's check what we have in the zip file # now let's check what we have in the zip file
# XXX to be done # XXX to be done

View File

@ -18,11 +18,11 @@ class BuildTestCase(support.TempdirManager,
cmd.finalize_options() cmd.finalize_options()
# if not specified, plat_name gets the current platform # if not specified, plat_name gets the current platform
self.assertEquals(cmd.plat_name, get_platform()) self.assertEqual(cmd.plat_name, get_platform())
# build_purelib is build + lib # build_purelib is build + lib
wanted = os.path.join(cmd.build_base, 'lib') wanted = os.path.join(cmd.build_base, 'lib')
self.assertEquals(cmd.build_purelib, wanted) self.assertEqual(cmd.build_purelib, wanted)
# build_platlib is 'build/lib.platform-x.x[-pydebug]' # build_platlib is 'build/lib.platform-x.x[-pydebug]'
# examples: # examples:
@ -32,21 +32,21 @@ class BuildTestCase(support.TempdirManager,
self.assertTrue(cmd.build_platlib.endswith('-pydebug')) self.assertTrue(cmd.build_platlib.endswith('-pydebug'))
plat_spec += '-pydebug' plat_spec += '-pydebug'
wanted = os.path.join(cmd.build_base, 'lib' + plat_spec) wanted = os.path.join(cmd.build_base, 'lib' + plat_spec)
self.assertEquals(cmd.build_platlib, wanted) self.assertEqual(cmd.build_platlib, wanted)
# by default, build_lib = build_purelib # by default, build_lib = build_purelib
self.assertEquals(cmd.build_lib, cmd.build_purelib) self.assertEqual(cmd.build_lib, cmd.build_purelib)
# build_temp is build/temp.<plat> # build_temp is build/temp.<plat>
wanted = os.path.join(cmd.build_base, 'temp' + plat_spec) wanted = os.path.join(cmd.build_base, 'temp' + plat_spec)
self.assertEquals(cmd.build_temp, wanted) self.assertEqual(cmd.build_temp, wanted)
# build_scripts is build/scripts-x.x # build_scripts is build/scripts-x.x
wanted = os.path.join(cmd.build_base, 'scripts-' + sys.version[0:3]) wanted = os.path.join(cmd.build_base, 'scripts-' + sys.version[0:3])
self.assertEquals(cmd.build_scripts, wanted) self.assertEqual(cmd.build_scripts, wanted)
# executable is os.path.normpath(sys.executable) # executable is os.path.normpath(sys.executable)
self.assertEquals(cmd.executable, os.path.normpath(sys.executable)) self.assertEqual(cmd.executable, os.path.normpath(sys.executable))
def test_suite(): def test_suite():
return unittest.makeSuite(BuildTestCase) return unittest.makeSuite(BuildTestCase)

View File

@ -57,14 +57,14 @@ class BuildCLibTestCase(support.TempdirManager,
self.assertRaises(DistutilsSetupError, cmd.get_source_files) self.assertRaises(DistutilsSetupError, cmd.get_source_files)
cmd.libraries = [('name', {'sources': ['a', 'b']})] cmd.libraries = [('name', {'sources': ['a', 'b']})]
self.assertEquals(cmd.get_source_files(), ['a', 'b']) self.assertEqual(cmd.get_source_files(), ['a', 'b'])
cmd.libraries = [('name', {'sources': ('a', 'b')})] cmd.libraries = [('name', {'sources': ('a', 'b')})]
self.assertEquals(cmd.get_source_files(), ['a', 'b']) self.assertEqual(cmd.get_source_files(), ['a', 'b'])
cmd.libraries = [('name', {'sources': ('a', 'b')}), cmd.libraries = [('name', {'sources': ('a', 'b')}),
('name2', {'sources': ['c', 'd']})] ('name2', {'sources': ['c', 'd']})]
self.assertEquals(cmd.get_source_files(), ['a', 'b', 'c', 'd']) self.assertEqual(cmd.get_source_files(), ['a', 'b', 'c', 'd'])
def test_build_libraries(self): def test_build_libraries(self):
@ -93,11 +93,11 @@ class BuildCLibTestCase(support.TempdirManager,
cmd.include_dirs = 'one-dir' cmd.include_dirs = 'one-dir'
cmd.finalize_options() cmd.finalize_options()
self.assertEquals(cmd.include_dirs, ['one-dir']) self.assertEqual(cmd.include_dirs, ['one-dir'])
cmd.include_dirs = None cmd.include_dirs = None
cmd.finalize_options() cmd.finalize_options()
self.assertEquals(cmd.include_dirs, []) self.assertEqual(cmd.include_dirs, [])
cmd.distribution.libraries = 'WONTWORK' cmd.distribution.libraries = 'WONTWORK'
self.assertRaises(DistutilsSetupError, cmd.finalize_options) self.assertRaises(DistutilsSetupError, cmd.finalize_options)

View File

@ -96,11 +96,11 @@ class BuildExtTestCase(TempdirManager,
for attr in ('error', 'foo', 'new', 'roj'): for attr in ('error', 'foo', 'new', 'roj'):
self.assertTrue(hasattr(xx, attr)) self.assertTrue(hasattr(xx, attr))
self.assertEquals(xx.foo(2, 5), 7) self.assertEqual(xx.foo(2, 5), 7)
self.assertEquals(xx.foo(13,15), 28) self.assertEqual(xx.foo(13,15), 28)
self.assertEquals(xx.new().demo(), None) self.assertEqual(xx.new().demo(), None)
doc = 'This is a template module just for instruction.' doc = 'This is a template module just for instruction.'
self.assertEquals(xx.__doc__, doc) self.assertEqual(xx.__doc__, doc)
self.assertTrue(isinstance(xx.Null(), xx.Null)) self.assertTrue(isinstance(xx.Null(), xx.Null))
self.assertTrue(isinstance(xx.Str(), xx.Str)) self.assertTrue(isinstance(xx.Str(), xx.Str))
@ -206,7 +206,7 @@ class BuildExtTestCase(TempdirManager,
cmd = build_ext(dist) cmd = build_ext(dist)
cmd.libraries = 'my_lib' cmd.libraries = 'my_lib'
cmd.finalize_options() cmd.finalize_options()
self.assertEquals(cmd.libraries, ['my_lib']) self.assertEqual(cmd.libraries, ['my_lib'])
# make sure cmd.library_dirs is turned into a list # make sure cmd.library_dirs is turned into a list
# if it's a string # if it's a string
@ -220,7 +220,7 @@ class BuildExtTestCase(TempdirManager,
cmd = build_ext(dist) cmd = build_ext(dist)
cmd.rpath = os.pathsep.join(['one', 'two']) cmd.rpath = os.pathsep.join(['one', 'two'])
cmd.finalize_options() cmd.finalize_options()
self.assertEquals(cmd.rpath, ['one', 'two']) self.assertEqual(cmd.rpath, ['one', 'two'])
# XXX more tests to perform for win32 # XXX more tests to perform for win32
@ -229,25 +229,25 @@ class BuildExtTestCase(TempdirManager,
cmd = build_ext(dist) cmd = build_ext(dist)
cmd.define = 'one,two' cmd.define = 'one,two'
cmd.finalize_options() cmd.finalize_options()
self.assertEquals(cmd.define, [('one', '1'), ('two', '1')]) self.assertEqual(cmd.define, [('one', '1'), ('two', '1')])
# make sure undef is turned into a list of # make sure undef is turned into a list of
# strings if they are ','-separated strings # strings if they are ','-separated strings
cmd = build_ext(dist) cmd = build_ext(dist)
cmd.undef = 'one,two' cmd.undef = 'one,two'
cmd.finalize_options() cmd.finalize_options()
self.assertEquals(cmd.undef, ['one', 'two']) self.assertEqual(cmd.undef, ['one', 'two'])
# make sure swig_opts is turned into a list # make sure swig_opts is turned into a list
cmd = build_ext(dist) cmd = build_ext(dist)
cmd.swig_opts = None cmd.swig_opts = None
cmd.finalize_options() cmd.finalize_options()
self.assertEquals(cmd.swig_opts, []) self.assertEqual(cmd.swig_opts, [])
cmd = build_ext(dist) cmd = build_ext(dist)
cmd.swig_opts = '1 2' cmd.swig_opts = '1 2'
cmd.finalize_options() cmd.finalize_options()
self.assertEquals(cmd.swig_opts, ['1', '2']) self.assertEqual(cmd.swig_opts, ['1', '2'])
def test_check_extensions_list(self): def test_check_extensions_list(self):
dist = Distribution() dist = Distribution()
@ -284,7 +284,7 @@ class BuildExtTestCase(TempdirManager,
# check_extensions_list adds in ext the values passed # check_extensions_list adds in ext the values passed
# when they are in ('include_dirs', 'library_dirs', 'libraries' # when they are in ('include_dirs', 'library_dirs', 'libraries'
# 'extra_objects', 'extra_compile_args', 'extra_link_args') # 'extra_objects', 'extra_compile_args', 'extra_link_args')
self.assertEquals(ext.libraries, 'foo') self.assertEqual(ext.libraries, 'foo')
self.assertTrue(not hasattr(ext, 'some')) self.assertTrue(not hasattr(ext, 'some'))
# 'macros' element of build info dict must be 1- or 2-tuple # 'macros' element of build info dict must be 1- or 2-tuple
@ -294,15 +294,15 @@ class BuildExtTestCase(TempdirManager,
exts[0][1]['macros'] = [('1', '2'), ('3',)] exts[0][1]['macros'] = [('1', '2'), ('3',)]
cmd.check_extensions_list(exts) cmd.check_extensions_list(exts)
self.assertEquals(exts[0].undef_macros, ['3']) self.assertEqual(exts[0].undef_macros, ['3'])
self.assertEquals(exts[0].define_macros, [('1', '2')]) self.assertEqual(exts[0].define_macros, [('1', '2')])
def test_get_source_files(self): def test_get_source_files(self):
modules = [Extension('foo', ['xxx'], optional=False)] modules = [Extension('foo', ['xxx'], optional=False)]
dist = Distribution({'name': 'xx', 'ext_modules': modules}) dist = Distribution({'name': 'xx', 'ext_modules': modules})
cmd = build_ext(dist) cmd = build_ext(dist)
cmd.ensure_finalized() cmd.ensure_finalized()
self.assertEquals(cmd.get_source_files(), ['xxx']) self.assertEqual(cmd.get_source_files(), ['xxx'])
def test_compiler_option(self): def test_compiler_option(self):
# cmd.compiler is an option and # cmd.compiler is an option and
@ -313,7 +313,7 @@ class BuildExtTestCase(TempdirManager,
cmd.compiler = 'unix' cmd.compiler = 'unix'
cmd.ensure_finalized() cmd.ensure_finalized()
cmd.run() cmd.run()
self.assertEquals(cmd.compiler, 'unix') self.assertEqual(cmd.compiler, 'unix')
def test_get_outputs(self): def test_get_outputs(self):
tmp_dir = self.mkdtemp() tmp_dir = self.mkdtemp()
@ -325,7 +325,7 @@ class BuildExtTestCase(TempdirManager,
cmd = build_ext(dist) cmd = build_ext(dist)
self._fixup_command(cmd) self._fixup_command(cmd)
cmd.ensure_finalized() cmd.ensure_finalized()
self.assertEquals(len(cmd.get_outputs()), 1) self.assertEqual(len(cmd.get_outputs()), 1)
if os.name == "nt": if os.name == "nt":
cmd.debug = sys.executable.endswith("_d.exe") cmd.debug = sys.executable.endswith("_d.exe")
@ -348,7 +348,7 @@ class BuildExtTestCase(TempdirManager,
so_ext = sysconfig.get_config_var('SO') so_ext = sysconfig.get_config_var('SO')
self.assertTrue(so_file.endswith(so_ext)) self.assertTrue(so_file.endswith(so_ext))
so_dir = os.path.dirname(so_file) so_dir = os.path.dirname(so_file)
self.assertEquals(so_dir, other_tmp_dir) self.assertEqual(so_dir, other_tmp_dir)
cmd.inplace = 0 cmd.inplace = 0
cmd.compiler = None cmd.compiler = None
@ -357,7 +357,7 @@ class BuildExtTestCase(TempdirManager,
self.assertTrue(os.path.exists(so_file)) self.assertTrue(os.path.exists(so_file))
self.assertTrue(so_file.endswith(so_ext)) self.assertTrue(so_file.endswith(so_ext))
so_dir = os.path.dirname(so_file) so_dir = os.path.dirname(so_file)
self.assertEquals(so_dir, cmd.build_lib) self.assertEqual(so_dir, cmd.build_lib)
# inplace = 0, cmd.package = 'bar' # inplace = 0, cmd.package = 'bar'
build_py = cmd.get_finalized_command('build_py') build_py = cmd.get_finalized_command('build_py')
@ -365,7 +365,7 @@ class BuildExtTestCase(TempdirManager,
path = cmd.get_ext_fullpath('foo') path = cmd.get_ext_fullpath('foo')
# checking that the last directory is the build_dir # checking that the last directory is the build_dir
path = os.path.split(path)[0] path = os.path.split(path)[0]
self.assertEquals(path, cmd.build_lib) self.assertEqual(path, cmd.build_lib)
# inplace = 1, cmd.package = 'bar' # inplace = 1, cmd.package = 'bar'
cmd.inplace = 1 cmd.inplace = 1
@ -379,7 +379,7 @@ class BuildExtTestCase(TempdirManager,
# checking that the last directory is bar # checking that the last directory is bar
path = os.path.split(path)[0] path = os.path.split(path)[0]
lastdir = os.path.split(path)[-1] lastdir = os.path.split(path)[-1]
self.assertEquals(lastdir, 'bar') self.assertEqual(lastdir, 'bar')
def test_ext_fullpath(self): def test_ext_fullpath(self):
ext = sysconfig.get_config_vars()['SO'] ext = sysconfig.get_config_vars()['SO']
@ -395,14 +395,14 @@ class BuildExtTestCase(TempdirManager,
curdir = os.getcwd() curdir = os.getcwd()
wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext) wanted = os.path.join(curdir, 'src', 'lxml', 'etree' + ext)
path = cmd.get_ext_fullpath('lxml.etree') path = cmd.get_ext_fullpath('lxml.etree')
self.assertEquals(wanted, path) self.assertEqual(wanted, path)
# building lxml.etree not inplace # building lxml.etree not inplace
cmd.inplace = 0 cmd.inplace = 0
cmd.build_lib = os.path.join(curdir, 'tmpdir') cmd.build_lib = os.path.join(curdir, 'tmpdir')
wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext) wanted = os.path.join(curdir, 'tmpdir', 'lxml', 'etree' + ext)
path = cmd.get_ext_fullpath('lxml.etree') path = cmd.get_ext_fullpath('lxml.etree')
self.assertEquals(wanted, path) self.assertEqual(wanted, path)
# building twisted.runner.portmap not inplace # building twisted.runner.portmap not inplace
build_py = cmd.get_finalized_command('build_py') build_py = cmd.get_finalized_command('build_py')
@ -411,13 +411,13 @@ class BuildExtTestCase(TempdirManager,
path = cmd.get_ext_fullpath('twisted.runner.portmap') path = cmd.get_ext_fullpath('twisted.runner.portmap')
wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner', wanted = os.path.join(curdir, 'tmpdir', 'twisted', 'runner',
'portmap' + ext) 'portmap' + ext)
self.assertEquals(wanted, path) self.assertEqual(wanted, path)
# building twisted.runner.portmap inplace # building twisted.runner.portmap inplace
cmd.inplace = 1 cmd.inplace = 1
path = cmd.get_ext_fullpath('twisted.runner.portmap') path = cmd.get_ext_fullpath('twisted.runner.portmap')
wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext) wanted = os.path.join(curdir, 'twisted', 'runner', 'portmap' + ext)
self.assertEquals(wanted, path) self.assertEqual(wanted, path)
def test_suite(): def test_suite():
src = _get_source_filename() src = _get_source_filename()

View File

@ -27,7 +27,7 @@ class CheckTestCase(support.LoggingSilencer,
# by default, check is checking the metadata # by default, check is checking the metadata
# should have some warnings # should have some warnings
cmd = self._run() cmd = self._run()
self.assertEquals(cmd._warnings, 2) self.assertEqual(cmd._warnings, 2)
# now let's add the required fields # now let's add the required fields
# and run it again, to make sure we don't get # and run it again, to make sure we don't get
@ -36,7 +36,7 @@ class CheckTestCase(support.LoggingSilencer,
'author_email': 'xxx', 'author_email': 'xxx',
'name': 'xxx', 'version': 'xxx'} 'name': 'xxx', 'version': 'xxx'}
cmd = self._run(metadata) cmd = self._run(metadata)
self.assertEquals(cmd._warnings, 0) self.assertEqual(cmd._warnings, 0)
# now with the strict mode, we should # now with the strict mode, we should
# get an error if there are missing metadata # get an error if there are missing metadata
@ -44,7 +44,7 @@ class CheckTestCase(support.LoggingSilencer,
# and of course, no error when all metadata are present # and of course, no error when all metadata are present
cmd = self._run(metadata, strict=1) cmd = self._run(metadata, strict=1)
self.assertEquals(cmd._warnings, 0) self.assertEqual(cmd._warnings, 0)
def test_check_document(self): def test_check_document(self):
if not HAS_DOCUTILS: # won't test without docutils if not HAS_DOCUTILS: # won't test without docutils
@ -55,12 +55,12 @@ class CheckTestCase(support.LoggingSilencer,
# let's see if it detects broken rest # let's see if it detects broken rest
broken_rest = 'title\n===\n\ntest' broken_rest = 'title\n===\n\ntest'
msgs = cmd._check_rst_data(broken_rest) msgs = cmd._check_rst_data(broken_rest)
self.assertEquals(len(msgs), 1) self.assertEqual(len(msgs), 1)
# and non-broken rest # and non-broken rest
rest = 'title\n=====\n\ntest' rest = 'title\n=====\n\ntest'
msgs = cmd._check_rst_data(rest) msgs = cmd._check_rst_data(rest)
self.assertEquals(len(msgs), 0) self.assertEqual(len(msgs), 0)
def test_check_restructuredtext(self): def test_check_restructuredtext(self):
if not HAS_DOCUTILS: # won't test without docutils if not HAS_DOCUTILS: # won't test without docutils
@ -70,7 +70,7 @@ class CheckTestCase(support.LoggingSilencer,
pkg_info, dist = self.create_dist(long_description=broken_rest) pkg_info, dist = self.create_dist(long_description=broken_rest)
cmd = check(dist) cmd = check(dist)
cmd.check_restructuredtext() cmd.check_restructuredtext()
self.assertEquals(cmd._warnings, 1) self.assertEqual(cmd._warnings, 1)
# let's see if we have an error with strict=1 # let's see if we have an error with strict=1
metadata = {'url': 'xxx', 'author': 'xxx', metadata = {'url': 'xxx', 'author': 'xxx',
@ -83,7 +83,7 @@ class CheckTestCase(support.LoggingSilencer,
# and non-broken rest # and non-broken rest
metadata['long_description'] = 'title\n=====\n\ntest' metadata['long_description'] = 'title\n=====\n\ntest'
cmd = self._run(metadata, strict=1, restructuredtext=1) cmd = self._run(metadata, strict=1, restructuredtext=1)
self.assertEquals(cmd._warnings, 0) self.assertEqual(cmd._warnings, 0)
def test_check_all(self): def test_check_all(self):

View File

@ -44,7 +44,7 @@ class CommandTestCase(unittest.TestCase):
# making sure execute gets called properly # making sure execute gets called properly
def _execute(func, args, exec_msg, level): def _execute(func, args, exec_msg, level):
self.assertEquals(exec_msg, 'generating out from in') self.assertEqual(exec_msg, 'generating out from in')
cmd.force = True cmd.force = True
cmd.execute = _execute cmd.execute = _execute
cmd.make_file(infiles='in', outfile='out', func='func', args=()) cmd.make_file(infiles='in', outfile='out', func='func', args=())
@ -63,7 +63,7 @@ class CommandTestCase(unittest.TestCase):
wanted = ["command options for 'MyCmd':", ' option1 = 1', wanted = ["command options for 'MyCmd':", ' option1 = 1',
' option2 = 1'] ' option2 = 1']
self.assertEquals(msgs, wanted) self.assertEqual(msgs, wanted)
def test_ensure_string(self): def test_ensure_string(self):
cmd = self.cmd cmd = self.cmd
@ -81,7 +81,7 @@ class CommandTestCase(unittest.TestCase):
cmd = self.cmd cmd = self.cmd
cmd.option1 = 'ok,dok' cmd.option1 = 'ok,dok'
cmd.ensure_string_list('option1') cmd.ensure_string_list('option1')
self.assertEquals(cmd.option1, ['ok', 'dok']) self.assertEqual(cmd.option1, ['ok', 'dok'])
cmd.option2 = ['xxx', 'www'] cmd.option2 = ['xxx', 'www']
cmd.ensure_string_list('option2') cmd.ensure_string_list('option2')
@ -109,14 +109,14 @@ class CommandTestCase(unittest.TestCase):
with captured_stdout() as stdout: with captured_stdout() as stdout:
cmd.debug_print('xxx') cmd.debug_print('xxx')
stdout.seek(0) stdout.seek(0)
self.assertEquals(stdout.read(), '') self.assertEqual(stdout.read(), '')
debug.DEBUG = True debug.DEBUG = True
try: try:
with captured_stdout() as stdout: with captured_stdout() as stdout:
cmd.debug_print('xxx') cmd.debug_print('xxx')
stdout.seek(0) stdout.seek(0)
self.assertEquals(stdout.read(), 'xxx\n') self.assertEqual(stdout.read(), 'xxx\n')
finally: finally:
debug.DEBUG = False debug.DEBUG = False

View File

@ -89,7 +89,7 @@ class PyPIRCCommandTestCase(support.TempdirManager,
waited = [('password', 'secret'), ('realm', 'pypi'), waited = [('password', 'secret'), ('realm', 'pypi'),
('repository', 'http://pypi.python.org/pypi'), ('repository', 'http://pypi.python.org/pypi'),
('server', 'server1'), ('username', 'me')] ('server', 'server1'), ('username', 'me')]
self.assertEquals(config, waited) self.assertEqual(config, waited)
# old format # old format
self.write_file(self.rc, PYPIRC_OLD) self.write_file(self.rc, PYPIRC_OLD)
@ -98,7 +98,7 @@ class PyPIRCCommandTestCase(support.TempdirManager,
waited = [('password', 'secret'), ('realm', 'pypi'), waited = [('password', 'secret'), ('realm', 'pypi'),
('repository', 'http://pypi.python.org/pypi'), ('repository', 'http://pypi.python.org/pypi'),
('server', 'server-login'), ('username', 'tarek')] ('server', 'server-login'), ('username', 'tarek')]
self.assertEquals(config, waited) self.assertEqual(config, waited)
def test_server_empty_registration(self): def test_server_empty_registration(self):
cmd = self._cmd(self.dist) cmd = self._cmd(self.dist)
@ -109,7 +109,7 @@ class PyPIRCCommandTestCase(support.TempdirManager,
f = open(rc) f = open(rc)
try: try:
content = f.read() content = f.read()
self.assertEquals(content, WANTED) self.assertEqual(content, WANTED)
finally: finally:
f.close() f.close()

View File

@ -35,7 +35,7 @@ class ConfigTestCase(support.LoggingSilencer,
f.close() f.close()
dump_file(this_file, 'I am the header') dump_file(this_file, 'I am the header')
self.assertEquals(len(self._logs), numlines+1) self.assertEqual(len(self._logs), numlines+1)
def test_search_cpp(self): def test_search_cpp(self):
if sys.platform == 'win32': if sys.platform == 'win32':
@ -45,10 +45,10 @@ class ConfigTestCase(support.LoggingSilencer,
# simple pattern searches # simple pattern searches
match = cmd.search_cpp(pattern='xxx', body='// xxx') match = cmd.search_cpp(pattern='xxx', body='// xxx')
self.assertEquals(match, 0) self.assertEqual(match, 0)
match = cmd.search_cpp(pattern='_configtest', body='// xxx') match = cmd.search_cpp(pattern='_configtest', body='// xxx')
self.assertEquals(match, 1) self.assertEqual(match, 1)
def test_finalize_options(self): def test_finalize_options(self):
# finalize_options does a bit of transformation # finalize_options does a bit of transformation
@ -60,9 +60,9 @@ class ConfigTestCase(support.LoggingSilencer,
cmd.library_dirs = 'three%sfour' % os.pathsep cmd.library_dirs = 'three%sfour' % os.pathsep
cmd.ensure_finalized() cmd.ensure_finalized()
self.assertEquals(cmd.include_dirs, ['one', 'two']) self.assertEqual(cmd.include_dirs, ['one', 'two'])
self.assertEquals(cmd.libraries, ['one']) self.assertEqual(cmd.libraries, ['one'])
self.assertEquals(cmd.library_dirs, ['three', 'four']) self.assertEqual(cmd.library_dirs, ['three', 'four'])
def test_clean(self): def test_clean(self):
# _clean removes files # _clean removes files

View File

@ -89,7 +89,7 @@ class CoreTestCase(support.EnvironGuard, unittest.TestCase):
with captured_stdout() as stdout: with captured_stdout() as stdout:
distutils.core.setup(name='bar') distutils.core.setup(name='bar')
stdout.seek(0) stdout.seek(0)
self.assertEquals(stdout.read(), 'bar\n') self.assertEqual(stdout.read(), 'bar\n')
distutils.core.DEBUG = True distutils.core.DEBUG = True
try: try:
@ -99,7 +99,7 @@ class CoreTestCase(support.EnvironGuard, unittest.TestCase):
distutils.core.DEBUG = False distutils.core.DEBUG = False
stdout.seek(0) stdout.seek(0)
wanted = "options (after parsing config files):\n" wanted = "options (after parsing config files):\n"
self.assertEquals(stdout.readlines()[0], wanted) self.assertEqual(stdout.readlines()[0], wanted)
def test_suite(): def test_suite():
return unittest.makeSuite(CoreTestCase) return unittest.makeSuite(CoreTestCase)

View File

@ -66,82 +66,82 @@ class CygwinCCompilerTestCase(support.TempdirManager,
sys.version = ('2.6.1 (r261:67515, Dec 6 2008, 16:42:21) \n[GCC ' sys.version = ('2.6.1 (r261:67515, Dec 6 2008, 16:42:21) \n[GCC '
'4.0.1 (Apple Computer, Inc. build 5370)]') '4.0.1 (Apple Computer, Inc. build 5370)]')
self.assertEquals(check_config_h()[0], CONFIG_H_OK) self.assertEqual(check_config_h()[0], CONFIG_H_OK)
# then it tries to see if it can find "__GNUC__" in pyconfig.h # then it tries to see if it can find "__GNUC__" in pyconfig.h
sys.version = 'something without the *CC word' sys.version = 'something without the *CC word'
# if the file doesn't exist it returns CONFIG_H_UNCERTAIN # if the file doesn't exist it returns CONFIG_H_UNCERTAIN
self.assertEquals(check_config_h()[0], CONFIG_H_UNCERTAIN) self.assertEqual(check_config_h()[0], CONFIG_H_UNCERTAIN)
# if it exists but does not contain __GNUC__, it returns CONFIG_H_NOTOK # if it exists but does not contain __GNUC__, it returns CONFIG_H_NOTOK
self.write_file(self.python_h, 'xxx') self.write_file(self.python_h, 'xxx')
self.assertEquals(check_config_h()[0], CONFIG_H_NOTOK) self.assertEqual(check_config_h()[0], CONFIG_H_NOTOK)
# and CONFIG_H_OK if __GNUC__ is found # and CONFIG_H_OK if __GNUC__ is found
self.write_file(self.python_h, 'xxx __GNUC__ xxx') self.write_file(self.python_h, 'xxx __GNUC__ xxx')
self.assertEquals(check_config_h()[0], CONFIG_H_OK) self.assertEqual(check_config_h()[0], CONFIG_H_OK)
def test_get_versions(self): def test_get_versions(self):
# get_versions calls distutils.spawn.find_executable on # get_versions calls distutils.spawn.find_executable on
# 'gcc', 'ld' and 'dllwrap' # 'gcc', 'ld' and 'dllwrap'
self.assertEquals(get_versions(), (None, None, None)) self.assertEqual(get_versions(), (None, None, None))
# Let's fake we have 'gcc' and it returns '3.4.5' # Let's fake we have 'gcc' and it returns '3.4.5'
self._exes['gcc'] = b'gcc (GCC) 3.4.5 (mingw special)\nFSF' self._exes['gcc'] = b'gcc (GCC) 3.4.5 (mingw special)\nFSF'
res = get_versions() res = get_versions()
self.assertEquals(str(res[0]), '3.4.5') self.assertEqual(str(res[0]), '3.4.5')
# and let's see what happens when the version # and let's see what happens when the version
# doesn't match the regular expression # doesn't match the regular expression
# (\d+\.\d+(\.\d+)*) # (\d+\.\d+(\.\d+)*)
self._exes['gcc'] = b'very strange output' self._exes['gcc'] = b'very strange output'
res = get_versions() res = get_versions()
self.assertEquals(res[0], None) self.assertEqual(res[0], None)
# same thing for ld # same thing for ld
self._exes['ld'] = b'GNU ld version 2.17.50 20060824' self._exes['ld'] = b'GNU ld version 2.17.50 20060824'
res = get_versions() res = get_versions()
self.assertEquals(str(res[1]), '2.17.50') self.assertEqual(str(res[1]), '2.17.50')
self._exes['ld'] = b'@(#)PROGRAM:ld PROJECT:ld64-77' self._exes['ld'] = b'@(#)PROGRAM:ld PROJECT:ld64-77'
res = get_versions() res = get_versions()
self.assertEquals(res[1], None) self.assertEqual(res[1], None)
# and dllwrap # and dllwrap
self._exes['dllwrap'] = b'GNU dllwrap 2.17.50 20060824\nFSF' self._exes['dllwrap'] = b'GNU dllwrap 2.17.50 20060824\nFSF'
res = get_versions() res = get_versions()
self.assertEquals(str(res[2]), '2.17.50') self.assertEqual(str(res[2]), '2.17.50')
self._exes['dllwrap'] = b'Cheese Wrap' self._exes['dllwrap'] = b'Cheese Wrap'
res = get_versions() res = get_versions()
self.assertEquals(res[2], None) self.assertEqual(res[2], None)
def test_get_msvcr(self): def test_get_msvcr(self):
# none # none
sys.version = ('2.6.1 (r261:67515, Dec 6 2008, 16:42:21) ' sys.version = ('2.6.1 (r261:67515, Dec 6 2008, 16:42:21) '
'\n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]') '\n[GCC 4.0.1 (Apple Computer, Inc. build 5370)]')
self.assertEquals(get_msvcr(), None) self.assertEqual(get_msvcr(), None)
# MSVC 7.0 # MSVC 7.0
sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
'[MSC v.1300 32 bits (Intel)]') '[MSC v.1300 32 bits (Intel)]')
self.assertEquals(get_msvcr(), ['msvcr70']) self.assertEqual(get_msvcr(), ['msvcr70'])
# MSVC 7.1 # MSVC 7.1
sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
'[MSC v.1310 32 bits (Intel)]') '[MSC v.1310 32 bits (Intel)]')
self.assertEquals(get_msvcr(), ['msvcr71']) self.assertEqual(get_msvcr(), ['msvcr71'])
# VS2005 / MSVC 8.0 # VS2005 / MSVC 8.0
sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
'[MSC v.1400 32 bits (Intel)]') '[MSC v.1400 32 bits (Intel)]')
self.assertEquals(get_msvcr(), ['msvcr80']) self.assertEqual(get_msvcr(), ['msvcr80'])
# VS2008 / MSVC 9.0 # VS2008 / MSVC 9.0
sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '
'[MSC v.1500 32 bits (Intel)]') '[MSC v.1500 32 bits (Intel)]')
self.assertEquals(get_msvcr(), ['msvcr90']) self.assertEqual(get_msvcr(), ['msvcr90'])
# unknown # unknown
sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) ' sys.version = ('2.5.1 (r251:54863, Apr 18 2007, 08:51:08) '

View File

@ -43,8 +43,8 @@ class DepUtilTestCase(support.TempdirManager, unittest.TestCase):
self.write_file(two) self.write_file(two)
self.write_file(four) self.write_file(four)
self.assertEquals(newer_pairwise([one, two], [three, four]), self.assertEqual(newer_pairwise([one, two], [three, four]),
([one],[three])) ([one],[three]))
def test_newer_group(self): def test_newer_group(self):
tmpdir = self.mkdtemp() tmpdir = self.mkdtemp()

View File

@ -38,18 +38,18 @@ class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
mkpath(self.target, verbose=0) mkpath(self.target, verbose=0)
wanted = [] wanted = []
self.assertEquals(self._logs, wanted) self.assertEqual(self._logs, wanted)
remove_tree(self.root_target, verbose=0) remove_tree(self.root_target, verbose=0)
mkpath(self.target, verbose=1) mkpath(self.target, verbose=1)
wanted = ['creating %s' % self.root_target, wanted = ['creating %s' % self.root_target,
'creating %s' % self.target] 'creating %s' % self.target]
self.assertEquals(self._logs, wanted) self.assertEqual(self._logs, wanted)
self._logs = [] self._logs = []
remove_tree(self.root_target, verbose=1) remove_tree(self.root_target, verbose=1)
wanted = ["removing '%s' (and everything under it)" % self.root_target] wanted = ["removing '%s' (and everything under it)" % self.root_target]
self.assertEquals(self._logs, wanted) self.assertEqual(self._logs, wanted)
@unittest.skipIf(sys.platform.startswith('win'), @unittest.skipIf(sys.platform.startswith('win'),
"This test is only appropriate for POSIX-like systems.") "This test is only appropriate for POSIX-like systems.")
@ -67,12 +67,12 @@ class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
def test_create_tree_verbosity(self): def test_create_tree_verbosity(self):
create_tree(self.root_target, ['one', 'two', 'three'], verbose=0) create_tree(self.root_target, ['one', 'two', 'three'], verbose=0)
self.assertEquals(self._logs, []) self.assertEqual(self._logs, [])
remove_tree(self.root_target, verbose=0) remove_tree(self.root_target, verbose=0)
wanted = ['creating %s' % self.root_target] wanted = ['creating %s' % self.root_target]
create_tree(self.root_target, ['one', 'two', 'three'], verbose=1) create_tree(self.root_target, ['one', 'two', 'three'], verbose=1)
self.assertEquals(self._logs, wanted) self.assertEqual(self._logs, wanted)
remove_tree(self.root_target, verbose=0) remove_tree(self.root_target, verbose=0)
@ -82,7 +82,7 @@ class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
mkpath(self.target, verbose=0) mkpath(self.target, verbose=0)
copy_tree(self.target, self.target2, verbose=0) copy_tree(self.target, self.target2, verbose=0)
self.assertEquals(self._logs, []) self.assertEqual(self._logs, [])
remove_tree(self.root_target, verbose=0) remove_tree(self.root_target, verbose=0)
@ -96,18 +96,18 @@ class DirUtilTestCase(support.TempdirManager, unittest.TestCase):
wanted = ['copying %s -> %s' % (a_file, self.target2)] wanted = ['copying %s -> %s' % (a_file, self.target2)]
copy_tree(self.target, self.target2, verbose=1) copy_tree(self.target, self.target2, verbose=1)
self.assertEquals(self._logs, wanted) self.assertEqual(self._logs, wanted)
remove_tree(self.root_target, verbose=0) remove_tree(self.root_target, verbose=0)
remove_tree(self.target2, verbose=0) remove_tree(self.target2, verbose=0)
def test_ensure_relative(self): def test_ensure_relative(self):
if os.sep == '/': if os.sep == '/':
self.assertEquals(ensure_relative('/home/foo'), 'home/foo') self.assertEqual(ensure_relative('/home/foo'), 'home/foo')
self.assertEquals(ensure_relative('some/path'), 'some/path') self.assertEqual(ensure_relative('some/path'), 'some/path')
else: # \\ else: # \\
self.assertEquals(ensure_relative('c:\\home\\foo'), 'c:home\\foo') self.assertEqual(ensure_relative('c:\\home\\foo'), 'c:home\\foo')
self.assertEquals(ensure_relative('home\\foo'), 'home\\foo') self.assertEqual(ensure_relative('home\\foo'), 'home\\foo')
def test_suite(): def test_suite():
return unittest.makeSuite(DirUtilTestCase) return unittest.makeSuite(DirUtilTestCase)

View File

@ -124,7 +124,7 @@ class DistributionTestCase(support.LoggingSilencer,
finally: finally:
warnings.warn = old_warn warnings.warn = old_warn
self.assertEquals(len(warns), 0) self.assertEqual(len(warns), 0)
def test_finalize_options(self): def test_finalize_options(self):
@ -135,20 +135,20 @@ class DistributionTestCase(support.LoggingSilencer,
dist.finalize_options() dist.finalize_options()
# finalize_option splits platforms and keywords # finalize_option splits platforms and keywords
self.assertEquals(dist.metadata.platforms, ['one', 'two']) self.assertEqual(dist.metadata.platforms, ['one', 'two'])
self.assertEquals(dist.metadata.keywords, ['one', 'two']) self.assertEqual(dist.metadata.keywords, ['one', 'two'])
def test_get_command_packages(self): def test_get_command_packages(self):
dist = Distribution() dist = Distribution()
self.assertEquals(dist.command_packages, None) self.assertEqual(dist.command_packages, None)
cmds = dist.get_command_packages() cmds = dist.get_command_packages()
self.assertEquals(cmds, ['distutils.command']) self.assertEqual(cmds, ['distutils.command'])
self.assertEquals(dist.command_packages, self.assertEqual(dist.command_packages,
['distutils.command']) ['distutils.command'])
dist.command_packages = 'one,two' dist.command_packages = 'one,two'
cmds = dist.get_command_packages() cmds = dist.get_command_packages()
self.assertEquals(cmds, ['distutils.command', 'one', 'two']) self.assertEqual(cmds, ['distutils.command', 'one', 'two'])
def test_announce(self): def test_announce(self):
@ -287,8 +287,8 @@ class MetadataTestCase(support.TempdirManager, support.EnvironGuard,
def test_fix_help_options(self): def test_fix_help_options(self):
help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)] help_tuples = [('a', 'b', 'c', 'd'), (1, 2, 3, 4)]
fancy_options = fix_help_options(help_tuples) fancy_options = fix_help_options(help_tuples)
self.assertEquals(fancy_options[0], ('a', 'b', 'c')) self.assertEqual(fancy_options[0], ('a', 'b', 'c'))
self.assertEquals(fancy_options[1], (1, 2, 3)) self.assertEqual(fancy_options[1], (1, 2, 3))
def test_show_help(self): def test_show_help(self):
# smoke test, just makes sure some help is displayed # smoke test, just makes sure some help is displayed

View File

@ -28,38 +28,38 @@ class ExtensionTestCase(unittest.TestCase):
'rect', 'rwobject', 'scrap', 'surface', 'surflock', 'rect', 'rwobject', 'scrap', 'surface', 'surflock',
'time', 'transform'] 'time', 'transform']
self.assertEquals(names, wanted) self.assertEqual(names, wanted)
def test_extension_init(self): def test_extension_init(self):
# the first argument, which is the name, must be a string # the first argument, which is the name, must be a string
self.assertRaises(AssertionError, Extension, 1, []) self.assertRaises(AssertionError, Extension, 1, [])
ext = Extension('name', []) ext = Extension('name', [])
self.assertEquals(ext.name, 'name') self.assertEqual(ext.name, 'name')
# the second argument, which is the list of files, must # the second argument, which is the list of files, must
# be a list of strings # be a list of strings
self.assertRaises(AssertionError, Extension, 'name', 'file') self.assertRaises(AssertionError, Extension, 'name', 'file')
self.assertRaises(AssertionError, Extension, 'name', ['file', 1]) self.assertRaises(AssertionError, Extension, 'name', ['file', 1])
ext = Extension('name', ['file1', 'file2']) ext = Extension('name', ['file1', 'file2'])
self.assertEquals(ext.sources, ['file1', 'file2']) self.assertEqual(ext.sources, ['file1', 'file2'])
# others arguments have defaults # others arguments have defaults
for attr in ('include_dirs', 'define_macros', 'undef_macros', for attr in ('include_dirs', 'define_macros', 'undef_macros',
'library_dirs', 'libraries', 'runtime_library_dirs', 'library_dirs', 'libraries', 'runtime_library_dirs',
'extra_objects', 'extra_compile_args', 'extra_link_args', 'extra_objects', 'extra_compile_args', 'extra_link_args',
'export_symbols', 'swig_opts', 'depends'): 'export_symbols', 'swig_opts', 'depends'):
self.assertEquals(getattr(ext, attr), []) self.assertEqual(getattr(ext, attr), [])
self.assertEquals(ext.language, None) self.assertEqual(ext.language, None)
self.assertEquals(ext.optional, None) self.assertEqual(ext.optional, None)
# if there are unknown keyword options, warn about them # if there are unknown keyword options, warn about them
with check_warnings() as w: with check_warnings() as w:
warnings.simplefilter('always') warnings.simplefilter('always')
ext = Extension('name', ['file1', 'file2'], chic=True) ext = Extension('name', ['file1', 'file2'], chic=True)
self.assertEquals(len(w.warnings), 1) self.assertEqual(len(w.warnings), 1)
self.assertEquals(str(w.warnings[0].message), self.assertEqual(str(w.warnings[0].message),
"Unknown Extension options: 'chic'") "Unknown Extension options: 'chic'")
def test_suite(): def test_suite():

View File

@ -39,14 +39,14 @@ class FileUtilTestCase(support.TempdirManager, unittest.TestCase):
move_file(self.source, self.target, verbose=0) move_file(self.source, self.target, verbose=0)
wanted = [] wanted = []
self.assertEquals(self._logs, wanted) self.assertEqual(self._logs, wanted)
# back to original state # back to original state
move_file(self.target, self.source, verbose=0) move_file(self.target, self.source, verbose=0)
move_file(self.source, self.target, verbose=1) move_file(self.source, self.target, verbose=1)
wanted = ['moving %s -> %s' % (self.source, self.target)] wanted = ['moving %s -> %s' % (self.source, self.target)]
self.assertEquals(self._logs, wanted) self.assertEqual(self._logs, wanted)
# back to original state # back to original state
move_file(self.target, self.source, verbose=0) move_file(self.target, self.source, verbose=0)
@ -56,7 +56,7 @@ class FileUtilTestCase(support.TempdirManager, unittest.TestCase):
os.mkdir(self.target_dir) os.mkdir(self.target_dir)
move_file(self.source, self.target_dir, verbose=1) move_file(self.source, self.target_dir, verbose=1)
wanted = ['moving %s -> %s' % (self.source, self.target_dir)] wanted = ['moving %s -> %s' % (self.source, self.target_dir)]
self.assertEquals(self._logs, wanted) self.assertEqual(self._logs, wanted)
def test_suite(): def test_suite():

View File

@ -9,29 +9,29 @@ class FileListTestCase(unittest.TestCase):
def test_glob_to_re(self): def test_glob_to_re(self):
# simple cases # simple cases
self.assertEquals(glob_to_re('foo*'), 'foo[^/]*\\Z(?ms)') self.assertEqual(glob_to_re('foo*'), 'foo[^/]*\\Z(?ms)')
self.assertEquals(glob_to_re('foo?'), 'foo[^/]\\Z(?ms)') self.assertEqual(glob_to_re('foo?'), 'foo[^/]\\Z(?ms)')
self.assertEquals(glob_to_re('foo??'), 'foo[^/][^/]\\Z(?ms)') self.assertEqual(glob_to_re('foo??'), 'foo[^/][^/]\\Z(?ms)')
# special cases # special cases
self.assertEquals(glob_to_re(r'foo\\*'), r'foo\\\\[^/]*\Z(?ms)') self.assertEqual(glob_to_re(r'foo\\*'), r'foo\\\\[^/]*\Z(?ms)')
self.assertEquals(glob_to_re(r'foo\\\*'), r'foo\\\\\\[^/]*\Z(?ms)') self.assertEqual(glob_to_re(r'foo\\\*'), r'foo\\\\\\[^/]*\Z(?ms)')
self.assertEquals(glob_to_re('foo????'), r'foo[^/][^/][^/][^/]\Z(?ms)') self.assertEqual(glob_to_re('foo????'), r'foo[^/][^/][^/][^/]\Z(?ms)')
self.assertEquals(glob_to_re(r'foo\\??'), r'foo\\\\[^/][^/]\Z(?ms)') self.assertEqual(glob_to_re(r'foo\\??'), r'foo\\\\[^/][^/]\Z(?ms)')
def test_debug_print(self): def test_debug_print(self):
file_list = FileList() file_list = FileList()
with captured_stdout() as stdout: with captured_stdout() as stdout:
file_list.debug_print('xxx') file_list.debug_print('xxx')
stdout.seek(0) stdout.seek(0)
self.assertEquals(stdout.read(), '') self.assertEqual(stdout.read(), '')
debug.DEBUG = True debug.DEBUG = True
try: try:
with captured_stdout() as stdout: with captured_stdout() as stdout:
file_list.debug_print('xxx') file_list.debug_print('xxx')
stdout.seek(0) stdout.seek(0)
self.assertEquals(stdout.read(), 'xxx\n') self.assertEqual(stdout.read(), 'xxx\n')
finally: finally:
debug.DEBUG = False debug.DEBUG = False

View File

@ -123,23 +123,23 @@ class InstallTestCase(support.TempdirManager,
# two elements # two elements
cmd.handle_extra_path() cmd.handle_extra_path()
self.assertEquals(cmd.extra_path, ['path', 'dirs']) self.assertEqual(cmd.extra_path, ['path', 'dirs'])
self.assertEquals(cmd.extra_dirs, 'dirs') self.assertEqual(cmd.extra_dirs, 'dirs')
self.assertEquals(cmd.path_file, 'path') self.assertEqual(cmd.path_file, 'path')
# one element # one element
cmd.extra_path = ['path'] cmd.extra_path = ['path']
cmd.handle_extra_path() cmd.handle_extra_path()
self.assertEquals(cmd.extra_path, ['path']) self.assertEqual(cmd.extra_path, ['path'])
self.assertEquals(cmd.extra_dirs, 'path') self.assertEqual(cmd.extra_dirs, 'path')
self.assertEquals(cmd.path_file, 'path') self.assertEqual(cmd.path_file, 'path')
# none # none
dist.extra_path = cmd.extra_path = None dist.extra_path = cmd.extra_path = None
cmd.handle_extra_path() cmd.handle_extra_path()
self.assertEquals(cmd.extra_path, None) self.assertEqual(cmd.extra_path, None)
self.assertEquals(cmd.extra_dirs, '') self.assertEqual(cmd.extra_dirs, '')
self.assertEquals(cmd.path_file, None) self.assertEqual(cmd.path_file, None)
# three elements (no way !) # three elements (no way !)
cmd.extra_path = 'path,dirs,again' cmd.extra_path = 'path,dirs,again'
@ -184,7 +184,7 @@ class InstallTestCase(support.TempdirManager,
# line (the egg info file) # line (the egg info file)
f = open(cmd.record) f = open(cmd.record)
try: try:
self.assertEquals(len(f.readlines()), 1) self.assertEqual(len(f.readlines()), 1)
finally: finally:
f.close() f.close()

View File

@ -28,14 +28,14 @@ class InstallDataTestCase(support.TempdirManager,
self.write_file(two, 'xxx') self.write_file(two, 'xxx')
cmd.data_files = [one, (inst2, [two])] cmd.data_files = [one, (inst2, [two])]
self.assertEquals(cmd.get_inputs(), [one, (inst2, [two])]) self.assertEqual(cmd.get_inputs(), [one, (inst2, [two])])
# let's run the command # let's run the command
cmd.ensure_finalized() cmd.ensure_finalized()
cmd.run() cmd.run()
# let's check the result # let's check the result
self.assertEquals(len(cmd.get_outputs()), 2) self.assertEqual(len(cmd.get_outputs()), 2)
rtwo = os.path.split(two)[-1] rtwo = os.path.split(two)[-1]
self.assertTrue(os.path.exists(os.path.join(inst2, rtwo))) self.assertTrue(os.path.exists(os.path.join(inst2, rtwo)))
rone = os.path.split(one)[-1] rone = os.path.split(one)[-1]
@ -48,7 +48,7 @@ class InstallDataTestCase(support.TempdirManager,
cmd.run() cmd.run()
# let's check the result # let's check the result
self.assertEquals(len(cmd.get_outputs()), 2) self.assertEqual(len(cmd.get_outputs()), 2)
self.assertTrue(os.path.exists(os.path.join(inst2, rtwo))) self.assertTrue(os.path.exists(os.path.join(inst2, rtwo)))
self.assertTrue(os.path.exists(os.path.join(inst, rone))) self.assertTrue(os.path.exists(os.path.join(inst, rone)))
cmd.outfiles = [] cmd.outfiles = []
@ -66,7 +66,7 @@ class InstallDataTestCase(support.TempdirManager,
cmd.run() cmd.run()
# let's check the result # let's check the result
self.assertEquals(len(cmd.get_outputs()), 4) self.assertEqual(len(cmd.get_outputs()), 4)
self.assertTrue(os.path.exists(os.path.join(inst2, rtwo))) self.assertTrue(os.path.exists(os.path.join(inst2, rtwo)))
self.assertTrue(os.path.exists(os.path.join(inst, rone))) self.assertTrue(os.path.exists(os.path.join(inst, rone)))

View File

@ -24,7 +24,7 @@ class InstallHeadersTestCase(support.TempdirManager,
pkg_dir, dist = self.create_dist(headers=headers) pkg_dir, dist = self.create_dist(headers=headers)
cmd = install_headers(dist) cmd = install_headers(dist)
self.assertEquals(cmd.get_inputs(), headers) self.assertEqual(cmd.get_inputs(), headers)
# let's run the command # let's run the command
cmd.install_dir = os.path.join(pkg_dir, 'inst') cmd.install_dir = os.path.join(pkg_dir, 'inst')
@ -32,7 +32,7 @@ class InstallHeadersTestCase(support.TempdirManager,
cmd.run() cmd.run()
# let's check the results # let's check the results
self.assertEquals(len(cmd.get_outputs()), 2) self.assertEqual(len(cmd.get_outputs()), 2)
def test_suite(): def test_suite():
return unittest.makeSuite(InstallHeadersTestCase) return unittest.makeSuite(InstallHeadersTestCase)

View File

@ -19,8 +19,8 @@ class InstallLibTestCase(support.TempdirManager,
cmd = install_lib(dist) cmd = install_lib(dist)
cmd.finalize_options() cmd.finalize_options()
self.assertEquals(cmd.compile, 1) self.assertEqual(cmd.compile, 1)
self.assertEquals(cmd.optimize, 0) self.assertEqual(cmd.optimize, 0)
# optimize must be 0, 1, or 2 # optimize must be 0, 1, or 2
cmd.optimize = 'foo' cmd.optimize = 'foo'
@ -30,7 +30,7 @@ class InstallLibTestCase(support.TempdirManager,
cmd.optimize = '2' cmd.optimize = '2'
cmd.finalize_options() cmd.finalize_options()
self.assertEquals(cmd.optimize, 2) self.assertEqual(cmd.optimize, 2)
@unittest.skipUnless(not sys.dont_write_bytecode, @unittest.skipUnless(not sys.dont_write_bytecode,
'byte-compile not supported') 'byte-compile not supported')
@ -77,7 +77,7 @@ class InstallLibTestCase(support.TempdirManager,
cmd.distribution.script_name = 'setup.py' cmd.distribution.script_name = 'setup.py'
# get_input should return 2 elements # get_input should return 2 elements
self.assertEquals(len(cmd.get_inputs()), 2) self.assertEqual(len(cmd.get_inputs()), 2)
def test_dont_write_bytecode(self): def test_dont_write_bytecode(self):
# makes sure byte_compile is not used # makes sure byte_compile is not used

View File

@ -23,9 +23,9 @@ class TestLog(unittest.TestCase):
log.debug("debug:\xe9") log.debug("debug:\xe9")
log.fatal("fatal:\xe9") log.fatal("fatal:\xe9")
stdout.seek(0) stdout.seek(0)
self.assertEquals(stdout.read().rstrip(), "debug:\\xe9") self.assertEqual(stdout.read().rstrip(), "debug:\\xe9")
stderr.seek(0) stderr.seek(0)
self.assertEquals(stderr.read().rstrip(), "fatal:\\xe9") self.assertEqual(stderr.read().rstrip(), "fatal:\\xe9")
finally: finally:
sys.stdout = old_stdout sys.stdout = old_stdout
sys.stderr = old_stderr sys.stderr = old_stderr

View File

@ -104,7 +104,7 @@ class msvc9compilerTestCase(support.TempdirManager,
import winreg import winreg
HKCU = winreg.HKEY_CURRENT_USER HKCU = winreg.HKEY_CURRENT_USER
keys = Reg.read_keys(HKCU, 'xxxx') keys = Reg.read_keys(HKCU, 'xxxx')
self.assertEquals(keys, None) self.assertEqual(keys, None)
keys = Reg.read_keys(HKCU, r'Control Panel') keys = Reg.read_keys(HKCU, r'Control Panel')
self.assertTrue('Desktop' in keys) self.assertTrue('Desktop' in keys)
@ -131,7 +131,7 @@ class msvc9compilerTestCase(support.TempdirManager,
f.close() f.close()
# makes sure the manifest was properly cleaned # makes sure the manifest was properly cleaned
self.assertEquals(content, _CLEANED_MANIFEST) self.assertEqual(content, _CLEANED_MANIFEST)
def test_suite(): def test_suite():

View File

@ -121,7 +121,7 @@ class RegisterTestCase(PyPIRCCommandTestCase):
f = open(self.rc) f = open(self.rc)
try: try:
content = f.read() content = f.read()
self.assertEquals(content, WANTED_PYPIRC) self.assertEqual(content, WANTED_PYPIRC)
finally: finally:
f.close() f.close()
@ -141,8 +141,8 @@ class RegisterTestCase(PyPIRCCommandTestCase):
req1 = dict(self.conn.reqs[0].headers) req1 = dict(self.conn.reqs[0].headers)
req2 = dict(self.conn.reqs[1].headers) req2 = dict(self.conn.reqs[1].headers)
self.assertEquals(req1['Content-length'], '1374') self.assertEqual(req1['Content-length'], '1374')
self.assertEquals(req2['Content-length'], '1374') self.assertEqual(req2['Content-length'], '1374')
self.assertTrue((b'xxx') in self.conn.reqs[1].data) self.assertTrue((b'xxx') in self.conn.reqs[1].data)
def test_password_not_in_file(self): def test_password_not_in_file(self):
@ -155,7 +155,7 @@ class RegisterTestCase(PyPIRCCommandTestCase):
# dist.password should be set # dist.password should be set
# therefore used afterwards by other commands # therefore used afterwards by other commands
self.assertEquals(cmd.distribution.password, 'password') self.assertEqual(cmd.distribution.password, 'password')
def test_registering(self): def test_registering(self):
# this test runs choice 2 # this test runs choice 2
@ -172,7 +172,7 @@ class RegisterTestCase(PyPIRCCommandTestCase):
self.assertTrue(self.conn.reqs, 1) self.assertTrue(self.conn.reqs, 1)
req = self.conn.reqs[0] req = self.conn.reqs[0]
headers = dict(req.headers) headers = dict(req.headers)
self.assertEquals(headers['Content-length'], '608') self.assertEqual(headers['Content-length'], '608')
self.assertTrue((b'tarek') in req.data) self.assertTrue((b'tarek') in req.data)
def test_password_reset(self): def test_password_reset(self):
@ -190,7 +190,7 @@ class RegisterTestCase(PyPIRCCommandTestCase):
self.assertTrue(self.conn.reqs, 1) self.assertTrue(self.conn.reqs, 1)
req = self.conn.reqs[0] req = self.conn.reqs[0]
headers = dict(req.headers) headers = dict(req.headers)
self.assertEquals(headers['Content-length'], '290') self.assertEqual(headers['Content-length'], '290')
self.assertTrue((b'tarek') in req.data) self.assertTrue((b'tarek') in req.data)
def test_strict(self): def test_strict(self):
@ -253,7 +253,7 @@ class RegisterTestCase(PyPIRCCommandTestCase):
with check_warnings() as w: with check_warnings() as w:
warnings.simplefilter("always") warnings.simplefilter("always")
cmd.check_metadata() cmd.check_metadata()
self.assertEquals(len(w.warnings), 1) self.assertEqual(len(w.warnings), 1)
def test_suite(): def test_suite():
return unittest.makeSuite(RegisterTestCase) return unittest.makeSuite(RegisterTestCase)

View File

@ -108,7 +108,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
# now let's check what we have # now let's check what we have
dist_folder = join(self.tmp_dir, 'dist') dist_folder = join(self.tmp_dir, 'dist')
files = os.listdir(dist_folder) files = os.listdir(dist_folder)
self.assertEquals(files, ['fake-1.0.zip']) self.assertEqual(files, ['fake-1.0.zip'])
zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip')) zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip'))
try: try:
@ -117,7 +117,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
zip_file.close() zip_file.close()
# making sure everything has been pruned correctly # making sure everything has been pruned correctly
self.assertEquals(len(content), 4) self.assertEqual(len(content), 4)
def test_make_distribution(self): def test_make_distribution(self):
@ -138,8 +138,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
dist_folder = join(self.tmp_dir, 'dist') dist_folder = join(self.tmp_dir, 'dist')
result = os.listdir(dist_folder) result = os.listdir(dist_folder)
result.sort() result.sort()
self.assertEquals(result, self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz'] )
['fake-1.0.tar', 'fake-1.0.tar.gz'] )
os.remove(join(dist_folder, 'fake-1.0.tar')) os.remove(join(dist_folder, 'fake-1.0.tar'))
os.remove(join(dist_folder, 'fake-1.0.tar.gz')) os.remove(join(dist_folder, 'fake-1.0.tar.gz'))
@ -152,8 +151,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
result = os.listdir(dist_folder) result = os.listdir(dist_folder)
result.sort() result.sort()
self.assertEquals(result, self.assertEqual(result, ['fake-1.0.tar', 'fake-1.0.tar.gz'])
['fake-1.0.tar', 'fake-1.0.tar.gz'])
def test_add_defaults(self): def test_add_defaults(self):
@ -201,7 +199,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
# now let's check what we have # now let's check what we have
dist_folder = join(self.tmp_dir, 'dist') dist_folder = join(self.tmp_dir, 'dist')
files = os.listdir(dist_folder) files = os.listdir(dist_folder)
self.assertEquals(files, ['fake-1.0.zip']) self.assertEqual(files, ['fake-1.0.zip'])
zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip')) zip_file = zipfile.ZipFile(join(dist_folder, 'fake-1.0.zip'))
try: try:
@ -210,13 +208,13 @@ class SDistTestCase(PyPIRCCommandTestCase):
zip_file.close() zip_file.close()
# making sure everything was added # making sure everything was added
self.assertEquals(len(content), 11) self.assertEqual(len(content), 11)
# checking the MANIFEST # checking the MANIFEST
f = open(join(self.tmp_dir, 'MANIFEST')) f = open(join(self.tmp_dir, 'MANIFEST'))
try: try:
manifest = f.read() manifest = f.read()
self.assertEquals(manifest, MANIFEST % {'sep': os.sep}) self.assertEqual(manifest, MANIFEST % {'sep': os.sep})
finally: finally:
f.close() f.close()
@ -229,7 +227,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
cmd.ensure_finalized() cmd.ensure_finalized()
cmd.run() cmd.run()
warnings = self.get_logs(WARN) warnings = self.get_logs(WARN)
self.assertEquals(len(warnings), 2) self.assertEqual(len(warnings), 2)
# trying with a complete set of metadata # trying with a complete set of metadata
self.clear_logs() self.clear_logs()
@ -238,7 +236,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
cmd.metadata_check = 0 cmd.metadata_check = 0
cmd.run() cmd.run()
warnings = self.get_logs(WARN) warnings = self.get_logs(WARN)
self.assertEquals(len(warnings), 0) self.assertEqual(len(warnings), 0)
def test_check_metadata_deprecated(self): def test_check_metadata_deprecated(self):
# makes sure make_metadata is deprecated # makes sure make_metadata is deprecated
@ -246,7 +244,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
with check_warnings() as w: with check_warnings() as w:
warnings.simplefilter("always") warnings.simplefilter("always")
cmd.check_metadata() cmd.check_metadata()
self.assertEquals(len(w.warnings), 1) self.assertEqual(len(w.warnings), 1)
def test_show_formats(self): def test_show_formats(self):
with captured_stdout() as stdout: with captured_stdout() as stdout:
@ -256,7 +254,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
num_formats = len(ARCHIVE_FORMATS.keys()) num_formats = len(ARCHIVE_FORMATS.keys())
output = [line for line in stdout.getvalue().split('\n') output = [line for line in stdout.getvalue().split('\n')
if line.strip().startswith('--formats=')] if line.strip().startswith('--formats=')]
self.assertEquals(len(output), num_formats) self.assertEqual(len(output), num_formats)
def test_finalize_options(self): def test_finalize_options(self):
@ -264,9 +262,9 @@ class SDistTestCase(PyPIRCCommandTestCase):
cmd.finalize_options() cmd.finalize_options()
# default options set by finalize # default options set by finalize
self.assertEquals(cmd.manifest, 'MANIFEST') self.assertEqual(cmd.manifest, 'MANIFEST')
self.assertEquals(cmd.template, 'MANIFEST.in') self.assertEqual(cmd.template, 'MANIFEST.in')
self.assertEquals(cmd.dist_dir, 'dist') self.assertEqual(cmd.dist_dir, 'dist')
# formats has to be a string splitable on (' ', ',') or # formats has to be a string splitable on (' ', ',') or
# a stringlist # a stringlist
@ -297,7 +295,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
finally: finally:
f.close() f.close()
self.assertEquals(len(manifest), 5) self.assertEqual(len(manifest), 5)
# adding a file # adding a file
self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#') self.write_file((self.tmp_dir, 'somecode', 'doc2.txt'), '#')
@ -317,7 +315,7 @@ class SDistTestCase(PyPIRCCommandTestCase):
f.close() f.close()
# do we have the new file in MANIFEST ? # do we have the new file in MANIFEST ?
self.assertEquals(len(manifest2), 6) self.assertEqual(len(manifest2), 6)
self.assertIn('doc2.txt', manifest2[-1]) self.assertIn('doc2.txt', manifest2[-1])
def test_manifest_marker(self): def test_manifest_marker(self):

View File

@ -20,7 +20,7 @@ class SpawnTestCase(support.TempdirManager,
(['nochange', 'nospace'], (['nochange', 'nospace'],
['nochange', 'nospace'])): ['nochange', 'nospace'])):
res = _nt_quote_args(args) res = _nt_quote_args(args)
self.assertEquals(res, wanted) self.assertEqual(res, wanted)
@unittest.skipUnless(os.name in ('nt', 'posix'), @unittest.skipUnless(os.name in ('nt', 'posix'),

View File

@ -70,7 +70,7 @@ class SysconfigTestCase(support.EnvironGuard,
comp = compiler() comp = compiler()
sysconfig.customize_compiler(comp) sysconfig.customize_compiler(comp)
self.assertEquals(comp.exes['archiver'], 'my_ar -arflags') self.assertEqual(comp.exes['archiver'], 'my_ar -arflags')
def test_parse_makefile_base(self): def test_parse_makefile_base(self):
self.makefile = TESTFN self.makefile = TESTFN
@ -81,8 +81,8 @@ class SysconfigTestCase(support.EnvironGuard,
finally: finally:
fd.close() fd.close()
d = sysconfig.parse_makefile(self.makefile) d = sysconfig.parse_makefile(self.makefile)
self.assertEquals(d, {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'", self.assertEqual(d, {'CONFIG_ARGS': "'--arg1=optarg1' 'ENV=LIB'",
'OTHER': 'foo'}) 'OTHER': 'foo'})
def test_parse_makefile_literal_dollar(self): def test_parse_makefile_literal_dollar(self):
self.makefile = TESTFN self.makefile = TESTFN
@ -93,16 +93,16 @@ class SysconfigTestCase(support.EnvironGuard,
finally: finally:
fd.close() fd.close()
d = sysconfig.parse_makefile(self.makefile) d = sysconfig.parse_makefile(self.makefile)
self.assertEquals(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'", self.assertEqual(d, {'CONFIG_ARGS': r"'--arg1=optarg1' 'ENV=\$LIB'",
'OTHER': 'foo'}) 'OTHER': 'foo'})
def test_sysconfig_module(self): def test_sysconfig_module(self):
import sysconfig as global_sysconfig import sysconfig as global_sysconfig
self.assertEquals(global_sysconfig.get_config_var('CFLAGS'), sysconfig.get_config_var('CFLAGS')) self.assertEqual(global_sysconfig.get_config_var('CFLAGS'), sysconfig.get_config_var('CFLAGS'))
self.assertEquals(global_sysconfig.get_config_var('LDFLAGS'), sysconfig.get_config_var('LDFLAGS')) self.assertEqual(global_sysconfig.get_config_var('LDFLAGS'), sysconfig.get_config_var('LDFLAGS'))
self.assertEquals(global_sysconfig.get_config_var('LDSHARED'),sysconfig.get_config_var('LDSHARED')) self.assertEqual(global_sysconfig.get_config_var('LDSHARED'),sysconfig.get_config_var('LDSHARED'))
self.assertEquals(global_sysconfig.get_config_var('CC'), sysconfig.get_config_var('CC')) self.assertEqual(global_sysconfig.get_config_var('CC'), sysconfig.get_config_var('CC'))

View File

@ -49,7 +49,7 @@ class TextFileTestCase(support.TempdirManager, unittest.TestCase):
def test_input(count, description, file, expected_result): def test_input(count, description, file, expected_result):
result = file.readlines() result = file.readlines()
self.assertEquals(result, expected_result) self.assertEqual(result, expected_result)
tmpdir = self.mkdtemp() tmpdir = self.mkdtemp()
filename = os.path.join(tmpdir, "test.txt") filename = os.path.join(tmpdir, "test.txt")

View File

@ -89,7 +89,7 @@ class uploadTestCase(PyPIRCCommandTestCase):
for attr, waited in (('username', 'me'), ('password', 'secret'), for attr, waited in (('username', 'me'), ('password', 'secret'),
('realm', 'pypi'), ('realm', 'pypi'),
('repository', 'http://pypi.python.org/pypi')): ('repository', 'http://pypi.python.org/pypi')):
self.assertEquals(getattr(cmd, attr), waited) self.assertEqual(getattr(cmd, attr), waited)
def test_saved_password(self): def test_saved_password(self):
# file with no password # file with no password
@ -99,14 +99,14 @@ class uploadTestCase(PyPIRCCommandTestCase):
dist = Distribution() dist = Distribution()
cmd = upload(dist) cmd = upload(dist)
cmd.finalize_options() cmd.finalize_options()
self.assertEquals(cmd.password, None) self.assertEqual(cmd.password, None)
# make sure we get it as well, if another command # make sure we get it as well, if another command
# initialized it at the dist level # initialized it at the dist level
dist.password = 'xxx' dist.password = 'xxx'
cmd = upload(dist) cmd = upload(dist)
cmd.finalize_options() cmd.finalize_options()
self.assertEquals(cmd.password, 'xxx') self.assertEqual(cmd.password, 'xxx')
def test_upload(self): def test_upload(self):
tmp = self.mkdtemp() tmp = self.mkdtemp()
@ -124,12 +124,12 @@ class uploadTestCase(PyPIRCCommandTestCase):
# what did we send ? # what did we send ?
headers = dict(self.conn.headers) headers = dict(self.conn.headers)
self.assertEquals(headers['Content-length'], '2087') self.assertEqual(headers['Content-length'], '2087')
self.assertTrue(headers['Content-type'].startswith('multipart/form-data')) self.assertTrue(headers['Content-type'].startswith('multipart/form-data'))
self.assertFalse('\n' in headers['Authorization']) self.assertFalse('\n' in headers['Authorization'])
self.assertEquals(self.conn.requests, [('POST', '/pypi')]) self.assertEqual(self.conn.requests, [('POST', '/pypi')])
self.assert_((b'xxx') in self.conn.body) self.assertTrue((b'xxx') in self.conn.body)
def test_suite(): def test_suite():
return unittest.makeSuite(uploadTestCase) return unittest.makeSuite(uploadTestCase)

View File

@ -67,21 +67,21 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) ' sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Intel)]') '[MSC v.1310 32 bit (Intel)]')
sys.platform = 'win32' sys.platform = 'win32'
self.assertEquals(get_platform(), 'win32') self.assertEqual(get_platform(), 'win32')
# windows XP, amd64 # windows XP, amd64
os.name = 'nt' os.name = 'nt'
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) ' sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Amd64)]') '[MSC v.1310 32 bit (Amd64)]')
sys.platform = 'win32' sys.platform = 'win32'
self.assertEquals(get_platform(), 'win-amd64') self.assertEqual(get_platform(), 'win-amd64')
# windows XP, itanium # windows XP, itanium
os.name = 'nt' os.name = 'nt'
sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) ' sys.version = ('2.4.4 (#71, Oct 18 2006, 08:34:43) '
'[MSC v.1310 32 bit (Itanium)]') '[MSC v.1310 32 bit (Itanium)]')
sys.platform = 'win32' sys.platform = 'win32'
self.assertEquals(get_platform(), 'win-ia64') self.assertEqual(get_platform(), 'win-ia64')
# macbook # macbook
os.name = 'posix' os.name = 'posix'
@ -100,7 +100,7 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
cursize = sys.maxsize cursize = sys.maxsize
sys.maxsize = (2 ** 31)-1 sys.maxsize = (2 ** 31)-1
try: try:
self.assertEquals(get_platform(), 'macosx-10.3-i386') self.assertEqual(get_platform(), 'macosx-10.3-i386')
finally: finally:
sys.maxsize = cursize sys.maxsize = cursize
@ -111,33 +111,33 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
'-fno-strict-aliasing -fno-common ' '-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3') '-dynamic -DNDEBUG -g -O3')
self.assertEquals(get_platform(), 'macosx-10.4-fat') self.assertEqual(get_platform(), 'macosx-10.4-fat')
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot ' get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk ' '/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common ' '-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3') '-dynamic -DNDEBUG -g -O3')
self.assertEquals(get_platform(), 'macosx-10.4-intel') self.assertEqual(get_platform(), 'macosx-10.4-intel')
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot ' get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk ' '/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common ' '-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3') '-dynamic -DNDEBUG -g -O3')
self.assertEquals(get_platform(), 'macosx-10.4-fat3') self.assertEqual(get_platform(), 'macosx-10.4-fat3')
get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot ' get_config_vars()['CFLAGS'] = ('-arch ppc64 -arch x86_64 -arch ppc -arch i386 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk ' '/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common ' '-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3') '-dynamic -DNDEBUG -g -O3')
self.assertEquals(get_platform(), 'macosx-10.4-universal') self.assertEqual(get_platform(), 'macosx-10.4-universal')
get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot ' get_config_vars()['CFLAGS'] = ('-arch x86_64 -arch ppc64 -isysroot '
'/Developer/SDKs/MacOSX10.4u.sdk ' '/Developer/SDKs/MacOSX10.4u.sdk '
'-fno-strict-aliasing -fno-common ' '-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3') '-dynamic -DNDEBUG -g -O3')
self.assertEquals(get_platform(), 'macosx-10.4-fat64') self.assertEqual(get_platform(), 'macosx-10.4-fat64')
for arch in ('ppc', 'i386', 'x86_64', 'ppc64'): for arch in ('ppc', 'i386', 'x86_64', 'ppc64'):
get_config_vars()['CFLAGS'] = ('-arch %s -isysroot ' get_config_vars()['CFLAGS'] = ('-arch %s -isysroot '
@ -145,7 +145,7 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
'-fno-strict-aliasing -fno-common ' '-fno-strict-aliasing -fno-common '
'-dynamic -DNDEBUG -g -O3'%(arch,)) '-dynamic -DNDEBUG -g -O3'%(arch,))
self.assertEquals(get_platform(), 'macosx-10.4-%s'%(arch,)) self.assertEqual(get_platform(), 'macosx-10.4-%s'%(arch,))
# linux debian sarge # linux debian sarge
os.name = 'posix' os.name = 'posix'
@ -155,7 +155,7 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7', self._set_uname(('Linux', 'aglae', '2.6.21.1dedibox-r7',
'#1 Mon Apr 30 17:25:38 CEST 2007', 'i686')) '#1 Mon Apr 30 17:25:38 CEST 2007', 'i686'))
self.assertEquals(get_platform(), 'linux-i686') self.assertEqual(get_platform(), 'linux-i686')
# XXX more platforms to tests here # XXX more platforms to tests here
@ -166,8 +166,8 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
return '/'.join(path) return '/'.join(path)
os.path.join = _join os.path.join = _join
self.assertEquals(convert_path('/home/to/my/stuff'), self.assertEqual(convert_path('/home/to/my/stuff'),
'/home/to/my/stuff') '/home/to/my/stuff')
# win # win
os.sep = '\\' os.sep = '\\'
@ -178,10 +178,10 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
self.assertRaises(ValueError, convert_path, '/home/to/my/stuff') self.assertRaises(ValueError, convert_path, '/home/to/my/stuff')
self.assertRaises(ValueError, convert_path, 'home/to/my/stuff/') self.assertRaises(ValueError, convert_path, 'home/to/my/stuff/')
self.assertEquals(convert_path('home/to/my/stuff'), self.assertEqual(convert_path('home/to/my/stuff'),
'home\\to\\my\\stuff') 'home\\to\\my\\stuff')
self.assertEquals(convert_path('.'), self.assertEqual(convert_path('.'),
os.curdir) os.curdir)
def test_change_root(self): def test_change_root(self):
# linux/mac # linux/mac
@ -193,10 +193,10 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
return '/'.join(path) return '/'.join(path)
os.path.join = _join os.path.join = _join
self.assertEquals(change_root('/root', '/old/its/here'), self.assertEqual(change_root('/root', '/old/its/here'),
'/root/old/its/here') '/root/old/its/here')
self.assertEquals(change_root('/root', 'its/here'), self.assertEqual(change_root('/root', 'its/here'),
'/root/its/here') '/root/its/here')
# windows # windows
os.name = 'nt' os.name = 'nt'
@ -212,10 +212,10 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
return '\\'.join(path) return '\\'.join(path)
os.path.join = _join os.path.join = _join
self.assertEquals(change_root('c:\\root', 'c:\\old\\its\\here'), self.assertEqual(change_root('c:\\root', 'c:\\old\\its\\here'),
'c:\\root\\old\\its\\here') 'c:\\root\\old\\its\\here')
self.assertEquals(change_root('c:\\root', 'its\\here'), self.assertEqual(change_root('c:\\root', 'its\\here'),
'c:\\root\\its\\here') 'c:\\root\\its\\here')
# BugsBunny os (it's a great os) # BugsBunny os (it's a great os)
os.name = 'BugsBunny' os.name = 'BugsBunny'
@ -233,16 +233,16 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
if os.name == 'posix': # this test won't run on windows if os.name == 'posix': # this test won't run on windows
check_environ() check_environ()
import pwd import pwd
self.assertEquals(os.environ['HOME'], pwd.getpwuid(os.getuid())[5]) self.assertEqual(os.environ['HOME'], pwd.getpwuid(os.getuid())[5])
else: else:
check_environ() check_environ()
self.assertEquals(os.environ['PLAT'], get_platform()) self.assertEqual(os.environ['PLAT'], get_platform())
self.assertEquals(util._environ_checked, 1) self.assertEqual(util._environ_checked, 1)
def test_split_quoted(self): def test_split_quoted(self):
self.assertEquals(split_quoted('""one"" "two" \'three\' \\four'), self.assertEqual(split_quoted('""one"" "two" \'three\' \\four'),
['one', 'two', 'three', 'four']) ['one', 'two', 'three', 'four'])
def test_strtobool(self): def test_strtobool(self):
yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1') yes = ('y', 'Y', 'yes', 'True', 't', 'true', 'True', 'On', 'on', '1')
@ -259,7 +259,7 @@ class UtilTestCase(support.EnvironGuard, unittest.TestCase):
res = rfc822_escape(header) res = rfc822_escape(header)
wanted = ('I am a%(8s)spoor%(8s)slonesome%(8s)s' wanted = ('I am a%(8s)spoor%(8s)slonesome%(8s)s'
'header%(8s)s') % {'8s': '\n'+8*' '} 'header%(8s)s') % {'8s': '\n'+8*' '}
self.assertEquals(res, wanted) self.assertEqual(res, wanted)
def test_dont_write_bytecode(self): def test_dont_write_bytecode(self):
# makes sure byte_compile raise a DistutilsError # makes sure byte_compile raise a DistutilsError

View File

@ -8,12 +8,12 @@ class VersionTestCase(unittest.TestCase):
def test_prerelease(self): def test_prerelease(self):
version = StrictVersion('1.2.3a1') version = StrictVersion('1.2.3a1')
self.assertEquals(version.version, (1, 2, 3)) self.assertEqual(version.version, (1, 2, 3))
self.assertEquals(version.prerelease, ('a', 1)) self.assertEqual(version.prerelease, ('a', 1))
self.assertEquals(str(version), '1.2.3a1') self.assertEqual(str(version), '1.2.3a1')
version = StrictVersion('1.2.0') version = StrictVersion('1.2.0')
self.assertEquals(str(version), '1.2') self.assertEqual(str(version), '1.2')
def test_cmp_strict(self): def test_cmp_strict(self):
versions = (('1.5.1', '1.5.2b2', -1), versions = (('1.5.1', '1.5.2b2', -1),
@ -42,9 +42,9 @@ class VersionTestCase(unittest.TestCase):
raise AssertionError(("cmp(%s, %s) " raise AssertionError(("cmp(%s, %s) "
"shouldn't raise ValueError") "shouldn't raise ValueError")
% (v1, v2)) % (v1, v2))
self.assertEquals(res, wanted, self.assertEqual(res, wanted,
'cmp(%s, %s) should be %s, got %s' % 'cmp(%s, %s) should be %s, got %s' %
(v1, v2, wanted, res)) (v1, v2, wanted, res))
def test_cmp(self): def test_cmp(self):
@ -60,9 +60,9 @@ class VersionTestCase(unittest.TestCase):
for v1, v2, wanted in versions: for v1, v2, wanted in versions:
res = LooseVersion(v1)._cmp(LooseVersion(v2)) res = LooseVersion(v1)._cmp(LooseVersion(v2))
self.assertEquals(res, wanted, self.assertEqual(res, wanted,
'cmp(%s, %s) should be %s, got %s' % 'cmp(%s, %s) should be %s, got %s' %
(v1, v2, wanted, res)) (v1, v2, wanted, res))
def test_suite(): def test_suite():
return unittest.makeSuite(VersionTestCase) return unittest.makeSuite(VersionTestCase)

View File

@ -44,13 +44,13 @@ EMPTYSTRING = ''
SPACE = ' ' SPACE = ' '
def openfile(filename, *args, **kws): def openfile(filename, *args, **kws):
path = os.path.join(os.path.dirname(landmark), 'data', filename) path = os.path.join(os.path.dirname(landmark), 'data', filename)
return open(path, *args, **kws) return open(path, *args, **kws)
# Base test class # Base test class
class TestEmailBase(unittest.TestCase): class TestEmailBase(unittest.TestCase):
def ndiffAssertEqual(self, first, second): def ndiffAssertEqual(self, first, second):
@ -68,7 +68,7 @@ class TestEmailBase(unittest.TestCase):
return email.message_from_file(fp) return email.message_from_file(fp)
# Test various aspects of the Message class's API # Test various aspects of the Message class's API
class TestMessageAPI(TestEmailBase): class TestMessageAPI(TestEmailBase):
def test_get_all(self): def test_get_all(self):
@ -510,7 +510,7 @@ class TestMessageAPI(TestEmailBase):
bytes(x, 'raw-unicode-escape')) bytes(x, 'raw-unicode-escape'))
# Test the email.encoders module # Test the email.encoders module
class TestEncoders(unittest.TestCase): class TestEncoders(unittest.TestCase):
def test_encode_empty_payload(self): def test_encode_empty_payload(self):
@ -539,7 +539,7 @@ class TestEncoders(unittest.TestCase):
msg = MIMEText('', _charset='euc-jp') msg = MIMEText('', _charset='euc-jp')
eq(msg['content-transfer-encoding'], '7bit') eq(msg['content-transfer-encoding'], '7bit')
# Test long header wrapping # Test long header wrapping
class TestLongHeaders(TestEmailBase): class TestLongHeaders(TestEmailBase):
def test_split_long_continuation(self): def test_split_long_continuation(self):
@ -918,7 +918,7 @@ List: List-Unsubscribe: <http://lists.sourceforge.net/lists/listinfo/spamassassi
""") """)
# Test mangling of "From " lines in the body of a message # Test mangling of "From " lines in the body of a message
class TestFromMangling(unittest.TestCase): class TestFromMangling(unittest.TestCase):
def setUp(self): def setUp(self):
@ -952,7 +952,7 @@ Blah blah blah
""") """)
# Test the basic MIMEAudio class # Test the basic MIMEAudio class
class TestMIMEAudio(unittest.TestCase): class TestMIMEAudio(unittest.TestCase):
def setUp(self): def setUp(self):
@ -999,7 +999,7 @@ class TestMIMEAudio(unittest.TestCase):
header='foobar') is missing) header='foobar') is missing)
# Test the basic MIMEImage class # Test the basic MIMEImage class
class TestMIMEImage(unittest.TestCase): class TestMIMEImage(unittest.TestCase):
def setUp(self): def setUp(self):
@ -1040,7 +1040,7 @@ class TestMIMEImage(unittest.TestCase):
header='foobar') is missing) header='foobar') is missing)
# Test the basic MIMEApplication class # Test the basic MIMEApplication class
class TestMIMEApplication(unittest.TestCase): class TestMIMEApplication(unittest.TestCase):
def test_headers(self): def test_headers(self):
@ -1057,7 +1057,7 @@ class TestMIMEApplication(unittest.TestCase):
eq(msg.get_payload(decode=True), bytes) eq(msg.get_payload(decode=True), bytes)
# Test the basic MIMEText class # Test the basic MIMEText class
class TestMIMEText(unittest.TestCase): class TestMIMEText(unittest.TestCase):
def setUp(self): def setUp(self):
@ -1111,7 +1111,7 @@ class TestMIMEText(unittest.TestCase):
self.assertRaises(UnicodeEncodeError, MIMEText, teststr) self.assertRaises(UnicodeEncodeError, MIMEText, teststr)
# Test complicated multipart/* messages # Test complicated multipart/* messages
class TestMultipart(TestEmailBase): class TestMultipart(TestEmailBase):
def setUp(self): def setUp(self):
@ -1483,10 +1483,10 @@ Content-Transfer-Encoding: base64
YXNkZg== YXNkZg==
--===============0012394164==--""") --===============0012394164==--""")
self.assertEquals(m.get_payload(0).get_payload(), 'YXNkZg==') self.assertEqual(m.get_payload(0).get_payload(), 'YXNkZg==')
# Test some badly formatted messages # Test some badly formatted messages
class TestNonConformant(TestEmailBase): class TestNonConformant(TestEmailBase):
def test_parse_missing_minor_type(self): def test_parse_missing_minor_type(self):
@ -1600,7 +1600,7 @@ counter to RFC 2822, there's no separating newline here
eq(msg.defects[0].line, ' Line 1\n') eq(msg.defects[0].line, ' Line 1\n')
# Test RFC 2047 header encoding and decoding # Test RFC 2047 header encoding and decoding
class TestRFC2047(TestEmailBase): class TestRFC2047(TestEmailBase):
def test_rfc2047_multiline(self): def test_rfc2047_multiline(self):
@ -1666,7 +1666,7 @@ Re: =?mac-iceland?q?r=8Aksm=9Arg=8Cs?= baz foo bar =?mac-iceland?q?r=8Aksm?=
self.assertEqual(decode_header(s), self.assertEqual(decode_header(s),
[(b'andr\xe9=zz', 'iso-8659-1')]) [(b'andr\xe9=zz', 'iso-8659-1')])
# Test the MIMEMessage class # Test the MIMEMessage class
class TestMIMEMessage(TestEmailBase): class TestMIMEMessage(TestEmailBase):
def setUp(self): def setUp(self):
@ -1967,7 +1967,7 @@ message 2
msg = MIMEMultipart() msg = MIMEMultipart()
self.assertTrue(msg.is_multipart()) self.assertTrue(msg.is_multipart())
# A general test of parser->model->generator idempotency. IOW, read a message # A general test of parser->model->generator idempotency. IOW, read a message
# in, parse it into a message object tree, then without touching the tree, # in, parse it into a message object tree, then without touching the tree,
# regenerate the plain text. The original text and the transformed text # regenerate the plain text. The original text and the transformed text
@ -1988,7 +1988,7 @@ class TestIdempotent(TestEmailBase):
eq(text, s.getvalue()) eq(text, s.getvalue())
def test_parse_text_message(self): def test_parse_text_message(self):
eq = self.assertEquals eq = self.assertEqual
msg, text = self._msgobj('msg_01.txt') msg, text = self._msgobj('msg_01.txt')
eq(msg.get_content_type(), 'text/plain') eq(msg.get_content_type(), 'text/plain')
eq(msg.get_content_maintype(), 'text') eq(msg.get_content_maintype(), 'text')
@ -2000,7 +2000,7 @@ class TestIdempotent(TestEmailBase):
self._idempotent(msg, text) self._idempotent(msg, text)
def test_parse_untyped_message(self): def test_parse_untyped_message(self):
eq = self.assertEquals eq = self.assertEqual
msg, text = self._msgobj('msg_03.txt') msg, text = self._msgobj('msg_03.txt')
eq(msg.get_content_type(), 'text/plain') eq(msg.get_content_type(), 'text/plain')
eq(msg.get_params(), None) eq(msg.get_params(), None)
@ -2076,7 +2076,7 @@ class TestIdempotent(TestEmailBase):
self._idempotent(msg, text) self._idempotent(msg, text)
def test_content_type(self): def test_content_type(self):
eq = self.assertEquals eq = self.assertEqual
unless = self.assertTrue unless = self.assertTrue
# Get a message object and reset the seek pointer for other tests # Get a message object and reset the seek pointer for other tests
msg, text = self._msgobj('msg_05.txt') msg, text = self._msgobj('msg_05.txt')
@ -2108,7 +2108,7 @@ class TestIdempotent(TestEmailBase):
eq(msg4.get_payload(), 'Yadda yadda yadda\n') eq(msg4.get_payload(), 'Yadda yadda yadda\n')
def test_parser(self): def test_parser(self):
eq = self.assertEquals eq = self.assertEqual
unless = self.assertTrue unless = self.assertTrue
msg, text = self._msgobj('msg_06.txt') msg, text = self._msgobj('msg_06.txt')
# Check some of the outer headers # Check some of the outer headers
@ -2125,7 +2125,7 @@ class TestIdempotent(TestEmailBase):
eq(msg1.get_payload(), '\n') eq(msg1.get_payload(), '\n')
# Test various other bits of the package's functionality # Test various other bits of the package's functionality
class TestMiscellaneous(TestEmailBase): class TestMiscellaneous(TestEmailBase):
def test_message_from_string(self): def test_message_from_string(self):
@ -2450,7 +2450,7 @@ multipart/report
""") """)
# Test the iterator/generators # Test the iterator/generators
class TestIterators(TestEmailBase): class TestIterators(TestEmailBase):
def test_body_line_iterator(self): def test_body_line_iterator(self):
@ -2540,7 +2540,7 @@ Do you like this message?
self.assertTrue(''.join([il for il, n in imt]) == ''.join(om)) self.assertTrue(''.join([il for il, n in imt]) == ''.join(om))
class TestParsers(TestEmailBase): class TestParsers(TestEmailBase):
def test_header_parser(self): def test_header_parser(self):
eq = self.assertEqual eq = self.assertEqual
@ -2704,7 +2704,7 @@ Here's the message body
msg = email.message_from_string(m) msg = email.message_from_string(m)
self.assertTrue(msg.get_payload(0).get_payload().endswith('\r\n')) self.assertTrue(msg.get_payload(0).get_payload().endswith('\r\n'))
class Test8BitBytesHandling(unittest.TestCase): class Test8BitBytesHandling(unittest.TestCase):
# In Python3 all input is string, but that doesn't work if the actual input # In Python3 all input is string, but that doesn't work if the actual input
# uses an 8bit transfer encoding. To hack around that, in email 5.1 we # uses an 8bit transfer encoding. To hack around that, in email 5.1 we
@ -2954,7 +2954,7 @@ class Test8BitBytesHandling(unittest.TestCase):
self.assertEqual(s.getvalue(), text) self.assertEqual(s.getvalue(), text)
maxDiff = None maxDiff = None
class TestBytesGeneratorIdempotent(TestIdempotent): class TestBytesGeneratorIdempotent(TestIdempotent):
maxDiff = None maxDiff = None
@ -2977,7 +2977,7 @@ class TestBytesGeneratorIdempotent(TestIdempotent):
self.assertListEqual(str1.split(b'\n'), str2.split(b'\n')) self.assertListEqual(str1.split(b'\n'), str2.split(b'\n'))
class TestBase64(unittest.TestCase): class TestBase64(unittest.TestCase):
def test_len(self): def test_len(self):
eq = self.assertEqual eq = self.assertEqual
@ -3030,7 +3030,7 @@ eHh4eCB4eHh4IA==\r
eq(he('hello\nworld'), '=?iso-8859-1?b?aGVsbG8Kd29ybGQ=?=') eq(he('hello\nworld'), '=?iso-8859-1?b?aGVsbG8Kd29ybGQ=?=')
class TestQuopri(unittest.TestCase): class TestQuopri(unittest.TestCase):
def setUp(self): def setUp(self):
# Set of characters (as byte integers) that don't need to be encoded # Set of characters (as byte integers) that don't need to be encoded
@ -3149,7 +3149,7 @@ one line
two line""") two line""")
# Test the Charset class # Test the Charset class
class TestCharset(unittest.TestCase): class TestCharset(unittest.TestCase):
def tearDown(self): def tearDown(self):
@ -3207,7 +3207,7 @@ class TestCharset(unittest.TestCase):
self.assertRaises(errors.CharsetError, Charset, 'asc\xffii') self.assertRaises(errors.CharsetError, Charset, 'asc\xffii')
# Test multilingual MIME headers. # Test multilingual MIME headers.
class TestHeader(TestEmailBase): class TestHeader(TestEmailBase):
def test_simple(self): def test_simple(self):
@ -3517,7 +3517,7 @@ A very long line that must get split to something other than at the
raises(errors.HeaderParseError, decode_header, s) raises(errors.HeaderParseError, decode_header, s)
# Test RFC 2231 header parameters (en/de)coding # Test RFC 2231 header parameters (en/de)coding
class TestRFC2231(TestEmailBase): class TestRFC2231(TestEmailBase):
def test_get_param(self): def test_get_param(self):
@ -3829,7 +3829,7 @@ Content-Type: application/x-foo;
eq(s, 'My Document For You') eq(s, 'My Document For You')
# Tests to ensure that signed parts of an email are completely preserved, as # Tests to ensure that signed parts of an email are completely preserved, as
# required by RFC1847 section 2.1. Note that these are incomplete, because the # required by RFC1847 section 2.1. Note that these are incomplete, because the
# email package does not currently always preserve the body. See issue 1670765. # email package does not currently always preserve the body. See issue 1670765.
@ -3867,7 +3867,7 @@ class TestSigned(TestEmailBase):
self._signed_parts_eq(original, result) self._signed_parts_eq(original, result)
def _testclasses(): def _testclasses():
mod = sys.modules[__name__] mod = sys.modules[__name__]
return [getattr(mod, name) for name in dir(mod) if name.startswith('Test')] return [getattr(mod, name) for name in dir(mod) if name.startswith('Test')]
@ -3885,6 +3885,6 @@ def test_main():
run_unittest(testclass) run_unittest(testclass)
if __name__ == '__main__': if __name__ == '__main__':
unittest.main(defaultTest='suite') unittest.main(defaultTest='suite')

View File

@ -42,7 +42,7 @@ class Using__package__(unittest.TestCase):
module = import_util.import_('', module = import_util.import_('',
globals={'__package__': 'pkg.fake'}, globals={'__package__': 'pkg.fake'},
fromlist=['attr'], level=2) fromlist=['attr'], level=2)
self.assertEquals(module.__name__, 'pkg') self.assertEqual(module.__name__, 'pkg')
def test_using___name__(self, package_as_None=False): def test_using___name__(self, package_as_None=False):
# [__name__] # [__name__]
@ -54,7 +54,7 @@ class Using__package__(unittest.TestCase):
import_util.import_('pkg.fake') import_util.import_('pkg.fake')
module = import_util.import_('', globals= globals_, module = import_util.import_('', globals= globals_,
fromlist=['attr'], level=2) fromlist=['attr'], level=2)
self.assertEquals(module.__name__, 'pkg') self.assertEqual(module.__name__, 'pkg')
def test_None_as___package__(self): def test_None_as___package__(self):
# [None] # [None]

View File

@ -54,7 +54,7 @@ class UseCache(unittest.TestCase):
with self.create_mock('module') as mock: with self.create_mock('module') as mock:
with util.import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
module = import_util.import_('module') module = import_util.import_('module')
self.assertEquals(id(module), id(sys.modules['module'])) self.assertEqual(id(module), id(sys.modules['module']))
# See test_using_cache_after_loader() for reasoning. # See test_using_cache_after_loader() for reasoning.
@import_util.importlib_only @import_util.importlib_only
@ -74,8 +74,8 @@ class UseCache(unittest.TestCase):
with util.import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_util.import_('pkg', fromlist=['module']) module = import_util.import_('pkg', fromlist=['module'])
self.assertTrue(hasattr(module, 'module')) self.assertTrue(hasattr(module, 'module'))
self.assertEquals(id(module.module), self.assertEqual(id(module.module),
id(sys.modules['pkg.module'])) id(sys.modules['pkg.module']))
def test_main(): def test_main():

View File

@ -19,14 +19,14 @@ class ReturnValue(unittest.TestCase):
with util.mock_modules('pkg.__init__', 'pkg.module') as importer: with util.mock_modules('pkg.__init__', 'pkg.module') as importer:
with util.import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_util.import_('pkg.module') module = import_util.import_('pkg.module')
self.assertEquals(module.__name__, 'pkg') self.assertEqual(module.__name__, 'pkg')
def test_return_from_from_import(self): def test_return_from_from_import(self):
# [from return] # [from return]
with util.mock_modules('pkg.__init__', 'pkg.module')as importer: with util.mock_modules('pkg.__init__', 'pkg.module')as importer:
with util.import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_util.import_('pkg.module', fromlist=['attr']) module = import_util.import_('pkg.module', fromlist=['attr'])
self.assertEquals(module.__name__, 'pkg.module') self.assertEqual(module.__name__, 'pkg.module')
class HandlingFromlist(unittest.TestCase): class HandlingFromlist(unittest.TestCase):
@ -51,14 +51,14 @@ class HandlingFromlist(unittest.TestCase):
with util.mock_modules('module') as importer: with util.mock_modules('module') as importer:
with util.import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_util.import_('module', fromlist=['attr']) module = import_util.import_('module', fromlist=['attr'])
self.assertEquals(module.__name__, 'module') self.assertEqual(module.__name__, 'module')
def test_unexistent_object(self): def test_unexistent_object(self):
# [bad object] # [bad object]
with util.mock_modules('module') as importer: with util.mock_modules('module') as importer:
with util.import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_util.import_('module', fromlist=['non_existent']) module = import_util.import_('module', fromlist=['non_existent'])
self.assertEquals(module.__name__, 'module') self.assertEqual(module.__name__, 'module')
self.assertTrue(not hasattr(module, 'non_existent')) self.assertTrue(not hasattr(module, 'non_existent'))
def test_module_from_package(self): def test_module_from_package(self):
@ -66,23 +66,23 @@ class HandlingFromlist(unittest.TestCase):
with util.mock_modules('pkg.__init__', 'pkg.module') as importer: with util.mock_modules('pkg.__init__', 'pkg.module') as importer:
with util.import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_util.import_('pkg', fromlist=['module']) module = import_util.import_('pkg', fromlist=['module'])
self.assertEquals(module.__name__, 'pkg') self.assertEqual(module.__name__, 'pkg')
self.assertTrue(hasattr(module, 'module')) self.assertTrue(hasattr(module, 'module'))
self.assertEquals(module.module.__name__, 'pkg.module') self.assertEqual(module.module.__name__, 'pkg.module')
def test_no_module_from_package(self): def test_no_module_from_package(self):
# [no module] # [no module]
with util.mock_modules('pkg.__init__') as importer: with util.mock_modules('pkg.__init__') as importer:
with util.import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_util.import_('pkg', fromlist='non_existent') module = import_util.import_('pkg', fromlist='non_existent')
self.assertEquals(module.__name__, 'pkg') self.assertEqual(module.__name__, 'pkg')
self.assertTrue(not hasattr(module, 'non_existent')) self.assertTrue(not hasattr(module, 'non_existent'))
def test_empty_string(self): def test_empty_string(self):
with util.mock_modules('pkg.__init__', 'pkg.mod') as importer: with util.mock_modules('pkg.__init__', 'pkg.mod') as importer:
with util.import_state(meta_path=[importer]): with util.import_state(meta_path=[importer]):
module = import_util.import_('pkg.mod', fromlist=['']) module = import_util.import_('pkg.mod', fromlist=[''])
self.assertEquals(module.__name__, 'pkg.mod') self.assertEqual(module.__name__, 'pkg.mod')
def basic_star_test(self, fromlist=['*']): def basic_star_test(self, fromlist=['*']):
# [using *] # [using *]
@ -90,7 +90,7 @@ class HandlingFromlist(unittest.TestCase):
with util.import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
mock['pkg'].__all__ = ['module'] mock['pkg'].__all__ = ['module']
module = import_util.import_('pkg', fromlist=fromlist) module = import_util.import_('pkg', fromlist=fromlist)
self.assertEquals(module.__name__, 'pkg') self.assertEqual(module.__name__, 'pkg')
self.assertTrue(hasattr(module, 'module')) self.assertTrue(hasattr(module, 'module'))
self.assertEqual(module.module.__name__, 'pkg.module') self.assertEqual(module.module.__name__, 'pkg.module')
@ -108,11 +108,11 @@ class HandlingFromlist(unittest.TestCase):
with util.import_state(meta_path=[mock]): with util.import_state(meta_path=[mock]):
mock['pkg'].__all__ = ['module1'] mock['pkg'].__all__ = ['module1']
module = import_util.import_('pkg', fromlist=['module2', '*']) module = import_util.import_('pkg', fromlist=['module2', '*'])
self.assertEquals(module.__name__, 'pkg') self.assertEqual(module.__name__, 'pkg')
self.assertTrue(hasattr(module, 'module1')) self.assertTrue(hasattr(module, 'module1'))
self.assertTrue(hasattr(module, 'module2')) self.assertTrue(hasattr(module, 'module2'))
self.assertEquals(module.module1.__name__, 'pkg.module1') self.assertEqual(module.module1.__name__, 'pkg.module1')
self.assertEquals(module.module2.__name__, 'pkg.module2') self.assertEqual(module.module2.__name__, 'pkg.module2')
def test_main(): def test_main():

View File

@ -21,7 +21,7 @@ class CallingOrder(unittest.TestCase):
first.modules[mod] = 42 first.modules[mod] = 42
second.modules[mod] = -13 second.modules[mod] = -13
with util.import_state(meta_path=[first, second]): with util.import_state(meta_path=[first, second]):
self.assertEquals(import_util.import_(mod), 42) self.assertEqual(import_util.import_(mod), 42)
def test_continuing(self): def test_continuing(self):
# [continuing] # [continuing]
@ -31,7 +31,7 @@ class CallingOrder(unittest.TestCase):
first.find_module = lambda self, fullname, path=None: None first.find_module = lambda self, fullname, path=None: None
second.modules[mod_name] = 42 second.modules[mod_name] = 42
with util.import_state(meta_path=[first, second]): with util.import_state(meta_path=[first, second]):
self.assertEquals(import_util.import_(mod_name), 42) self.assertEqual(import_util.import_(mod_name), 42)
class CallSignature(unittest.TestCase): class CallSignature(unittest.TestCase):
@ -61,9 +61,9 @@ class CallSignature(unittest.TestCase):
args = log[0][0] args = log[0][0]
kwargs = log[0][1] kwargs = log[0][1]
# Assuming all arguments are positional. # Assuming all arguments are positional.
self.assertEquals(len(args), 2) self.assertEqual(len(args), 2)
self.assertEquals(len(kwargs), 0) self.assertEqual(len(kwargs), 0)
self.assertEquals(args[0], mod_name) self.assertEqual(args[0], mod_name)
self.assertTrue(args[1] is None) self.assertTrue(args[1] is None)
def test_with_path(self): def test_with_path(self):
@ -83,7 +83,7 @@ class CallSignature(unittest.TestCase):
kwargs = log[1][1] kwargs = log[1][1]
# Assuming all arguments are positional. # Assuming all arguments are positional.
self.assertTrue(not kwargs) self.assertTrue(not kwargs)
self.assertEquals(args[0], mod_name) self.assertEqual(args[0], mod_name)
self.assertTrue(args[1] is path) self.assertTrue(args[1] is path)

View File

@ -24,12 +24,12 @@ class TestDecode(TestCase):
def test_decimal(self): def test_decimal(self):
rval = json.loads('1.1', parse_float=decimal.Decimal) rval = json.loads('1.1', parse_float=decimal.Decimal)
self.assertTrue(isinstance(rval, decimal.Decimal)) self.assertTrue(isinstance(rval, decimal.Decimal))
self.assertEquals(rval, decimal.Decimal('1.1')) self.assertEqual(rval, decimal.Decimal('1.1'))
def test_float(self): def test_float(self):
rval = json.loads('1', parse_int=float) rval = json.loads('1', parse_int=float)
self.assertTrue(isinstance(rval, float)) self.assertTrue(isinstance(rval, float))
self.assertEquals(rval, 1.0) self.assertEqual(rval, 1.0)
def test_object_pairs_hook(self): def test_object_pairs_hook(self):
s = '{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}' s = '{"xkd":1, "kcw":2, "art":3, "hxm":4, "qrt":5, "pad":6, "hoy":7}'
@ -53,7 +53,7 @@ class TestDecode(TestCase):
# the whitespace regex, so this test is designed to try and # the whitespace regex, so this test is designed to try and
# exercise the uncommon cases. The array cases are already covered. # exercise the uncommon cases. The array cases are already covered.
rval = json.loads('{ "key" : "value" , "k":"v" }') rval = json.loads('{ "key" : "value" , "k":"v" }')
self.assertEquals(rval, {"key":"value", "k":"v"}) self.assertEqual(rval, {"key":"value", "k":"v"})
def check_keys_reuse(self, source, loads): def check_keys_reuse(self, source, loads):
rval = loads(source) rval = loads(source)

View File

@ -4,6 +4,6 @@ import json
class TestDefault(TestCase): class TestDefault(TestCase):
def test_default(self): def test_default(self):
self.assertEquals( self.assertEqual(
json.dumps(type, default=repr), json.dumps(type, default=repr),
json.dumps(repr(type))) json.dumps(repr(type)))

View File

@ -7,15 +7,15 @@ class TestDump(TestCase):
def test_dump(self): def test_dump(self):
sio = StringIO() sio = StringIO()
json.dump({}, sio) json.dump({}, sio)
self.assertEquals(sio.getvalue(), '{}') self.assertEqual(sio.getvalue(), '{}')
def test_dumps(self): def test_dumps(self):
self.assertEquals(json.dumps({}), '{}') self.assertEqual(json.dumps({}), '{}')
def test_encode_truefalse(self): def test_encode_truefalse(self):
self.assertEquals(json.dumps( self.assertEqual(json.dumps(
{True: False, False: True}, sort_keys=True), {True: False, False: True}, sort_keys=True),
'{"false": true, "true": false}') '{"false": true, "true": false}')
self.assertEquals(json.dumps( self.assertEqual(json.dumps(
{2: 3.0, 4.0: 5, False: 1, 6: True}, sort_keys=True), {2: 3.0, 4.0: 5, False: 1, 6: True}, sort_keys=True),
'{"false": 1, "2": 3.0, "4.0": 5, "6": true}') '{"false": 1, "2": 3.0, "4.0": 5, "6": true}')

View File

@ -34,7 +34,7 @@ class TestEncodeBaseStringAscii(TestCase):
fname = encode_basestring_ascii.__name__ fname = encode_basestring_ascii.__name__
for input_string, expect in CASES: for input_string, expect in CASES:
result = encode_basestring_ascii(input_string) result = encode_basestring_ascii(input_string)
self.assertEquals(result, expect, self.assertEqual(result, expect,
'{0!r} != {1!r} for {2}({3!r})'.format( '{0!r} != {1!r} for {2}({3!r})'.format(
result, expect, fname, input_string)) result, expect, fname, input_string))

View File

@ -6,10 +6,10 @@ import json
class TestFloat(TestCase): class TestFloat(TestCase):
def test_floats(self): def test_floats(self):
for num in [1617161771.7650001, math.pi, math.pi**100, math.pi**-100, 3.1]: for num in [1617161771.7650001, math.pi, math.pi**100, math.pi**-100, 3.1]:
self.assertEquals(float(json.dumps(num)), num) self.assertEqual(float(json.dumps(num)), num)
self.assertEquals(json.loads(json.dumps(num)), num) self.assertEqual(json.loads(json.dumps(num)), num)
def test_ints(self): def test_ints(self):
for num in [1, 1<<32, 1<<64]: for num in [1, 1<<32, 1<<64]:
self.assertEquals(json.dumps(num), str(num)) self.assertEqual(json.dumps(num), str(num))
self.assertEquals(int(json.dumps(num)), num) self.assertEqual(int(json.dumps(num)), num)

View File

@ -38,8 +38,8 @@ class TestIndent(TestCase):
h2 = json.loads(d2) h2 = json.loads(d2)
h3 = json.loads(d3) h3 = json.loads(d3)
self.assertEquals(h1, h) self.assertEqual(h1, h)
self.assertEquals(h2, h) self.assertEqual(h2, h)
self.assertEquals(h3, h) self.assertEqual(h3, h)
self.assertEquals(d2, expect.expandtabs(2)) self.assertEqual(d2, expect.expandtabs(2))
self.assertEquals(d3, expect) self.assertEqual(d3, expect)

View File

@ -67,7 +67,7 @@ class TestPass1(TestCase):
# test in/out equivalence and parsing # test in/out equivalence and parsing
res = json.loads(JSON) res = json.loads(JSON)
out = json.dumps(res) out = json.dumps(res)
self.assertEquals(res, json.loads(out)) self.assertEqual(res, json.loads(out))
try: try:
json.dumps(res, allow_nan=False) json.dumps(res, allow_nan=False)
except ValueError: except ValueError:

View File

@ -11,4 +11,4 @@ class TestPass2(TestCase):
# test in/out equivalence and parsing # test in/out equivalence and parsing
res = json.loads(JSON) res = json.loads(JSON)
out = json.dumps(res) out = json.dumps(res)
self.assertEquals(res, json.loads(out)) self.assertEqual(res, json.loads(out))

View File

@ -17,4 +17,4 @@ class TestPass3(TestCase):
# test in/out equivalence and parsing # test in/out equivalence and parsing
res = json.loads(JSON) res = json.loads(JSON)
out = json.dumps(res) out = json.dumps(res)
self.assertEquals(res, json.loads(out)) self.assertEqual(res, json.loads(out))

View File

@ -57,7 +57,7 @@ class TestRecursion(TestCase):
def test_defaultrecursion(self): def test_defaultrecursion(self):
enc = RecursiveJSONEncoder() enc = RecursiveJSONEncoder()
self.assertEquals(enc.encode(JSONTestObject), '"JSONTestObject"') self.assertEqual(enc.encode(JSONTestObject), '"JSONTestObject"')
enc.recurse = True enc.recurse = True
try: try:
enc.encode(JSONTestObject) enc.encode(JSONTestObject)

View File

@ -14,92 +14,92 @@ class TestScanString(TestCase):
self._test_scanstring(json.decoder.c_scanstring) self._test_scanstring(json.decoder.c_scanstring)
def _test_scanstring(self, scanstring): def _test_scanstring(self, scanstring):
self.assertEquals( self.assertEqual(
scanstring('"z\\ud834\\udd20x"', 1, True), scanstring('"z\\ud834\\udd20x"', 1, True),
('z\U0001d120x', 16)) ('z\U0001d120x', 16))
if sys.maxunicode == 65535: if sys.maxunicode == 65535:
self.assertEquals( self.assertEqual(
scanstring('"z\U0001d120x"', 1, True), scanstring('"z\U0001d120x"', 1, True),
('z\U0001d120x', 6)) ('z\U0001d120x', 6))
else: else:
self.assertEquals( self.assertEqual(
scanstring('"z\U0001d120x"', 1, True), scanstring('"z\U0001d120x"', 1, True),
('z\U0001d120x', 5)) ('z\U0001d120x', 5))
self.assertEquals( self.assertEqual(
scanstring('"\\u007b"', 1, True), scanstring('"\\u007b"', 1, True),
('{', 8)) ('{', 8))
self.assertEquals( self.assertEqual(
scanstring('"A JSON payload should be an object or array, not a string."', 1, True), scanstring('"A JSON payload should be an object or array, not a string."', 1, True),
('A JSON payload should be an object or array, not a string.', 60)) ('A JSON payload should be an object or array, not a string.', 60))
self.assertEquals( self.assertEqual(
scanstring('["Unclosed array"', 2, True), scanstring('["Unclosed array"', 2, True),
('Unclosed array', 17)) ('Unclosed array', 17))
self.assertEquals( self.assertEqual(
scanstring('["extra comma",]', 2, True), scanstring('["extra comma",]', 2, True),
('extra comma', 14)) ('extra comma', 14))
self.assertEquals( self.assertEqual(
scanstring('["double extra comma",,]', 2, True), scanstring('["double extra comma",,]', 2, True),
('double extra comma', 21)) ('double extra comma', 21))
self.assertEquals( self.assertEqual(
scanstring('["Comma after the close"],', 2, True), scanstring('["Comma after the close"],', 2, True),
('Comma after the close', 24)) ('Comma after the close', 24))
self.assertEquals( self.assertEqual(
scanstring('["Extra close"]]', 2, True), scanstring('["Extra close"]]', 2, True),
('Extra close', 14)) ('Extra close', 14))
self.assertEquals( self.assertEqual(
scanstring('{"Extra comma": true,}', 2, True), scanstring('{"Extra comma": true,}', 2, True),
('Extra comma', 14)) ('Extra comma', 14))
self.assertEquals( self.assertEqual(
scanstring('{"Extra value after close": true} "misplaced quoted value"', 2, True), scanstring('{"Extra value after close": true} "misplaced quoted value"', 2, True),
('Extra value after close', 26)) ('Extra value after close', 26))
self.assertEquals( self.assertEqual(
scanstring('{"Illegal expression": 1 + 2}', 2, True), scanstring('{"Illegal expression": 1 + 2}', 2, True),
('Illegal expression', 21)) ('Illegal expression', 21))
self.assertEquals( self.assertEqual(
scanstring('{"Illegal invocation": alert()}', 2, True), scanstring('{"Illegal invocation": alert()}', 2, True),
('Illegal invocation', 21)) ('Illegal invocation', 21))
self.assertEquals( self.assertEqual(
scanstring('{"Numbers cannot have leading zeroes": 013}', 2, True), scanstring('{"Numbers cannot have leading zeroes": 013}', 2, True),
('Numbers cannot have leading zeroes', 37)) ('Numbers cannot have leading zeroes', 37))
self.assertEquals( self.assertEqual(
scanstring('{"Numbers cannot be hex": 0x14}', 2, True), scanstring('{"Numbers cannot be hex": 0x14}', 2, True),
('Numbers cannot be hex', 24)) ('Numbers cannot be hex', 24))
self.assertEquals( self.assertEqual(
scanstring('[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]', 21, True), scanstring('[[[[[[[[[[[[[[[[[[[["Too deep"]]]]]]]]]]]]]]]]]]]]', 21, True),
('Too deep', 30)) ('Too deep', 30))
self.assertEquals( self.assertEqual(
scanstring('{"Missing colon" null}', 2, True), scanstring('{"Missing colon" null}', 2, True),
('Missing colon', 16)) ('Missing colon', 16))
self.assertEquals( self.assertEqual(
scanstring('{"Double colon":: null}', 2, True), scanstring('{"Double colon":: null}', 2, True),
('Double colon', 15)) ('Double colon', 15))
self.assertEquals( self.assertEqual(
scanstring('{"Comma instead of colon", null}', 2, True), scanstring('{"Comma instead of colon", null}', 2, True),
('Comma instead of colon', 25)) ('Comma instead of colon', 25))
self.assertEquals( self.assertEqual(
scanstring('["Colon instead of comma": false]', 2, True), scanstring('["Colon instead of comma": false]', 2, True),
('Colon instead of comma', 25)) ('Colon instead of comma', 25))
self.assertEquals( self.assertEqual(
scanstring('["Bad value", truth]', 2, True), scanstring('["Bad value", truth]', 2, True),
('Bad value', 12)) ('Bad value', 12))

View File

@ -37,6 +37,6 @@ class TestSeparators(TestCase):
h1 = json.loads(d1) h1 = json.loads(d1)
h2 = json.loads(d2) h2 = json.loads(d2)
self.assertEquals(h1, h) self.assertEqual(h1, h)
self.assertEquals(h2, h) self.assertEqual(h2, h)
self.assertEquals(d2, expect) self.assertEqual(d2, expect)

View File

@ -5,11 +5,11 @@ from json import decoder, encoder, scanner
class TestSpeedups(TestCase): class TestSpeedups(TestCase):
def test_scanstring(self): def test_scanstring(self):
self.assertEquals(decoder.scanstring.__module__, "_json") self.assertEqual(decoder.scanstring.__module__, "_json")
self.assertTrue(decoder.scanstring is decoder.c_scanstring) self.assertTrue(decoder.scanstring is decoder.c_scanstring)
def test_encode_basestring_ascii(self): def test_encode_basestring_ascii(self):
self.assertEquals(encoder.encode_basestring_ascii.__module__, "_json") self.assertEqual(encoder.encode_basestring_ascii.__module__, "_json")
self.assertTrue(encoder.encode_basestring_ascii is self.assertTrue(encoder.encode_basestring_ascii is
encoder.c_encode_basestring_ascii) encoder.c_encode_basestring_ascii)

View File

@ -10,43 +10,43 @@ class TestUnicode(TestCase):
def test_encoding3(self): def test_encoding3(self):
u = '\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' u = '\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
j = json.dumps(u) j = json.dumps(u)
self.assertEquals(j, '"\\u03b1\\u03a9"') self.assertEqual(j, '"\\u03b1\\u03a9"')
def test_encoding4(self): def test_encoding4(self):
u = '\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' u = '\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
j = json.dumps([u]) j = json.dumps([u])
self.assertEquals(j, '["\\u03b1\\u03a9"]') self.assertEqual(j, '["\\u03b1\\u03a9"]')
def test_encoding5(self): def test_encoding5(self):
u = '\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' u = '\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
j = json.dumps(u, ensure_ascii=False) j = json.dumps(u, ensure_ascii=False)
self.assertEquals(j, '"{0}"'.format(u)) self.assertEqual(j, '"{0}"'.format(u))
def test_encoding6(self): def test_encoding6(self):
u = '\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}' u = '\N{GREEK SMALL LETTER ALPHA}\N{GREEK CAPITAL LETTER OMEGA}'
j = json.dumps([u], ensure_ascii=False) j = json.dumps([u], ensure_ascii=False)
self.assertEquals(j, '["{0}"]'.format(u)) self.assertEqual(j, '["{0}"]'.format(u))
def test_big_unicode_encode(self): def test_big_unicode_encode(self):
u = '\U0001d120' u = '\U0001d120'
self.assertEquals(json.dumps(u), '"\\ud834\\udd20"') self.assertEqual(json.dumps(u), '"\\ud834\\udd20"')
self.assertEquals(json.dumps(u, ensure_ascii=False), '"\U0001d120"') self.assertEqual(json.dumps(u, ensure_ascii=False), '"\U0001d120"')
def test_big_unicode_decode(self): def test_big_unicode_decode(self):
u = 'z\U0001d120x' u = 'z\U0001d120x'
self.assertEquals(json.loads('"' + u + '"'), u) self.assertEqual(json.loads('"' + u + '"'), u)
self.assertEquals(json.loads('"z\\ud834\\udd20x"'), u) self.assertEqual(json.loads('"z\\ud834\\udd20x"'), u)
def test_unicode_decode(self): def test_unicode_decode(self):
for i in range(0, 0xd7ff): for i in range(0, 0xd7ff):
u = chr(i) u = chr(i)
s = '"\\u{0:04x}"'.format(i) s = '"\\u{0:04x}"'.format(i)
self.assertEquals(json.loads(s), u) self.assertEqual(json.loads(s), u)
def test_unicode_preservation(self): def test_unicode_preservation(self):
self.assertEquals(type(json.loads('""')), str) self.assertEqual(type(json.loads('""')), str)
self.assertEquals(type(json.loads('"a"')), str) self.assertEqual(type(json.loads('"a"')), str)
self.assertEquals(type(json.loads('["a"]')[0]), str) self.assertEqual(type(json.loads('["a"]')[0]), str)
def test_bytes_encode(self): def test_bytes_encode(self):
self.assertRaises(TypeError, json.dumps, b"hi") self.assertRaises(TypeError, json.dumps, b"hi")

View File

@ -20,21 +20,21 @@ class TokenTests(unittest.TestCase):
# Backslash means line continuation: # Backslash means line continuation:
x = 1 \ x = 1 \
+ 1 + 1
self.assertEquals(x, 2, 'backslash for line continuation') self.assertEqual(x, 2, 'backslash for line continuation')
# Backslash does not means continuation in comments :\ # Backslash does not means continuation in comments :\
x = 0 x = 0
self.assertEquals(x, 0, 'backslash ending comment') self.assertEqual(x, 0, 'backslash ending comment')
def testPlainIntegers(self): def testPlainIntegers(self):
self.assertEquals(0xff, 255) self.assertEqual(0xff, 255)
self.assertEquals(0377, 255) self.assertEqual(0377, 255)
self.assertEquals(2147483647, 017777777777) self.assertEqual(2147483647, 017777777777)
# "0x" is not a valid literal # "0x" is not a valid literal
self.assertRaises(SyntaxError, eval, "0x") self.assertRaises(SyntaxError, eval, "0x")
from sys import maxint from sys import maxint
if maxint == 2147483647: if maxint == 2147483647:
self.assertEquals(-2147483647-1, -020000000000) self.assertEqual(-2147483647-1, -020000000000)
# XXX -2147483648 # XXX -2147483648
self.assert_(037777777777 > 0) self.assert_(037777777777 > 0)
self.assert_(0xffffffff > 0) self.assert_(0xffffffff > 0)
@ -44,7 +44,7 @@ class TokenTests(unittest.TestCase):
except OverflowError: except OverflowError:
self.fail("OverflowError on huge integer literal %r" % s) self.fail("OverflowError on huge integer literal %r" % s)
elif maxint == 9223372036854775807: elif maxint == 9223372036854775807:
self.assertEquals(-9223372036854775807-1, -01000000000000000000000) self.assertEqual(-9223372036854775807-1, -01000000000000000000000)
self.assert_(01777777777777777777777 > 0) self.assert_(01777777777777777777777 > 0)
self.assert_(0xffffffffffffffff > 0) self.assert_(0xffffffffffffffff > 0)
for s in '9223372036854775808', '02000000000000000000000', \ for s in '9223372036854775808', '02000000000000000000000', \
@ -97,28 +97,28 @@ jumps over
the 'lazy' dog. the 'lazy' dog.
""" """
y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
self.assertEquals(x, y) self.assertEqual(x, y)
y = ''' y = '''
The "quick" The "quick"
brown fox brown fox
jumps over jumps over
the 'lazy' dog. the 'lazy' dog.
''' '''
self.assertEquals(x, y) self.assertEqual(x, y)
y = "\n\ y = "\n\
The \"quick\"\n\ The \"quick\"\n\
brown fox\n\ brown fox\n\
jumps over\n\ jumps over\n\
the 'lazy' dog.\n\ the 'lazy' dog.\n\
" "
self.assertEquals(x, y) self.assertEqual(x, y)
y = '\n\ y = '\n\
The \"quick\"\n\ The \"quick\"\n\
brown fox\n\ brown fox\n\
jumps over\n\ jumps over\n\
the \'lazy\' dog.\n\ the \'lazy\' dog.\n\
' '
self.assertEquals(x, y) self.assertEqual(x, y)
class GrammarTests(unittest.TestCase): class GrammarTests(unittest.TestCase):
@ -154,18 +154,18 @@ class GrammarTests(unittest.TestCase):
def f3(two, arguments): pass def f3(two, arguments): pass
def f4(two, (compound, (argument, list))): pass def f4(two, (compound, (argument, list))): pass
def f5((compound, first), two): pass def f5((compound, first), two): pass
self.assertEquals(f2.func_code.co_varnames, ('one_argument',)) self.assertEqual(f2.func_code.co_varnames, ('one_argument',))
self.assertEquals(f3.func_code.co_varnames, ('two', 'arguments')) self.assertEqual(f3.func_code.co_varnames, ('two', 'arguments'))
if sys.platform.startswith('java'): if sys.platform.startswith('java'):
self.assertEquals(f4.func_code.co_varnames, self.assertEqual(f4.func_code.co_varnames,
('two', '(compound, (argument, list))', 'compound', 'argument', ('two', '(compound, (argument, list))', 'compound', 'argument',
'list',)) 'list',))
self.assertEquals(f5.func_code.co_varnames, self.assertEqual(f5.func_code.co_varnames,
('(compound, first)', 'two', 'compound', 'first')) ('(compound, first)', 'two', 'compound', 'first'))
else: else:
self.assertEquals(f4.func_code.co_varnames, self.assertEqual(f4.func_code.co_varnames,
('two', '.1', 'compound', 'argument', 'list')) ('two', '.1', 'compound', 'argument', 'list'))
self.assertEquals(f5.func_code.co_varnames, self.assertEqual(f5.func_code.co_varnames,
('.0', 'two', 'compound', 'first')) ('.0', 'two', 'compound', 'first'))
def a1(one_arg,): pass def a1(one_arg,): pass
def a2(two, args,): pass def a2(two, args,): pass
@ -201,10 +201,10 @@ class GrammarTests(unittest.TestCase):
# ceval unpacks the formal arguments into the first argcount names; # ceval unpacks the formal arguments into the first argcount names;
# thus, the names nested inside tuples must appear after these names. # thus, the names nested inside tuples must appear after these names.
if sys.platform.startswith('java'): if sys.platform.startswith('java'):
self.assertEquals(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c')) self.assertEqual(v3.func_code.co_varnames, ('a', '(b, c)', 'rest', 'b', 'c'))
else: else:
self.assertEquals(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c')) self.assertEqual(v3.func_code.co_varnames, ('a', '.1', 'rest', 'b', 'c'))
self.assertEquals(v3(1, (2, 3), 4), (1, 2, 3, (4,))) self.assertEqual(v3(1, (2, 3), 4), (1, 2, 3, (4,)))
def d01(a=1): pass def d01(a=1): pass
d01() d01()
d01(1) d01(1)
@ -285,7 +285,7 @@ class GrammarTests(unittest.TestCase):
# keyword arguments after *arglist # keyword arguments after *arglist
def f(*args, **kwargs): def f(*args, **kwargs):
return args, kwargs return args, kwargs
self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4), self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
{'x':2, 'y':5})) {'x':2, 'y':5}))
self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)") self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)") self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
@ -297,15 +297,15 @@ class GrammarTests(unittest.TestCase):
def testLambdef(self): def testLambdef(self):
### lambdef: 'lambda' [varargslist] ':' test ### lambdef: 'lambda' [varargslist] ':' test
l1 = lambda : 0 l1 = lambda : 0
self.assertEquals(l1(), 0) self.assertEqual(l1(), 0)
l2 = lambda : a[d] # XXX just testing the expression l2 = lambda : a[d] # XXX just testing the expression
l3 = lambda : [2 < x for x in [-1, 3, 0L]] l3 = lambda : [2 < x for x in [-1, 3, 0L]]
self.assertEquals(l3(), [0, 1, 0]) self.assertEqual(l3(), [0, 1, 0])
l4 = lambda x = lambda y = lambda z=1 : z : y() : x() l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
self.assertEquals(l4(), 1) self.assertEqual(l4(), 1)
l5 = lambda x, y, z=2: x + y + z l5 = lambda x, y, z=2: x + y + z
self.assertEquals(l5(1, 2), 5) self.assertEqual(l5(1, 2), 5)
self.assertEquals(l5(1, 2, 3), 6) self.assertEqual(l5(1, 2, 3), 6)
check_syntax_error(self, "lambda x: x = 2") check_syntax_error(self, "lambda x: x = 2")
check_syntax_error(self, "lambda (None,): None") check_syntax_error(self, "lambda (None,): None")
@ -558,7 +558,7 @@ hello world
try: try:
assert 0, "msg" assert 0, "msg"
except AssertionError, e: except AssertionError, e:
self.assertEquals(e.args[0], "msg") self.assertEqual(e.args[0], "msg")
else: else:
if __debug__: if __debug__:
self.fail("AssertionError not raised by assert 0") self.fail("AssertionError not raised by assert 0")
@ -592,7 +592,7 @@ hello world
x = 1 x = 1
else: else:
x = 2 x = 2
self.assertEquals(x, 2) self.assertEqual(x, 2)
def testFor(self): def testFor(self):
# 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
@ -745,7 +745,7 @@ hello world
d[1,2,3] = 4 d[1,2,3] = 4
L = list(d) L = list(d)
L.sort() L.sort()
self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]') self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
def testAtoms(self): def testAtoms(self):
### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING

View File

@ -20,23 +20,23 @@ class TokenTests(unittest.TestCase):
# Backslash means line continuation: # Backslash means line continuation:
x = 1 \ x = 1 \
+ 1 + 1
self.assertEquals(x, 2, 'backslash for line continuation') self.assertEqual(x, 2, 'backslash for line continuation')
# Backslash does not means continuation in comments :\ # Backslash does not means continuation in comments :\
x = 0 x = 0
self.assertEquals(x, 0, 'backslash ending comment') self.assertEqual(x, 0, 'backslash ending comment')
def testPlainIntegers(self): def testPlainIntegers(self):
self.assertEquals(type(000), type(0)) self.assertEqual(type(000), type(0))
self.assertEquals(0xff, 255) self.assertEqual(0xff, 255)
self.assertEquals(0o377, 255) self.assertEqual(0o377, 255)
self.assertEquals(2147483647, 0o17777777777) self.assertEqual(2147483647, 0o17777777777)
self.assertEquals(0b1001, 9) self.assertEqual(0b1001, 9)
# "0x" is not a valid literal # "0x" is not a valid literal
self.assertRaises(SyntaxError, eval, "0x") self.assertRaises(SyntaxError, eval, "0x")
from sys import maxsize from sys import maxsize
if maxsize == 2147483647: if maxsize == 2147483647:
self.assertEquals(-2147483647-1, -0o20000000000) self.assertEqual(-2147483647-1, -0o20000000000)
# XXX -2147483648 # XXX -2147483648
self.assert_(0o37777777777 > 0) self.assert_(0o37777777777 > 0)
self.assert_(0xffffffff > 0) self.assert_(0xffffffff > 0)
@ -48,7 +48,7 @@ class TokenTests(unittest.TestCase):
except OverflowError: except OverflowError:
self.fail("OverflowError on huge integer literal %r" % s) self.fail("OverflowError on huge integer literal %r" % s)
elif maxsize == 9223372036854775807: elif maxsize == 9223372036854775807:
self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000) self.assertEqual(-9223372036854775807-1, -0o1000000000000000000000)
self.assert_(0o1777777777777777777777 > 0) self.assert_(0o1777777777777777777777 > 0)
self.assert_(0xffffffffffffffff > 0) self.assert_(0xffffffffffffffff > 0)
self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0) self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
@ -103,28 +103,28 @@ jumps over
the 'lazy' dog. the 'lazy' dog.
""" """
y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n' y = '\nThe "quick"\nbrown fox\njumps over\nthe \'lazy\' dog.\n'
self.assertEquals(x, y) self.assertEqual(x, y)
y = ''' y = '''
The "quick" The "quick"
brown fox brown fox
jumps over jumps over
the 'lazy' dog. the 'lazy' dog.
''' '''
self.assertEquals(x, y) self.assertEqual(x, y)
y = "\n\ y = "\n\
The \"quick\"\n\ The \"quick\"\n\
brown fox\n\ brown fox\n\
jumps over\n\ jumps over\n\
the 'lazy' dog.\n\ the 'lazy' dog.\n\
" "
self.assertEquals(x, y) self.assertEqual(x, y)
y = '\n\ y = '\n\
The \"quick\"\n\ The \"quick\"\n\
brown fox\n\ brown fox\n\
jumps over\n\ jumps over\n\
the \'lazy\' dog.\n\ the \'lazy\' dog.\n\
' '
self.assertEquals(x, y) self.assertEqual(x, y)
def testEllipsis(self): def testEllipsis(self):
x = ... x = ...
@ -165,8 +165,8 @@ class GrammarTests(unittest.TestCase):
f1(*(), **{}) f1(*(), **{})
def f2(one_argument): pass def f2(one_argument): pass
def f3(two, arguments): pass def f3(two, arguments): pass
self.assertEquals(f2.__code__.co_varnames, ('one_argument',)) self.assertEqual(f2.__code__.co_varnames, ('one_argument',))
self.assertEquals(f3.__code__.co_varnames, ('two', 'arguments')) self.assertEqual(f3.__code__.co_varnames, ('two', 'arguments'))
def a1(one_arg,): pass def a1(one_arg,): pass
def a2(two, args,): pass def a2(two, args,): pass
def v0(*rest): pass def v0(*rest): pass
@ -287,37 +287,37 @@ class GrammarTests(unittest.TestCase):
# keyword arguments after *arglist # keyword arguments after *arglist
def f(*args, **kwargs): def f(*args, **kwargs):
return args, kwargs return args, kwargs
self.assertEquals(f(1, x=2, *[3, 4], y=5), ((1, 3, 4), self.assertEqual(f(1, x=2, *[3, 4], y=5), ((1, 3, 4),
{'x':2, 'y':5})) {'x':2, 'y':5}))
self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)") self.assertRaises(SyntaxError, eval, "f(1, *(2,3), 4)")
self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)") self.assertRaises(SyntaxError, eval, "f(1, x=2, *(3,4), x=5)")
# argument annotation tests # argument annotation tests
def f(x) -> list: pass def f(x) -> list: pass
self.assertEquals(f.__annotations__, {'return': list}) self.assertEqual(f.__annotations__, {'return': list})
def f(x:int): pass def f(x:int): pass
self.assertEquals(f.__annotations__, {'x': int}) self.assertEqual(f.__annotations__, {'x': int})
def f(*x:str): pass def f(*x:str): pass
self.assertEquals(f.__annotations__, {'x': str}) self.assertEqual(f.__annotations__, {'x': str})
def f(**x:float): pass def f(**x:float): pass
self.assertEquals(f.__annotations__, {'x': float}) self.assertEqual(f.__annotations__, {'x': float})
def f(x, y:1+2): pass def f(x, y:1+2): pass
self.assertEquals(f.__annotations__, {'y': 3}) self.assertEqual(f.__annotations__, {'y': 3})
def f(a, b:1, c:2, d): pass def f(a, b:1, c:2, d): pass
self.assertEquals(f.__annotations__, {'b': 1, 'c': 2}) self.assertEqual(f.__annotations__, {'b': 1, 'c': 2})
def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass def f(a, b:1, c:2, d, e:3=4, f=5, *g:6): pass
self.assertEquals(f.__annotations__, self.assertEqual(f.__annotations__,
{'b': 1, 'c': 2, 'e': 3, 'g': 6}) {'b': 1, 'c': 2, 'e': 3, 'g': 6})
def f(a, b:1, c:2, d, e:3=4, f=5, *g:6, h:7, i=8, j:9=10, def f(a, b:1, c:2, d, e:3=4, f=5, *g:6, h:7, i=8, j:9=10,
**k:11) -> 12: pass **k:11) -> 12: pass
self.assertEquals(f.__annotations__, self.assertEqual(f.__annotations__,
{'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9, {'b': 1, 'c': 2, 'e': 3, 'g': 6, 'h': 7, 'j': 9,
'k': 11, 'return': 12}) 'k': 11, 'return': 12})
# Check for SF Bug #1697248 - mixing decorators and a return annotation # Check for SF Bug #1697248 - mixing decorators and a return annotation
def null(x): return x def null(x): return x
@null @null
def f(x) -> list: pass def f(x) -> list: pass
self.assertEquals(f.__annotations__, {'return': list}) self.assertEqual(f.__annotations__, {'return': list})
# test MAKE_CLOSURE with a variety of oparg's # test MAKE_CLOSURE with a variety of oparg's
closure = 1 closure = 1
@ -333,20 +333,20 @@ class GrammarTests(unittest.TestCase):
def testLambdef(self): def testLambdef(self):
### lambdef: 'lambda' [varargslist] ':' test ### lambdef: 'lambda' [varargslist] ':' test
l1 = lambda : 0 l1 = lambda : 0
self.assertEquals(l1(), 0) self.assertEqual(l1(), 0)
l2 = lambda : a[d] # XXX just testing the expression l2 = lambda : a[d] # XXX just testing the expression
l3 = lambda : [2 < x for x in [-1, 3, 0]] l3 = lambda : [2 < x for x in [-1, 3, 0]]
self.assertEquals(l3(), [0, 1, 0]) self.assertEqual(l3(), [0, 1, 0])
l4 = lambda x = lambda y = lambda z=1 : z : y() : x() l4 = lambda x = lambda y = lambda z=1 : z : y() : x()
self.assertEquals(l4(), 1) self.assertEqual(l4(), 1)
l5 = lambda x, y, z=2: x + y + z l5 = lambda x, y, z=2: x + y + z
self.assertEquals(l5(1, 2), 5) self.assertEqual(l5(1, 2), 5)
self.assertEquals(l5(1, 2, 3), 6) self.assertEqual(l5(1, 2, 3), 6)
check_syntax_error(self, "lambda x: x = 2") check_syntax_error(self, "lambda x: x = 2")
check_syntax_error(self, "lambda (None,): None") check_syntax_error(self, "lambda (None,): None")
l6 = lambda x, y, *, k=20: x+y+k l6 = lambda x, y, *, k=20: x+y+k
self.assertEquals(l6(1,2), 1+2+20) self.assertEqual(l6(1,2), 1+2+20)
self.assertEquals(l6(1,2,k=10), 1+2+10) self.assertEqual(l6(1,2,k=10), 1+2+10)
### stmt: simple_stmt | compound_stmt ### stmt: simple_stmt | compound_stmt
@ -502,7 +502,7 @@ class GrammarTests(unittest.TestCase):
try: try:
assert 0, "msg" assert 0, "msg"
except AssertionError as e: except AssertionError as e:
self.assertEquals(e.args[0], "msg") self.assertEqual(e.args[0], "msg")
else: else:
if __debug__: if __debug__:
self.fail("AssertionError not raised by assert 0") self.fail("AssertionError not raised by assert 0")
@ -536,7 +536,7 @@ class GrammarTests(unittest.TestCase):
x = 1 x = 1
else: else:
x = 2 x = 2
self.assertEquals(x, 2) self.assertEqual(x, 2)
def testFor(self): def testFor(self):
# 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite] # 'for' exprlist 'in' exprlist ':' suite ['else' ':' suite]
@ -688,7 +688,7 @@ class GrammarTests(unittest.TestCase):
d[1,2,3] = 4 d[1,2,3] = 4
L = list(d) L = list(d)
L.sort(key=lambda x: x if isinstance(x, tuple) else ()) L.sort(key=lambda x: x if isinstance(x, tuple) else ())
self.assertEquals(str(L), '[1, (1,), (1, 2), (1, 2, 3)]') self.assertEqual(str(L), '[1, (1,), (1, 2), (1, 2, 3)]')
def testAtoms(self): def testAtoms(self):
### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictsetmaker] '}' | NAME | NUMBER | STRING

View File

@ -43,7 +43,7 @@ class ModuleTests(unittest.TestCase):
sqlite.paramstyle) sqlite.paramstyle)
def CheckWarning(self): def CheckWarning(self):
self.assert_(issubclass(sqlite.Warning, Exception), self.assertTrue(issubclass(sqlite.Warning, Exception),
"Warning is not a subclass of Exception") "Warning is not a subclass of Exception")
def CheckError(self): def CheckError(self):

View File

@ -291,7 +291,7 @@ class ColNamesTests(unittest.TestCase):
no row returned. no row returned.
""" """
self.cur.execute("select * from test where 0 = 1") self.cur.execute("select * from test where 0 = 1")
self.assert_(self.cur.description[0][0] == "x") self.assertEqual(self.cur.description[0][0], "x")
class ObjectAdaptationTests(unittest.TestCase): class ObjectAdaptationTests(unittest.TestCase):
def cast(obj): def cast(obj):

View File

@ -15,32 +15,32 @@ class MixinBytesBufferCommonTests(object):
def test_islower(self): def test_islower(self):
self.assertFalse(self.marshal(b'').islower()) self.assertFalse(self.marshal(b'').islower())
self.assert_(self.marshal(b'a').islower()) self.assertTrue(self.marshal(b'a').islower())
self.assertFalse(self.marshal(b'A').islower()) self.assertFalse(self.marshal(b'A').islower())
self.assertFalse(self.marshal(b'\n').islower()) self.assertFalse(self.marshal(b'\n').islower())
self.assert_(self.marshal(b'abc').islower()) self.assertTrue(self.marshal(b'abc').islower())
self.assertFalse(self.marshal(b'aBc').islower()) self.assertFalse(self.marshal(b'aBc').islower())
self.assert_(self.marshal(b'abc\n').islower()) self.assertTrue(self.marshal(b'abc\n').islower())
self.assertRaises(TypeError, self.marshal(b'abc').islower, 42) self.assertRaises(TypeError, self.marshal(b'abc').islower, 42)
def test_isupper(self): def test_isupper(self):
self.assertFalse(self.marshal(b'').isupper()) self.assertFalse(self.marshal(b'').isupper())
self.assertFalse(self.marshal(b'a').isupper()) self.assertFalse(self.marshal(b'a').isupper())
self.assert_(self.marshal(b'A').isupper()) self.assertTrue(self.marshal(b'A').isupper())
self.assertFalse(self.marshal(b'\n').isupper()) self.assertFalse(self.marshal(b'\n').isupper())
self.assert_(self.marshal(b'ABC').isupper()) self.assertTrue(self.marshal(b'ABC').isupper())
self.assertFalse(self.marshal(b'AbC').isupper()) self.assertFalse(self.marshal(b'AbC').isupper())
self.assert_(self.marshal(b'ABC\n').isupper()) self.assertTrue(self.marshal(b'ABC\n').isupper())
self.assertRaises(TypeError, self.marshal(b'abc').isupper, 42) self.assertRaises(TypeError, self.marshal(b'abc').isupper, 42)
def test_istitle(self): def test_istitle(self):
self.assertFalse(self.marshal(b'').istitle()) self.assertFalse(self.marshal(b'').istitle())
self.assertFalse(self.marshal(b'a').istitle()) self.assertFalse(self.marshal(b'a').istitle())
self.assert_(self.marshal(b'A').istitle()) self.assertTrue(self.marshal(b'A').istitle())
self.assertFalse(self.marshal(b'\n').istitle()) self.assertFalse(self.marshal(b'\n').istitle())
self.assert_(self.marshal(b'A Titlecased Line').istitle()) self.assertTrue(self.marshal(b'A Titlecased Line').istitle())
self.assert_(self.marshal(b'A\nTitlecased Line').istitle()) self.assertTrue(self.marshal(b'A\nTitlecased Line').istitle())
self.assert_(self.marshal(b'A Titlecased, Line').istitle()) self.assertTrue(self.marshal(b'A Titlecased, Line').istitle())
self.assertFalse(self.marshal(b'Not a capitalized String').istitle()) self.assertFalse(self.marshal(b'Not a capitalized String').istitle())
self.assertFalse(self.marshal(b'Not\ta Titlecase String').istitle()) self.assertFalse(self.marshal(b'Not\ta Titlecase String').istitle())
self.assertFalse(self.marshal(b'Not--a Titlecase String').istitle()) self.assertFalse(self.marshal(b'Not--a Titlecase String').istitle())
@ -50,31 +50,31 @@ class MixinBytesBufferCommonTests(object):
def test_isspace(self): def test_isspace(self):
self.assertFalse(self.marshal(b'').isspace()) self.assertFalse(self.marshal(b'').isspace())
self.assertFalse(self.marshal(b'a').isspace()) self.assertFalse(self.marshal(b'a').isspace())
self.assert_(self.marshal(b' ').isspace()) self.assertTrue(self.marshal(b' ').isspace())
self.assert_(self.marshal(b'\t').isspace()) self.assertTrue(self.marshal(b'\t').isspace())
self.assert_(self.marshal(b'\r').isspace()) self.assertTrue(self.marshal(b'\r').isspace())
self.assert_(self.marshal(b'\n').isspace()) self.assertTrue(self.marshal(b'\n').isspace())
self.assert_(self.marshal(b' \t\r\n').isspace()) self.assertTrue(self.marshal(b' \t\r\n').isspace())
self.assertFalse(self.marshal(b' \t\r\na').isspace()) self.assertFalse(self.marshal(b' \t\r\na').isspace())
self.assertRaises(TypeError, self.marshal(b'abc').isspace, 42) self.assertRaises(TypeError, self.marshal(b'abc').isspace, 42)
def test_isalpha(self): def test_isalpha(self):
self.assertFalse(self.marshal(b'').isalpha()) self.assertFalse(self.marshal(b'').isalpha())
self.assert_(self.marshal(b'a').isalpha()) self.assertTrue(self.marshal(b'a').isalpha())
self.assert_(self.marshal(b'A').isalpha()) self.assertTrue(self.marshal(b'A').isalpha())
self.assertFalse(self.marshal(b'\n').isalpha()) self.assertFalse(self.marshal(b'\n').isalpha())
self.assert_(self.marshal(b'abc').isalpha()) self.assertTrue(self.marshal(b'abc').isalpha())
self.assertFalse(self.marshal(b'aBc123').isalpha()) self.assertFalse(self.marshal(b'aBc123').isalpha())
self.assertFalse(self.marshal(b'abc\n').isalpha()) self.assertFalse(self.marshal(b'abc\n').isalpha())
self.assertRaises(TypeError, self.marshal(b'abc').isalpha, 42) self.assertRaises(TypeError, self.marshal(b'abc').isalpha, 42)
def test_isalnum(self): def test_isalnum(self):
self.assertFalse(self.marshal(b'').isalnum()) self.assertFalse(self.marshal(b'').isalnum())
self.assert_(self.marshal(b'a').isalnum()) self.assertTrue(self.marshal(b'a').isalnum())
self.assert_(self.marshal(b'A').isalnum()) self.assertTrue(self.marshal(b'A').isalnum())
self.assertFalse(self.marshal(b'\n').isalnum()) self.assertFalse(self.marshal(b'\n').isalnum())
self.assert_(self.marshal(b'123abc456').isalnum()) self.assertTrue(self.marshal(b'123abc456').isalnum())
self.assert_(self.marshal(b'a1b3c').isalnum()) self.assertTrue(self.marshal(b'a1b3c').isalnum())
self.assertFalse(self.marshal(b'aBc000 ').isalnum()) self.assertFalse(self.marshal(b'aBc000 ').isalnum())
self.assertFalse(self.marshal(b'abc\n').isalnum()) self.assertFalse(self.marshal(b'abc\n').isalnum())
self.assertRaises(TypeError, self.marshal(b'abc').isalnum, 42) self.assertRaises(TypeError, self.marshal(b'abc').isalnum, 42)
@ -82,8 +82,8 @@ class MixinBytesBufferCommonTests(object):
def test_isdigit(self): def test_isdigit(self):
self.assertFalse(self.marshal(b'').isdigit()) self.assertFalse(self.marshal(b'').isdigit())
self.assertFalse(self.marshal(b'a').isdigit()) self.assertFalse(self.marshal(b'a').isdigit())
self.assert_(self.marshal(b'0').isdigit()) self.assertTrue(self.marshal(b'0').isdigit())
self.assert_(self.marshal(b'0123456789').isdigit()) self.assertTrue(self.marshal(b'0123456789').isdigit())
self.assertFalse(self.marshal(b'0123456789a').isdigit()) self.assertFalse(self.marshal(b'0123456789a').isdigit())
self.assertRaises(TypeError, self.marshal(b'abc').isdigit, 42) self.assertRaises(TypeError, self.marshal(b'abc').isdigit, 42)

View File

@ -40,8 +40,8 @@ class ForkWait(unittest.TestCase):
break break
time.sleep(2 * SHORTSLEEP) time.sleep(2 * SHORTSLEEP)
self.assertEquals(spid, cpid) self.assertEqual(spid, cpid)
self.assertEquals(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8)) self.assertEqual(status, 0, "cause = %d, exit = %d" % (status&0xff, status>>8))
def test_wait(self): def test_wait(self):
for i in range(NUM_THREADS): for i in range(NUM_THREADS):
@ -50,7 +50,7 @@ class ForkWait(unittest.TestCase):
time.sleep(LONGSLEEP) time.sleep(LONGSLEEP)
a = sorted(self.alive.keys()) a = sorted(self.alive.keys())
self.assertEquals(a, list(range(NUM_THREADS))) self.assertEqual(a, list(range(NUM_THREADS)))
prefork_lives = self.alive.copy() prefork_lives = self.alive.copy()

View File

@ -337,7 +337,7 @@ class CommonTest(seq_tests.CommonTest):
self.assertRaises(BadExc, d.remove, 'c') self.assertRaises(BadExc, d.remove, 'c')
for x, y in zip(d, e): for x, y in zip(d, e):
# verify that original order and values are retained. # verify that original order and values are retained.
self.assert_(x is y) self.assertIs(x, y)
def test_count(self): def test_count(self):
a = self.type2test([0, 1, 2])*3 a = self.type2test([0, 1, 2])*3
@ -482,7 +482,7 @@ class CommonTest(seq_tests.CommonTest):
u = self.type2test([0, 1]) u = self.type2test([0, 1])
u2 = u u2 = u
u += [2, 3] u += [2, 3]
self.assert_(u is u2) self.assertIs(u, u2)
u = self.type2test("spam") u = self.type2test("spam")
u += "eggs" u += "eggs"

View File

@ -35,7 +35,7 @@ class TextIOWrapperTest(unittest.TestCase):
if not c: if not c:
break break
reads += c reads += c
self.assertEquals(reads, self.normalized) self.assertEqual(reads, self.normalized)
def test_issue1395_2(self): def test_issue1395_2(self):
txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ASCII") txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ASCII")
@ -47,7 +47,7 @@ class TextIOWrapperTest(unittest.TestCase):
if not c: if not c:
break break
reads += c reads += c
self.assertEquals(reads, self.normalized) self.assertEqual(reads, self.normalized)
def test_issue1395_3(self): def test_issue1395_3(self):
txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ASCII") txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ASCII")
@ -58,7 +58,7 @@ class TextIOWrapperTest(unittest.TestCase):
reads += txt.readline() reads += txt.readline()
reads += txt.readline() reads += txt.readline()
reads += txt.readline() reads += txt.readline()
self.assertEquals(reads, self.normalized) self.assertEqual(reads, self.normalized)
def test_issue1395_4(self): def test_issue1395_4(self):
txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ASCII") txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ASCII")
@ -66,7 +66,7 @@ class TextIOWrapperTest(unittest.TestCase):
reads = txt.read(4) reads = txt.read(4)
reads += txt.read() reads += txt.read()
self.assertEquals(reads, self.normalized) self.assertEqual(reads, self.normalized)
def test_issue1395_5(self): def test_issue1395_5(self):
txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ASCII") txt = io.TextIOWrapper(io.BytesIO(self.testdata), encoding="ASCII")
@ -76,7 +76,7 @@ class TextIOWrapperTest(unittest.TestCase):
pos = txt.tell() pos = txt.tell()
txt.seek(0) txt.seek(0)
txt.seek(pos) txt.seek(pos)
self.assertEquals(txt.read(4), "BBB\n") self.assertEqual(txt.read(4), "BBB\n")

View File

@ -579,7 +579,7 @@ class AbstractPickleTests(unittest.TestCase):
def test_get(self): def test_get(self):
self.assertRaises(KeyError, self.loads, b'g0\np0') self.assertRaises(KeyError, self.loads, b'g0\np0')
self.assertEquals(self.loads(b'((Kdtp0\nh\x00l.))'), [(100,), (100,)]) self.assertEqual(self.loads(b'((Kdtp0\nh\x00l.))'), [(100,), (100,)])
def test_insecure_strings(self): def test_insecure_strings(self):
# XXX Some of these tests are temporarily disabled # XXX Some of these tests are temporarily disabled

View File

@ -131,8 +131,8 @@ class CommonTest(unittest.TestCase):
self.assertRaises(ZeroDivisionError, self.type2test, IterGenExc(s)) self.assertRaises(ZeroDivisionError, self.type2test, IterGenExc(s))
def test_truth(self): def test_truth(self):
self.assert_(not self.type2test()) self.assertFalse(self.type2test())
self.assert_(self.type2test([42])) self.assertTrue(self.type2test([42]))
def test_getitem(self): def test_getitem(self):
u = self.type2test([0, 1, 2, 3, 4]) u = self.type2test([0, 1, 2, 3, 4])
@ -268,7 +268,7 @@ class CommonTest(unittest.TestCase):
pass pass
u3 = subclass([0, 1]) u3 = subclass([0, 1])
self.assertEqual(u3, u3*1) self.assertEqual(u3, u3*1)
self.assert_(u3 is not u3*1) self.assertIsNot(u3, u3*1)
def test_iadd(self): def test_iadd(self):
u = self.type2test([0, 1]) u = self.type2test([0, 1])

View File

@ -67,7 +67,7 @@ class BaseTest(unittest.TestCase):
else: else:
obj = subtype(obj) obj = subtype(obj)
realresult = getattr(obj, methodname)(*args) realresult = getattr(obj, methodname)(*args)
self.assert_(obj is not realresult) self.assertIsNot(obj, realresult)
# check that obj.method(*args) raises exc # check that obj.method(*args) raises exc
def checkraises(self, exc, obj, methodname, *args): def checkraises(self, exc, obj, methodname, *args):
@ -1197,34 +1197,34 @@ class MixinStrUnicodeTest:
pass pass
s1 = subclass("abcd") s1 = subclass("abcd")
s2 = t().join([s1]) s2 = t().join([s1])
self.assert_(s1 is not s2) self.assertIsNot(s1, s2)
self.assert_(type(s2) is t) self.assertIs(type(s2), t)
s1 = t("abcd") s1 = t("abcd")
s2 = t().join([s1]) s2 = t().join([s1])
self.assert_(s1 is s2) self.assertIs(s1, s2)
# Should also test mixed-type join. # Should also test mixed-type join.
if t is str: if t is str:
s1 = subclass("abcd") s1 = subclass("abcd")
s2 = "".join([s1]) s2 = "".join([s1])
self.assert_(s1 is not s2) self.assertIsNot(s1, s2)
self.assert_(type(s2) is t) self.assertIs(type(s2), t)
s1 = t("abcd") s1 = t("abcd")
s2 = "".join([s1]) s2 = "".join([s1])
self.assert_(s1 is s2) self.assertIs(s1, s2)
## elif t is str8: ## elif t is str8:
## s1 = subclass("abcd") ## s1 = subclass("abcd")
## s2 = "".join([s1]) ## s2 = "".join([s1])
## self.assert_(s1 is not s2) ## self.assertIsNot(s1, s2)
## self.assert_(type(s2) is str) # promotes! ## self.assertIs(type(s2), str) # promotes!
## s1 = t("abcd") ## s1 = t("abcd")
## s2 = "".join([s1]) ## s2 = "".join([s1])
## self.assert_(s1 is not s2) ## self.assertIsNot(s1, s2)
## self.assert_(type(s2) is str) # promotes! ## self.assertIs(type(s2), str) # promotes!
else: else:
self.fail("unexpected type for MixinStrUnicodeTest %r" % t) self.fail("unexpected type for MixinStrUnicodeTest %r" % t)

View File

@ -59,7 +59,7 @@ class _LocaleTests(unittest.TestCase):
known_value = known_numerics.get(used_locale, known_value = known_numerics.get(used_locale,
('', ''))[data_type == 'thousands_sep'] ('', ''))[data_type == 'thousands_sep']
if known_value and calc_value: if known_value and calc_value:
self.assertEquals(calc_value, known_value, self.assertEqual(calc_value, known_value,
self.lc_numeric_err_msg % ( self.lc_numeric_err_msg % (
calc_value, known_value, calc_value, known_value,
calc_type, data_type, set_locale, calc_type, data_type, set_locale,
@ -107,7 +107,7 @@ class _LocaleTests(unittest.TestCase):
set_locale = setlocale(LC_NUMERIC) set_locale = setlocale(LC_NUMERIC)
except Error: except Error:
set_locale = "<not able to determine>" set_locale = "<not able to determine>"
self.assertEquals(nl_radixchar, li_radixchar, self.assertEqual(nl_radixchar, li_radixchar,
"%s (nl_langinfo) != %s (localeconv) " "%s (nl_langinfo) != %s (localeconv) "
"(set to %s, using %s)" % ( "(set to %s, using %s)" % (
nl_radixchar, li_radixchar, nl_radixchar, li_radixchar,
@ -127,9 +127,9 @@ class _LocaleTests(unittest.TestCase):
if loc == 'eu_ES' and localeconv()['decimal_point'] == "' ": if loc == 'eu_ES' and localeconv()['decimal_point'] == "' ":
continue continue
self.assertEquals(int(eval('3.14') * 100), 314, self.assertEqual(int(eval('3.14') * 100), 314,
"using eval('3.14') failed for %s" % loc) "using eval('3.14') failed for %s" % loc)
self.assertEquals(int(float('3.14') * 100), 314, self.assertEqual(int(float('3.14') * 100), 314,
"using float('3.14') failed for %s" % loc) "using float('3.14') failed for %s" % loc)
if localeconv()['decimal_point'] != '.': if localeconv()['decimal_point'] != '.':
self.assertRaises(ValueError, float, self.assertRaises(ValueError, float,

View File

@ -2698,18 +2698,18 @@ class TestNamespaceContainsSimple(TestCase):
def test_empty(self): def test_empty(self):
ns = argparse.Namespace() ns = argparse.Namespace()
self.assertEquals('' in ns, False) self.assertEqual('' in ns, False)
self.assertEquals('' not in ns, True) self.assertEqual('' not in ns, True)
self.assertEquals('x' in ns, False) self.assertEqual('x' in ns, False)
def test_non_empty(self): def test_non_empty(self):
ns = argparse.Namespace(x=1, y=2) ns = argparse.Namespace(x=1, y=2)
self.assertEquals('x' in ns, True) self.assertEqual('x' in ns, True)
self.assertEquals('x' not in ns, False) self.assertEqual('x' not in ns, False)
self.assertEquals('y' in ns, True) self.assertEqual('y' in ns, True)
self.assertEquals('' in ns, False) self.assertEqual('' in ns, False)
self.assertEquals('xx' in ns, False) self.assertEqual('xx' in ns, False)
self.assertEquals('z' in ns, False) self.assertEqual('z' in ns, False)
# ===================== # =====================
# Help formatting tests # Help formatting tests

View File

@ -238,9 +238,9 @@ class BaseTest(unittest.TestCase):
def test_reduce_ex(self): def test_reduce_ex(self):
a = array.array(self.typecode, self.example) a = array.array(self.typecode, self.example)
for protocol in range(3): for protocol in range(3):
self.assert_(a.__reduce_ex__(protocol)[0] is array.array) self.assertIs(a.__reduce_ex__(protocol)[0], array.array)
for protocol in range(3, pickle.HIGHEST_PROTOCOL): for protocol in range(3, pickle.HIGHEST_PROTOCOL):
self.assert_(a.__reduce_ex__(protocol)[0] is array_reconstructor) self.assertIs(a.__reduce_ex__(protocol)[0], array_reconstructor)
def test_pickle(self): def test_pickle(self):
for protocol in range(pickle.HIGHEST_PROTOCOL + 1): for protocol in range(pickle.HIGHEST_PROTOCOL + 1):
@ -785,11 +785,11 @@ class BaseTest(unittest.TestCase):
data.reverse() data.reverse()
L[start:stop:step] = data L[start:stop:step] = data
a[start:stop:step] = array.array(self.typecode, data) a[start:stop:step] = array.array(self.typecode, data)
self.assertEquals(a, array.array(self.typecode, L)) self.assertEqual(a, array.array(self.typecode, L))
del L[start:stop:step] del L[start:stop:step]
del a[start:stop:step] del a[start:stop:step]
self.assertEquals(a, array.array(self.typecode, L)) self.assertEqual(a, array.array(self.typecode, L))
def test_index(self): def test_index(self):
example = 2*self.example example = 2*self.example

View File

@ -141,7 +141,7 @@ class AST_Tests(unittest.TestCase):
(eval_tests, eval_results, "eval")): (eval_tests, eval_results, "eval")):
for i, o in zip(input, output): for i, o in zip(input, output):
ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST) ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
self.assertEquals(to_tuple(ast_tree), o) self.assertEqual(to_tuple(ast_tree), o)
self._assertTrueorder(ast_tree, (0, 0)) self._assertTrueorder(ast_tree, (0, 0))
def test_slice(self): def test_slice(self):
@ -164,20 +164,20 @@ class AST_Tests(unittest.TestCase):
def test_nodeclasses(self): def test_nodeclasses(self):
x = ast.BinOp(1, 2, 3, lineno=0) x = ast.BinOp(1, 2, 3, lineno=0)
self.assertEquals(x.left, 1) self.assertEqual(x.left, 1)
self.assertEquals(x.op, 2) self.assertEqual(x.op, 2)
self.assertEquals(x.right, 3) self.assertEqual(x.right, 3)
self.assertEquals(x.lineno, 0) self.assertEqual(x.lineno, 0)
# node raises exception when not given enough arguments # node raises exception when not given enough arguments
self.assertRaises(TypeError, ast.BinOp, 1, 2) self.assertRaises(TypeError, ast.BinOp, 1, 2)
# can set attributes through kwargs too # can set attributes through kwargs too
x = ast.BinOp(left=1, op=2, right=3, lineno=0) x = ast.BinOp(left=1, op=2, right=3, lineno=0)
self.assertEquals(x.left, 1) self.assertEqual(x.left, 1)
self.assertEquals(x.op, 2) self.assertEqual(x.op, 2)
self.assertEquals(x.right, 3) self.assertEqual(x.right, 3)
self.assertEquals(x.lineno, 0) self.assertEqual(x.lineno, 0)
# this used to fail because Sub._fields was None # this used to fail because Sub._fields was None
x = ast.Sub() x = ast.Sub()
@ -195,7 +195,7 @@ class AST_Tests(unittest.TestCase):
for protocol in protocols: for protocol in protocols:
for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests): for ast in (compile(i, "?", "exec", 0x400) for i in exec_tests):
ast2 = mod.loads(mod.dumps(ast, protocol)) ast2 = mod.loads(mod.dumps(ast, protocol))
self.assertEquals(to_tuple(ast2), to_tuple(ast)) self.assertEqual(to_tuple(ast2), to_tuple(ast))
def test_invalid_sum(self): def test_invalid_sum(self):
pos = dict(lineno=2, col_offset=3) pos = dict(lineno=2, col_offset=3)

View File

@ -17,7 +17,7 @@ class AugAssignTest(unittest.TestCase):
x |= 5 x |= 5
x ^= 1 x ^= 1
x /= 2 x /= 2
self.assertEquals(x, 3.0) self.assertEqual(x, 3.0)
def test_with_unpacking(self): def test_with_unpacking(self):
self.assertRaises(SyntaxError, compile, "x, b += 3", "<test>", "exec") self.assertRaises(SyntaxError, compile, "x, b += 3", "<test>", "exec")
@ -34,7 +34,7 @@ class AugAssignTest(unittest.TestCase):
x[0] |= 5 x[0] |= 5
x[0] ^= 1 x[0] ^= 1
x[0] /= 2 x[0] /= 2
self.assertEquals(x[0], 3.0) self.assertEqual(x[0], 3.0)
def testInDict(self): def testInDict(self):
x = {0: 2} x = {0: 2}
@ -48,21 +48,21 @@ class AugAssignTest(unittest.TestCase):
x[0] |= 5 x[0] |= 5
x[0] ^= 1 x[0] ^= 1
x[0] /= 2 x[0] /= 2
self.assertEquals(x[0], 3.0) self.assertEqual(x[0], 3.0)
def testSequences(self): def testSequences(self):
x = [1,2] x = [1,2]
x += [3,4] x += [3,4]
x *= 2 x *= 2
self.assertEquals(x, [1, 2, 3, 4, 1, 2, 3, 4]) self.assertEqual(x, [1, 2, 3, 4, 1, 2, 3, 4])
x = [1, 2, 3] x = [1, 2, 3]
y = x y = x
x[1:2] *= 2 x[1:2] *= 2
y[1:2] += [1] y[1:2] += [1]
self.assertEquals(x, [1, 2, 1, 2, 3]) self.assertEqual(x, [1, 2, 1, 2, 3])
self.assertTrue(x is y) self.assertTrue(x is y)
def testCustomMethods1(self): def testCustomMethods1(self):
@ -90,14 +90,14 @@ class AugAssignTest(unittest.TestCase):
self.assertIsInstance(x, aug_test) self.assertIsInstance(x, aug_test)
self.assertTrue(y is not x) self.assertTrue(y is not x)
self.assertEquals(x.val, 11) self.assertEqual(x.val, 11)
x = aug_test2(2) x = aug_test2(2)
y = x y = x
x += 10 x += 10
self.assertTrue(y is x) self.assertTrue(y is x)
self.assertEquals(x.val, 12) self.assertEqual(x.val, 12)
x = aug_test3(3) x = aug_test3(3)
y = x y = x
@ -105,7 +105,7 @@ class AugAssignTest(unittest.TestCase):
self.assertIsInstance(x, aug_test3) self.assertIsInstance(x, aug_test3)
self.assertTrue(y is not x) self.assertTrue(y is not x)
self.assertEquals(x.val, 13) self.assertEqual(x.val, 13)
def testCustomMethods2(test_self): def testCustomMethods2(test_self):
@ -269,7 +269,7 @@ class AugAssignTest(unittest.TestCase):
1 << x 1 << x
x <<= 1 x <<= 1
test_self.assertEquals(output, '''\ test_self.assertEqual(output, '''\
__add__ called __add__ called
__radd__ called __radd__ called
__iadd__ called __iadd__ called

View File

@ -6,7 +6,7 @@ import sys
import subprocess import subprocess
class LegacyBase64TestCase(unittest.TestCase): class LegacyBase64TestCase(unittest.TestCase):
def test_encodebytes(self): def test_encodebytes(self):
eq = self.assertEqual eq = self.assertEqual
@ -58,7 +58,7 @@ class LegacyBase64TestCase(unittest.TestCase):
base64.decode(infp, outfp) base64.decode(infp, outfp)
self.assertEqual(outfp.getvalue(), b'www.python.org') self.assertEqual(outfp.getvalue(), b'www.python.org')
class BaseXYTestCase(unittest.TestCase): class BaseXYTestCase(unittest.TestCase):
def test_b64encode(self): def test_b64encode(self):
eq = self.assertEqual eq = self.assertEqual
@ -153,7 +153,7 @@ class BaseXYTestCase(unittest.TestCase):
(b'!', b''), (b'!', b''),
(b'YWJj\nYWI=', b'abcab')) (b'YWJj\nYWI=', b'abcab'))
for bstr, res in tests: for bstr, res in tests:
self.assertEquals(base64.b64decode(bstr), res) self.assertEqual(base64.b64decode(bstr), res)
with self.assertRaises(binascii.Error): with self.assertRaises(binascii.Error):
base64.b64decode(bstr, validate=True) base64.b64decode(bstr, validate=True)
@ -225,7 +225,7 @@ class BaseXYTestCase(unittest.TestCase):
self.assertTrue(issubclass(binascii.Error, ValueError)) self.assertTrue(issubclass(binascii.Error, ValueError))
class TestMain(unittest.TestCase): class TestMain(unittest.TestCase):
def get_output(self, *args, **options): def get_output(self, *args, **options):
args = (sys.executable, '-m', 'base64') + args args = (sys.executable, '-m', 'base64') + args
@ -244,20 +244,20 @@ class TestMain(unittest.TestCase):
fp.write(b'a\xffb\n') fp.write(b'a\xffb\n')
output = self.get_output('-e', support.TESTFN) output = self.get_output('-e', support.TESTFN)
self.assertEquals(output.rstrip(), b'Yf9iCg==') self.assertEqual(output.rstrip(), b'Yf9iCg==')
with open(support.TESTFN, 'rb') as fp: with open(support.TESTFN, 'rb') as fp:
output = self.get_output('-e', stdin=fp) output = self.get_output('-e', stdin=fp)
self.assertEquals(output.rstrip(), b'Yf9iCg==') self.assertEqual(output.rstrip(), b'Yf9iCg==')
def test_decode(self): def test_decode(self):
with open(support.TESTFN, 'wb') as fp: with open(support.TESTFN, 'wb') as fp:
fp.write(b'Yf9iCg==') fp.write(b'Yf9iCg==')
output = self.get_output('-d', support.TESTFN) output = self.get_output('-d', support.TESTFN)
self.assertEquals(output.rstrip(), b'a\xffb') self.assertEqual(output.rstrip(), b'a\xffb')
def test_main(): def test_main():
support.run_unittest(__name__) support.run_unittest(__name__)

View File

@ -13,7 +13,7 @@ import functools
# doesn't release the old 's' (if it exists) until well after its new # doesn't release the old 's' (if it exists) until well after its new
# value has been created. Use 'del s' before the create_largestring call. # value has been created. Use 'del s' before the create_largestring call.
# #
# - Do *not* compare large objects using assertEquals or similar. It's a # - Do *not* compare large objects using assertEqual or similar. It's a
# lengthy operation and the errormessage will be utterly useless due to # lengthy operation and the errormessage will be utterly useless due to
# its size. To make sure whether a result has the right contents, better # its size. To make sure whether a result has the right contents, better
# to use the strip or count methods, or compare meaningful slices. # to use the strip or count methods, or compare meaningful slices.
@ -48,32 +48,32 @@ class BaseStrTest:
SUBSTR = self.from_latin1(' abc def ghi') SUBSTR = self.from_latin1(' abc def ghi')
s = _('-') * size + SUBSTR s = _('-') * size + SUBSTR
caps = s.capitalize() caps = s.capitalize()
self.assertEquals(caps[-len(SUBSTR):], self.assertEqual(caps[-len(SUBSTR):],
SUBSTR.capitalize()) SUBSTR.capitalize())
self.assertEquals(caps.lstrip(_('-')), SUBSTR) self.assertEqual(caps.lstrip(_('-')), SUBSTR)
@bigmemtest(minsize=_2G + 10, memuse=1) @bigmemtest(minsize=_2G + 10, memuse=1)
def test_center(self, size): def test_center(self, size):
SUBSTR = self.from_latin1(' abc def ghi') SUBSTR = self.from_latin1(' abc def ghi')
s = SUBSTR.center(size) s = SUBSTR.center(size)
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
lpadsize = rpadsize = (len(s) - len(SUBSTR)) // 2 lpadsize = rpadsize = (len(s) - len(SUBSTR)) // 2
if len(s) % 2: if len(s) % 2:
lpadsize += 1 lpadsize += 1
self.assertEquals(s[lpadsize:-rpadsize], SUBSTR) self.assertEqual(s[lpadsize:-rpadsize], SUBSTR)
self.assertEquals(s.strip(), SUBSTR.strip()) self.assertEqual(s.strip(), SUBSTR.strip())
@bigmemtest(minsize=_2G, memuse=2) @bigmemtest(minsize=_2G, memuse=2)
def test_count(self, size): def test_count(self, size):
_ = self.from_latin1 _ = self.from_latin1
SUBSTR = _(' abc def ghi') SUBSTR = _(' abc def ghi')
s = _('.') * size + SUBSTR s = _('.') * size + SUBSTR
self.assertEquals(s.count(_('.')), size) self.assertEqual(s.count(_('.')), size)
s += _('.') s += _('.')
self.assertEquals(s.count(_('.')), size + 1) self.assertEqual(s.count(_('.')), size + 1)
self.assertEquals(s.count(_(' ')), 3) self.assertEqual(s.count(_(' ')), 3)
self.assertEquals(s.count(_('i')), 1) self.assertEqual(s.count(_('i')), 1)
self.assertEquals(s.count(_('j')), 0) self.assertEqual(s.count(_('j')), 0)
@bigmemtest(minsize=_2G, memuse=2) @bigmemtest(minsize=_2G, memuse=2)
def test_endswith(self, size): def test_endswith(self, size):
@ -92,13 +92,13 @@ class BaseStrTest:
_ = self.from_latin1 _ = self.from_latin1
s = _('-') * size s = _('-') * size
tabsize = 8 tabsize = 8
self.assertEquals(s.expandtabs(), s) self.assertEqual(s.expandtabs(), s)
del s del s
slen, remainder = divmod(size, tabsize) slen, remainder = divmod(size, tabsize)
s = _(' \t') * slen s = _(' \t') * slen
s = s.expandtabs(tabsize) s = s.expandtabs(tabsize)
self.assertEquals(len(s), size - remainder) self.assertEqual(len(s), size - remainder)
self.assertEquals(len(s.strip(_(' '))), 0) self.assertEqual(len(s.strip(_(' '))), 0)
@bigmemtest(minsize=_2G, memuse=2) @bigmemtest(minsize=_2G, memuse=2)
def test_find(self, size): def test_find(self, size):
@ -106,16 +106,16 @@ class BaseStrTest:
SUBSTR = _(' abc def ghi') SUBSTR = _(' abc def ghi')
sublen = len(SUBSTR) sublen = len(SUBSTR)
s = _('').join([SUBSTR, _('-') * size, SUBSTR]) s = _('').join([SUBSTR, _('-') * size, SUBSTR])
self.assertEquals(s.find(_(' ')), 0) self.assertEqual(s.find(_(' ')), 0)
self.assertEquals(s.find(SUBSTR), 0) self.assertEqual(s.find(SUBSTR), 0)
self.assertEquals(s.find(_(' '), sublen), sublen + size) self.assertEqual(s.find(_(' '), sublen), sublen + size)
self.assertEquals(s.find(SUBSTR, len(SUBSTR)), sublen + size) self.assertEqual(s.find(SUBSTR, len(SUBSTR)), sublen + size)
self.assertEquals(s.find(_('i')), SUBSTR.find(_('i'))) self.assertEqual(s.find(_('i')), SUBSTR.find(_('i')))
self.assertEquals(s.find(_('i'), sublen), self.assertEqual(s.find(_('i'), sublen),
sublen + size + SUBSTR.find(_('i'))) sublen + size + SUBSTR.find(_('i')))
self.assertEquals(s.find(_('i'), size), self.assertEqual(s.find(_('i'), size),
sublen + size + SUBSTR.find(_('i'))) sublen + size + SUBSTR.find(_('i')))
self.assertEquals(s.find(_('j')), -1) self.assertEqual(s.find(_('j')), -1)
@bigmemtest(minsize=_2G, memuse=2) @bigmemtest(minsize=_2G, memuse=2)
def test_index(self, size): def test_index(self, size):
@ -123,14 +123,14 @@ class BaseStrTest:
SUBSTR = _(' abc def ghi') SUBSTR = _(' abc def ghi')
sublen = len(SUBSTR) sublen = len(SUBSTR)
s = _('').join([SUBSTR, _('-') * size, SUBSTR]) s = _('').join([SUBSTR, _('-') * size, SUBSTR])
self.assertEquals(s.index(_(' ')), 0) self.assertEqual(s.index(_(' ')), 0)
self.assertEquals(s.index(SUBSTR), 0) self.assertEqual(s.index(SUBSTR), 0)
self.assertEquals(s.index(_(' '), sublen), sublen + size) self.assertEqual(s.index(_(' '), sublen), sublen + size)
self.assertEquals(s.index(SUBSTR, sublen), sublen + size) self.assertEqual(s.index(SUBSTR, sublen), sublen + size)
self.assertEquals(s.index(_('i')), SUBSTR.index(_('i'))) self.assertEqual(s.index(_('i')), SUBSTR.index(_('i')))
self.assertEquals(s.index(_('i'), sublen), self.assertEqual(s.index(_('i'), sublen),
sublen + size + SUBSTR.index(_('i'))) sublen + size + SUBSTR.index(_('i')))
self.assertEquals(s.index(_('i'), size), self.assertEqual(s.index(_('i'), size),
sublen + size + SUBSTR.index(_('i'))) sublen + size + SUBSTR.index(_('i')))
self.assertRaises(ValueError, s.index, _('j')) self.assertRaises(ValueError, s.index, _('j'))
@ -209,8 +209,8 @@ class BaseStrTest:
_ = self.from_latin1 _ = self.from_latin1
s = _('A') * size s = _('A') * size
x = s.join([_('aaaaa'), _('bbbbb')]) x = s.join([_('aaaaa'), _('bbbbb')])
self.assertEquals(x.count(_('a')), 5) self.assertEqual(x.count(_('a')), 5)
self.assertEquals(x.count(_('b')), 5) self.assertEqual(x.count(_('b')), 5)
self.assertTrue(x.startswith(_('aaaaaA'))) self.assertTrue(x.startswith(_('aaaaaA')))
self.assertTrue(x.endswith(_('Abbbbb'))) self.assertTrue(x.endswith(_('Abbbbb')))
@ -220,27 +220,27 @@ class BaseStrTest:
SUBSTR = _(' abc def ghi') SUBSTR = _(' abc def ghi')
s = SUBSTR.ljust(size) s = SUBSTR.ljust(size)
self.assertTrue(s.startswith(SUBSTR + _(' '))) self.assertTrue(s.startswith(SUBSTR + _(' ')))
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
self.assertEquals(s.strip(), SUBSTR.strip()) self.assertEqual(s.strip(), SUBSTR.strip())
@bigmemtest(minsize=_2G + 10, memuse=2) @bigmemtest(minsize=_2G + 10, memuse=2)
def test_lower(self, size): def test_lower(self, size):
_ = self.from_latin1 _ = self.from_latin1
s = _('A') * size s = _('A') * size
s = s.lower() s = s.lower()
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
self.assertEquals(s.count(_('a')), size) self.assertEqual(s.count(_('a')), size)
@bigmemtest(minsize=_2G + 10, memuse=1) @bigmemtest(minsize=_2G + 10, memuse=1)
def test_lstrip(self, size): def test_lstrip(self, size):
_ = self.from_latin1 _ = self.from_latin1
SUBSTR = _('abc def ghi') SUBSTR = _('abc def ghi')
s = SUBSTR.rjust(size) s = SUBSTR.rjust(size)
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
self.assertEquals(s.lstrip(), SUBSTR.lstrip()) self.assertEqual(s.lstrip(), SUBSTR.lstrip())
del s del s
s = SUBSTR.ljust(size) s = SUBSTR.ljust(size)
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
# Type-specific optimization # Type-specific optimization
if isinstance(s, (str, bytes)): if isinstance(s, (str, bytes)):
stripped = s.lstrip() stripped = s.lstrip()
@ -252,12 +252,12 @@ class BaseStrTest:
replacement = _('a') replacement = _('a')
s = _(' ') * size s = _(' ') * size
s = s.replace(_(' '), replacement) s = s.replace(_(' '), replacement)
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
self.assertEquals(s.count(replacement), size) self.assertEqual(s.count(replacement), size)
s = s.replace(replacement, _(' '), size - 4) s = s.replace(replacement, _(' '), size - 4)
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
self.assertEquals(s.count(replacement), 4) self.assertEqual(s.count(replacement), 4)
self.assertEquals(s[-10:], _(' aaaa')) self.assertEqual(s[-10:], _(' aaaa'))
@bigmemtest(minsize=_2G, memuse=2) @bigmemtest(minsize=_2G, memuse=2)
def test_rfind(self, size): def test_rfind(self, size):
@ -265,15 +265,15 @@ class BaseStrTest:
SUBSTR = _(' abc def ghi') SUBSTR = _(' abc def ghi')
sublen = len(SUBSTR) sublen = len(SUBSTR)
s = _('').join([SUBSTR, _('-') * size, SUBSTR]) s = _('').join([SUBSTR, _('-') * size, SUBSTR])
self.assertEquals(s.rfind(_(' ')), sublen + size + SUBSTR.rfind(_(' '))) self.assertEqual(s.rfind(_(' ')), sublen + size + SUBSTR.rfind(_(' ')))
self.assertEquals(s.rfind(SUBSTR), sublen + size) self.assertEqual(s.rfind(SUBSTR), sublen + size)
self.assertEquals(s.rfind(_(' '), 0, size), SUBSTR.rfind(_(' '))) self.assertEqual(s.rfind(_(' '), 0, size), SUBSTR.rfind(_(' ')))
self.assertEquals(s.rfind(SUBSTR, 0, sublen + size), 0) self.assertEqual(s.rfind(SUBSTR, 0, sublen + size), 0)
self.assertEquals(s.rfind(_('i')), sublen + size + SUBSTR.rfind(_('i'))) self.assertEqual(s.rfind(_('i')), sublen + size + SUBSTR.rfind(_('i')))
self.assertEquals(s.rfind(_('i'), 0, sublen), SUBSTR.rfind(_('i'))) self.assertEqual(s.rfind(_('i'), 0, sublen), SUBSTR.rfind(_('i')))
self.assertEquals(s.rfind(_('i'), 0, sublen + size), self.assertEqual(s.rfind(_('i'), 0, sublen + size),
SUBSTR.rfind(_('i'))) SUBSTR.rfind(_('i')))
self.assertEquals(s.rfind(_('j')), -1) self.assertEqual(s.rfind(_('j')), -1)
@bigmemtest(minsize=_2G, memuse=2) @bigmemtest(minsize=_2G, memuse=2)
def test_rindex(self, size): def test_rindex(self, size):
@ -281,17 +281,17 @@ class BaseStrTest:
SUBSTR = _(' abc def ghi') SUBSTR = _(' abc def ghi')
sublen = len(SUBSTR) sublen = len(SUBSTR)
s = _('').join([SUBSTR, _('-') * size, SUBSTR]) s = _('').join([SUBSTR, _('-') * size, SUBSTR])
self.assertEquals(s.rindex(_(' ')), self.assertEqual(s.rindex(_(' ')),
sublen + size + SUBSTR.rindex(_(' '))) sublen + size + SUBSTR.rindex(_(' ')))
self.assertEquals(s.rindex(SUBSTR), sublen + size) self.assertEqual(s.rindex(SUBSTR), sublen + size)
self.assertEquals(s.rindex(_(' '), 0, sublen + size - 1), self.assertEqual(s.rindex(_(' '), 0, sublen + size - 1),
SUBSTR.rindex(_(' '))) SUBSTR.rindex(_(' ')))
self.assertEquals(s.rindex(SUBSTR, 0, sublen + size), 0) self.assertEqual(s.rindex(SUBSTR, 0, sublen + size), 0)
self.assertEquals(s.rindex(_('i')), self.assertEqual(s.rindex(_('i')),
sublen + size + SUBSTR.rindex(_('i'))) sublen + size + SUBSTR.rindex(_('i')))
self.assertEquals(s.rindex(_('i'), 0, sublen), SUBSTR.rindex(_('i'))) self.assertEqual(s.rindex(_('i'), 0, sublen), SUBSTR.rindex(_('i')))
self.assertEquals(s.rindex(_('i'), 0, sublen + size), self.assertEqual(s.rindex(_('i'), 0, sublen + size),
SUBSTR.rindex(_('i'))) SUBSTR.rindex(_('i')))
self.assertRaises(ValueError, s.rindex, _('j')) self.assertRaises(ValueError, s.rindex, _('j'))
@bigmemtest(minsize=_2G + 10, memuse=1) @bigmemtest(minsize=_2G + 10, memuse=1)
@ -300,19 +300,19 @@ class BaseStrTest:
SUBSTR = _(' abc def ghi') SUBSTR = _(' abc def ghi')
s = SUBSTR.ljust(size) s = SUBSTR.ljust(size)
self.assertTrue(s.startswith(SUBSTR + _(' '))) self.assertTrue(s.startswith(SUBSTR + _(' ')))
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
self.assertEquals(s.strip(), SUBSTR.strip()) self.assertEqual(s.strip(), SUBSTR.strip())
@bigmemtest(minsize=_2G + 10, memuse=1) @bigmemtest(minsize=_2G + 10, memuse=1)
def test_rstrip(self, size): def test_rstrip(self, size):
_ = self.from_latin1 _ = self.from_latin1
SUBSTR = _(' abc def ghi') SUBSTR = _(' abc def ghi')
s = SUBSTR.ljust(size) s = SUBSTR.ljust(size)
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
self.assertEquals(s.rstrip(), SUBSTR.rstrip()) self.assertEqual(s.rstrip(), SUBSTR.rstrip())
del s del s
s = SUBSTR.rjust(size) s = SUBSTR.rjust(size)
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
# Type-specific optimization # Type-specific optimization
if isinstance(s, (str, bytes)): if isinstance(s, (str, bytes)):
stripped = s.rstrip() stripped = s.rstrip()
@ -330,16 +330,16 @@ class BaseStrTest:
SUBSTR = _('a') + _(' ') * chunksize SUBSTR = _('a') + _(' ') * chunksize
s = SUBSTR * chunksize s = SUBSTR * chunksize
l = s.split() l = s.split()
self.assertEquals(len(l), chunksize) self.assertEqual(len(l), chunksize)
expected = _('a') expected = _('a')
for item in l: for item in l:
self.assertEquals(item, expected) self.assertEqual(item, expected)
del l del l
l = s.split(_('a')) l = s.split(_('a'))
self.assertEquals(len(l), chunksize + 1) self.assertEqual(len(l), chunksize + 1)
expected = _(' ') * chunksize expected = _(' ') * chunksize
for item in filter(None, l): for item in filter(None, l):
self.assertEquals(item, expected) self.assertEqual(item, expected)
# Allocates a string of twice size (and briefly two) and a list of # Allocates a string of twice size (and briefly two) and a list of
# size. Because of internal affairs, the s.split() call produces a # size. Because of internal affairs, the s.split() call produces a
@ -352,12 +352,12 @@ class BaseStrTest:
_ = self.from_latin1 _ = self.from_latin1
s = _(' a') * size + _(' ') s = _(' a') * size + _(' ')
l = s.split() l = s.split()
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(set(l), set([_('a')])) self.assertEqual(set(l), set([_('a')]))
del l del l
l = s.split(_('a')) l = s.split(_('a'))
self.assertEquals(len(l), size + 1) self.assertEqual(len(l), size + 1)
self.assertEquals(set(l), set([_(' ')])) self.assertEqual(set(l), set([_(' ')]))
@bigmemtest(minsize=_2G, memuse=2.1) @bigmemtest(minsize=_2G, memuse=2.1)
def test_splitlines(self, size): def test_splitlines(self, size):
@ -368,10 +368,10 @@ class BaseStrTest:
SUBSTR = _(' ') * chunksize + _('\n') + _(' ') * chunksize + _('\r\n') SUBSTR = _(' ') * chunksize + _('\n') + _(' ') * chunksize + _('\r\n')
s = SUBSTR * chunksize s = SUBSTR * chunksize
l = s.splitlines() l = s.splitlines()
self.assertEquals(len(l), chunksize * 2) self.assertEqual(len(l), chunksize * 2)
expected = _(' ') * chunksize expected = _(' ') * chunksize
for item in l: for item in l:
self.assertEquals(item, expected) self.assertEqual(item, expected)
@bigmemtest(minsize=_2G, memuse=2) @bigmemtest(minsize=_2G, memuse=2)
def test_startswith(self, size): def test_startswith(self, size):
@ -387,12 +387,12 @@ class BaseStrTest:
_ = self.from_latin1 _ = self.from_latin1
SUBSTR = _(' abc def ghi ') SUBSTR = _(' abc def ghi ')
s = SUBSTR.rjust(size) s = SUBSTR.rjust(size)
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
self.assertEquals(s.strip(), SUBSTR.strip()) self.assertEqual(s.strip(), SUBSTR.strip())
del s del s
s = SUBSTR.ljust(size) s = SUBSTR.ljust(size)
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
self.assertEquals(s.strip(), SUBSTR.strip()) self.assertEqual(s.strip(), SUBSTR.strip())
@bigmemtest(minsize=_2G, memuse=2) @bigmemtest(minsize=_2G, memuse=2)
def test_swapcase(self, size): def test_swapcase(self, size):
@ -402,9 +402,9 @@ class BaseStrTest:
repeats = size // sublen + 2 repeats = size // sublen + 2
s = SUBSTR * repeats s = SUBSTR * repeats
s = s.swapcase() s = s.swapcase()
self.assertEquals(len(s), sublen * repeats) self.assertEqual(len(s), sublen * repeats)
self.assertEquals(s[:sublen * 3], SUBSTR.swapcase() * 3) self.assertEqual(s[:sublen * 3], SUBSTR.swapcase() * 3)
self.assertEquals(s[-sublen * 3:], SUBSTR.swapcase() * 3) self.assertEqual(s[-sublen * 3:], SUBSTR.swapcase() * 3)
@bigmemtest(minsize=_2G, memuse=2) @bigmemtest(minsize=_2G, memuse=2)
def test_title(self, size): def test_title(self, size):
@ -431,20 +431,20 @@ class BaseStrTest:
repeats = size // sublen + 2 repeats = size // sublen + 2
s = SUBSTR * repeats s = SUBSTR * repeats
s = s.translate(trans) s = s.translate(trans)
self.assertEquals(len(s), repeats * sublen) self.assertEqual(len(s), repeats * sublen)
self.assertEquals(s[:sublen], SUBSTR.translate(trans)) self.assertEqual(s[:sublen], SUBSTR.translate(trans))
self.assertEquals(s[-sublen:], SUBSTR.translate(trans)) self.assertEqual(s[-sublen:], SUBSTR.translate(trans))
self.assertEquals(s.count(_('.')), 0) self.assertEqual(s.count(_('.')), 0)
self.assertEquals(s.count(_('!')), repeats * 2) self.assertEqual(s.count(_('!')), repeats * 2)
self.assertEquals(s.count(_('z')), repeats * 3) self.assertEqual(s.count(_('z')), repeats * 3)
@bigmemtest(minsize=_2G + 5, memuse=2) @bigmemtest(minsize=_2G + 5, memuse=2)
def test_upper(self, size): def test_upper(self, size):
_ = self.from_latin1 _ = self.from_latin1
s = _('a') * size s = _('a') * size
s = s.upper() s = s.upper()
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
self.assertEquals(s.count(_('A')), size) self.assertEqual(s.count(_('A')), size)
@bigmemtest(minsize=_2G + 20, memuse=1) @bigmemtest(minsize=_2G + 20, memuse=1)
def test_zfill(self, size): def test_zfill(self, size):
@ -453,8 +453,8 @@ class BaseStrTest:
s = SUBSTR.zfill(size) s = SUBSTR.zfill(size)
self.assertTrue(s.endswith(_('0') + SUBSTR[1:])) self.assertTrue(s.endswith(_('0') + SUBSTR[1:]))
self.assertTrue(s.startswith(_('-0'))) self.assertTrue(s.startswith(_('-0')))
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
self.assertEquals(s.count(_('0')), size - len(SUBSTR)) self.assertEqual(s.count(_('0')), size - len(SUBSTR))
# This test is meaningful even with size < 2G, as long as the # This test is meaningful even with size < 2G, as long as the
# doubled string is > 2G (but it tests more if both are > 2G :) # doubled string is > 2G (but it tests more if both are > 2G :)
@ -462,10 +462,10 @@ class BaseStrTest:
def test_concat(self, size): def test_concat(self, size):
_ = self.from_latin1 _ = self.from_latin1
s = _('.') * size s = _('.') * size
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
s = s + s s = s + s
self.assertEquals(len(s), size * 2) self.assertEqual(len(s), size * 2)
self.assertEquals(s.count(_('.')), size * 2) self.assertEqual(s.count(_('.')), size * 2)
# This test is meaningful even with size < 2G, as long as the # This test is meaningful even with size < 2G, as long as the
# repeated string is > 2G (but it tests more if both are > 2G :) # repeated string is > 2G (but it tests more if both are > 2G :)
@ -473,10 +473,10 @@ class BaseStrTest:
def test_repeat(self, size): def test_repeat(self, size):
_ = self.from_latin1 _ = self.from_latin1
s = _('.') * size s = _('.') * size
self.assertEquals(len(s), size) self.assertEqual(len(s), size)
s = s * 2 s = s * 2
self.assertEquals(len(s), size * 2) self.assertEqual(len(s), size * 2)
self.assertEquals(s.count(_('.')), size * 2) self.assertEqual(s.count(_('.')), size * 2)
@bigmemtest(minsize=_2G + 20, memuse=2) @bigmemtest(minsize=_2G + 20, memuse=2)
def test_slice_and_getitem(self, size): def test_slice_and_getitem(self, size):
@ -487,26 +487,26 @@ class BaseStrTest:
stepsize = len(s) // 100 stepsize = len(s) // 100
stepsize = stepsize - (stepsize % sublen) stepsize = stepsize - (stepsize % sublen)
for i in range(0, len(s) - stepsize, stepsize): for i in range(0, len(s) - stepsize, stepsize):
self.assertEquals(s[i], SUBSTR[0]) self.assertEqual(s[i], SUBSTR[0])
self.assertEquals(s[i:i + sublen], SUBSTR) self.assertEqual(s[i:i + sublen], SUBSTR)
self.assertEquals(s[i:i + sublen:2], SUBSTR[::2]) self.assertEqual(s[i:i + sublen:2], SUBSTR[::2])
if i > 0: if i > 0:
self.assertEquals(s[i + sublen - 1:i - 1:-3], self.assertEqual(s[i + sublen - 1:i - 1:-3],
SUBSTR[sublen::-3]) SUBSTR[sublen::-3])
# Make sure we do some slicing and indexing near the end of the # Make sure we do some slicing and indexing near the end of the
# string, too. # string, too.
self.assertEquals(s[len(s) - 1], SUBSTR[-1]) self.assertEqual(s[len(s) - 1], SUBSTR[-1])
self.assertEquals(s[-1], SUBSTR[-1]) self.assertEqual(s[-1], SUBSTR[-1])
self.assertEquals(s[len(s) - 10], SUBSTR[0]) self.assertEqual(s[len(s) - 10], SUBSTR[0])
self.assertEquals(s[-sublen], SUBSTR[0]) self.assertEqual(s[-sublen], SUBSTR[0])
self.assertEquals(s[len(s):], _('')) self.assertEqual(s[len(s):], _(''))
self.assertEquals(s[len(s) - 1:], SUBSTR[-1:]) self.assertEqual(s[len(s) - 1:], SUBSTR[-1:])
self.assertEquals(s[-1:], SUBSTR[-1:]) self.assertEqual(s[-1:], SUBSTR[-1:])
self.assertEquals(s[len(s) - sublen:], SUBSTR) self.assertEqual(s[len(s) - sublen:], SUBSTR)
self.assertEquals(s[-sublen:], SUBSTR) self.assertEqual(s[-sublen:], SUBSTR)
self.assertEquals(len(s[:]), len(s)) self.assertEqual(len(s[:]), len(s))
self.assertEquals(len(s[:len(s) - 5]), len(s) - 5) self.assertEqual(len(s[:len(s) - 5]), len(s) - 5)
self.assertEquals(len(s[5:-5]), len(s) - 10) self.assertEqual(len(s[5:-5]), len(s) - 10)
self.assertRaises(IndexError, operator.getitem, s, len(s)) self.assertRaises(IndexError, operator.getitem, s, len(s))
self.assertRaises(IndexError, operator.getitem, s, len(s) + 1) self.assertRaises(IndexError, operator.getitem, s, len(s) + 1)
@ -565,7 +565,7 @@ class StrTest(unittest.TestCase, BaseStrTest):
expectedsize = size expectedsize = size
s = c * size s = c * size
self.assertEquals(len(s.encode(enc)), expectedsize) self.assertEqual(len(s.encode(enc)), expectedsize)
def setUp(self): def setUp(self):
# HACK: adjust memory use of tests inherited from BaseStrTest # HACK: adjust memory use of tests inherited from BaseStrTest
@ -632,7 +632,7 @@ class StrTest(unittest.TestCase, BaseStrTest):
self.assertEqual(s, sf) self.assertEqual(s, sf)
del sf del sf
sf = '..%s..' % (s,) sf = '..%s..' % (s,)
self.assertEquals(len(sf), len(s) + 4) self.assertEqual(len(sf), len(s) + 4)
self.assertTrue(sf.startswith('..-')) self.assertTrue(sf.startswith('..-'))
self.assertTrue(sf.endswith('-..')) self.assertTrue(sf.endswith('-..'))
del s, sf del s, sf
@ -642,18 +642,18 @@ class StrTest(unittest.TestCase, BaseStrTest):
s = ''.join([edge, '%s', edge]) s = ''.join([edge, '%s', edge])
del edge del edge
s = s % '...' s = s % '...'
self.assertEquals(len(s), size * 2 + 3) self.assertEqual(len(s), size * 2 + 3)
self.assertEquals(s.count('.'), 3) self.assertEqual(s.count('.'), 3)
self.assertEquals(s.count('-'), size * 2) self.assertEqual(s.count('-'), size * 2)
@bigmemtest(minsize=_2G + 10, memuse=character_size * 2) @bigmemtest(minsize=_2G + 10, memuse=character_size * 2)
def test_repr_small(self, size): def test_repr_small(self, size):
s = '-' * size s = '-' * size
s = repr(s) s = repr(s)
self.assertEquals(len(s), size + 2) self.assertEqual(len(s), size + 2)
self.assertEquals(s[0], "'") self.assertEqual(s[0], "'")
self.assertEquals(s[-1], "'") self.assertEqual(s[-1], "'")
self.assertEquals(s.count('-'), size) self.assertEqual(s.count('-'), size)
del s del s
# repr() will create a string four times as large as this 'binary # repr() will create a string four times as large as this 'binary
# string', but we don't want to allocate much more than twice # string', but we don't want to allocate much more than twice
@ -661,21 +661,21 @@ class StrTest(unittest.TestCase, BaseStrTest):
size = size // 5 * 2 size = size // 5 * 2
s = '\x00' * size s = '\x00' * size
s = repr(s) s = repr(s)
self.assertEquals(len(s), size * 4 + 2) self.assertEqual(len(s), size * 4 + 2)
self.assertEquals(s[0], "'") self.assertEqual(s[0], "'")
self.assertEquals(s[-1], "'") self.assertEqual(s[-1], "'")
self.assertEquals(s.count('\\'), size) self.assertEqual(s.count('\\'), size)
self.assertEquals(s.count('0'), size * 2) self.assertEqual(s.count('0'), size * 2)
@bigmemtest(minsize=_2G + 10, memuse=character_size * 5) @bigmemtest(minsize=_2G + 10, memuse=character_size * 5)
def test_repr_large(self, size): def test_repr_large(self, size):
s = '\x00' * size s = '\x00' * size
s = repr(s) s = repr(s)
self.assertEquals(len(s), size * 4 + 2) self.assertEqual(len(s), size * 4 + 2)
self.assertEquals(s[0], "'") self.assertEqual(s[0], "'")
self.assertEquals(s[-1], "'") self.assertEqual(s[-1], "'")
self.assertEquals(s.count('\\'), size) self.assertEqual(s.count('\\'), size)
self.assertEquals(s.count('0'), size * 2) self.assertEqual(s.count('0'), size * 2)
@bigmemtest(minsize=2**32 / 5, memuse=character_size * 7) @bigmemtest(minsize=2**32 / 5, memuse=character_size * 7)
def test_unicode_repr(self, size): def test_unicode_repr(self, size):
@ -708,7 +708,7 @@ class BytesTest(unittest.TestCase, BaseStrTest):
@bigmemtest(minsize=_2G + 2, memuse=1 + character_size) @bigmemtest(minsize=_2G + 2, memuse=1 + character_size)
def test_decode(self, size): def test_decode(self, size):
s = self.from_latin1('.') * size s = self.from_latin1('.') * size
self.assertEquals(len(s.decode('utf-8')), size) self.assertEqual(len(s.decode('utf-8')), size)
class BytearrayTest(unittest.TestCase, BaseStrTest): class BytearrayTest(unittest.TestCase, BaseStrTest):
@ -719,7 +719,7 @@ class BytearrayTest(unittest.TestCase, BaseStrTest):
@bigmemtest(minsize=_2G + 2, memuse=1 + character_size) @bigmemtest(minsize=_2G + 2, memuse=1 + character_size)
def test_decode(self, size): def test_decode(self, size):
s = self.from_latin1('.') * size s = self.from_latin1('.') * size
self.assertEquals(len(s.decode('utf-8')), size) self.assertEqual(len(s.decode('utf-8')), size)
test_hash = None test_hash = None
test_split_large = None test_split_large = None
@ -754,9 +754,9 @@ class TupleTest(unittest.TestCase):
# skipped, in verbose mode.) # skipped, in verbose mode.)
def basic_concat_test(self, size): def basic_concat_test(self, size):
t = ((),) * size t = ((),) * size
self.assertEquals(len(t), size) self.assertEqual(len(t), size)
t = t + t t = t + t
self.assertEquals(len(t), size * 2) self.assertEqual(len(t), size * 2)
@bigmemtest(minsize=_2G // 2 + 2, memuse=24) @bigmemtest(minsize=_2G // 2 + 2, memuse=24)
def test_concat_small(self, size): def test_concat_small(self, size):
@ -769,7 +769,7 @@ class TupleTest(unittest.TestCase):
@bigmemtest(minsize=_2G // 5 + 10, memuse=8 * 5) @bigmemtest(minsize=_2G // 5 + 10, memuse=8 * 5)
def test_contains(self, size): def test_contains(self, size):
t = (1, 2, 3, 4, 5) * size t = (1, 2, 3, 4, 5) * size
self.assertEquals(len(t), size * 5) self.assertEqual(len(t), size * 5)
self.assertIn(5, t) self.assertIn(5, t)
self.assertNotIn((1, 2, 3, 4, 5), t) self.assertNotIn((1, 2, 3, 4, 5), t)
self.assertNotIn(0, t) self.assertNotIn(0, t)
@ -785,27 +785,27 @@ class TupleTest(unittest.TestCase):
@bigmemtest(minsize=_2G + 10, memuse=8) @bigmemtest(minsize=_2G + 10, memuse=8)
def test_index_and_slice(self, size): def test_index_and_slice(self, size):
t = (None,) * size t = (None,) * size
self.assertEquals(len(t), size) self.assertEqual(len(t), size)
self.assertEquals(t[-1], None) self.assertEqual(t[-1], None)
self.assertEquals(t[5], None) self.assertEqual(t[5], None)
self.assertEquals(t[size - 1], None) self.assertEqual(t[size - 1], None)
self.assertRaises(IndexError, operator.getitem, t, size) self.assertRaises(IndexError, operator.getitem, t, size)
self.assertEquals(t[:5], (None,) * 5) self.assertEqual(t[:5], (None,) * 5)
self.assertEquals(t[-5:], (None,) * 5) self.assertEqual(t[-5:], (None,) * 5)
self.assertEquals(t[20:25], (None,) * 5) self.assertEqual(t[20:25], (None,) * 5)
self.assertEquals(t[-25:-20], (None,) * 5) self.assertEqual(t[-25:-20], (None,) * 5)
self.assertEquals(t[size - 5:], (None,) * 5) self.assertEqual(t[size - 5:], (None,) * 5)
self.assertEquals(t[size - 5:size], (None,) * 5) self.assertEqual(t[size - 5:size], (None,) * 5)
self.assertEquals(t[size - 6:size - 2], (None,) * 4) self.assertEqual(t[size - 6:size - 2], (None,) * 4)
self.assertEquals(t[size:size], ()) self.assertEqual(t[size:size], ())
self.assertEquals(t[size:size+5], ()) self.assertEqual(t[size:size+5], ())
# Like test_concat, split in two. # Like test_concat, split in two.
def basic_test_repeat(self, size): def basic_test_repeat(self, size):
t = ('',) * size t = ('',) * size
self.assertEquals(len(t), size) self.assertEqual(len(t), size)
t = t * 2 t = t * 2
self.assertEquals(len(t), size * 2) self.assertEqual(len(t), size * 2)
@bigmemtest(minsize=_2G // 2 + 2, memuse=24) @bigmemtest(minsize=_2G // 2 + 2, memuse=24)
def test_repeat_small(self, size): def test_repeat_small(self, size):
@ -829,9 +829,9 @@ class TupleTest(unittest.TestCase):
else: else:
count = 0 count = 0
for item in t: for item in t:
self.assertEquals(item, count) self.assertEqual(item, count)
count += 1 count += 1
self.assertEquals(count, size) self.assertEqual(count, size)
@precisionbigmemtest(size=_1G - 25, memuse=9) @precisionbigmemtest(size=_1G - 25, memuse=9)
def test_from_almost_2G_generator(self, size): def test_from_almost_2G_generator(self, size):
@ -840,9 +840,9 @@ class TupleTest(unittest.TestCase):
t = tuple(range(size)) t = tuple(range(size))
count = 0 count = 0
for item in t: for item in t:
self.assertEquals(item, count) self.assertEqual(item, count)
count += 1 count += 1
self.assertEquals(count, size) self.assertEqual(count, size)
except MemoryError: except MemoryError:
pass # acceptable, expected on 32-bit pass # acceptable, expected on 32-bit
@ -851,10 +851,10 @@ class TupleTest(unittest.TestCase):
t = (0,) * size t = (0,) * size
s = repr(t) s = repr(t)
# The repr of a tuple of 0's is exactly three times the tuple length. # The repr of a tuple of 0's is exactly three times the tuple length.
self.assertEquals(len(s), size * 3) self.assertEqual(len(s), size * 3)
self.assertEquals(s[:5], '(0, 0') self.assertEqual(s[:5], '(0, 0')
self.assertEquals(s[-5:], '0, 0)') self.assertEqual(s[-5:], '0, 0)')
self.assertEquals(s.count('0'), size) self.assertEqual(s.count('0'), size)
@bigmemtest(minsize=_2G // 3 + 2, memuse=8 + 3 * character_size) @bigmemtest(minsize=_2G // 3 + 2, memuse=8 + 3 * character_size)
def test_repr_small(self, size): def test_repr_small(self, size):
@ -890,9 +890,9 @@ class ListTest(unittest.TestCase):
# skipped, in verbose mode.) # skipped, in verbose mode.)
def basic_test_concat(self, size): def basic_test_concat(self, size):
l = [[]] * size l = [[]] * size
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
l = l + l l = l + l
self.assertEquals(len(l), size * 2) self.assertEqual(len(l), size * 2)
@bigmemtest(minsize=_2G // 2 + 2, memuse=24) @bigmemtest(minsize=_2G // 2 + 2, memuse=24)
def test_concat_small(self, size): def test_concat_small(self, size):
@ -905,7 +905,7 @@ class ListTest(unittest.TestCase):
def basic_test_inplace_concat(self, size): def basic_test_inplace_concat(self, size):
l = [sys.stdout] * size l = [sys.stdout] * size
l += l l += l
self.assertEquals(len(l), size * 2) self.assertEqual(len(l), size * 2)
self.assertTrue(l[0] is l[-1]) self.assertTrue(l[0] is l[-1])
self.assertTrue(l[size - 1] is l[size + 1]) self.assertTrue(l[size - 1] is l[size + 1])
@ -920,7 +920,7 @@ class ListTest(unittest.TestCase):
@bigmemtest(minsize=_2G // 5 + 10, memuse=8 * 5) @bigmemtest(minsize=_2G // 5 + 10, memuse=8 * 5)
def test_contains(self, size): def test_contains(self, size):
l = [1, 2, 3, 4, 5] * size l = [1, 2, 3, 4, 5] * size
self.assertEquals(len(l), size * 5) self.assertEqual(len(l), size * 5)
self.assertIn(5, l) self.assertIn(5, l)
self.assertNotIn([1, 2, 3, 4, 5], l) self.assertNotIn([1, 2, 3, 4, 5], l)
self.assertNotIn(0, l) self.assertNotIn(0, l)
@ -933,66 +933,66 @@ class ListTest(unittest.TestCase):
@bigmemtest(minsize=_2G + 10, memuse=8) @bigmemtest(minsize=_2G + 10, memuse=8)
def test_index_and_slice(self, size): def test_index_and_slice(self, size):
l = [None] * size l = [None] * size
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(l[-1], None) self.assertEqual(l[-1], None)
self.assertEquals(l[5], None) self.assertEqual(l[5], None)
self.assertEquals(l[size - 1], None) self.assertEqual(l[size - 1], None)
self.assertRaises(IndexError, operator.getitem, l, size) self.assertRaises(IndexError, operator.getitem, l, size)
self.assertEquals(l[:5], [None] * 5) self.assertEqual(l[:5], [None] * 5)
self.assertEquals(l[-5:], [None] * 5) self.assertEqual(l[-5:], [None] * 5)
self.assertEquals(l[20:25], [None] * 5) self.assertEqual(l[20:25], [None] * 5)
self.assertEquals(l[-25:-20], [None] * 5) self.assertEqual(l[-25:-20], [None] * 5)
self.assertEquals(l[size - 5:], [None] * 5) self.assertEqual(l[size - 5:], [None] * 5)
self.assertEquals(l[size - 5:size], [None] * 5) self.assertEqual(l[size - 5:size], [None] * 5)
self.assertEquals(l[size - 6:size - 2], [None] * 4) self.assertEqual(l[size - 6:size - 2], [None] * 4)
self.assertEquals(l[size:size], []) self.assertEqual(l[size:size], [])
self.assertEquals(l[size:size+5], []) self.assertEqual(l[size:size+5], [])
l[size - 2] = 5 l[size - 2] = 5
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(l[-3:], [None, 5, None]) self.assertEqual(l[-3:], [None, 5, None])
self.assertEquals(l.count(5), 1) self.assertEqual(l.count(5), 1)
self.assertRaises(IndexError, operator.setitem, l, size, 6) self.assertRaises(IndexError, operator.setitem, l, size, 6)
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
l[size - 7:] = [1, 2, 3, 4, 5] l[size - 7:] = [1, 2, 3, 4, 5]
size -= 2 size -= 2
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(l[-7:], [None, None, 1, 2, 3, 4, 5]) self.assertEqual(l[-7:], [None, None, 1, 2, 3, 4, 5])
l[:7] = [1, 2, 3, 4, 5] l[:7] = [1, 2, 3, 4, 5]
size -= 2 size -= 2
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(l[:7], [1, 2, 3, 4, 5, None, None]) self.assertEqual(l[:7], [1, 2, 3, 4, 5, None, None])
del l[size - 1] del l[size - 1]
size -= 1 size -= 1
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(l[-1], 4) self.assertEqual(l[-1], 4)
del l[-2:] del l[-2:]
size -= 2 size -= 2
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(l[-1], 2) self.assertEqual(l[-1], 2)
del l[0] del l[0]
size -= 1 size -= 1
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(l[0], 2) self.assertEqual(l[0], 2)
del l[:2] del l[:2]
size -= 2 size -= 2
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(l[0], 4) self.assertEqual(l[0], 4)
# Like test_concat, split in two. # Like test_concat, split in two.
def basic_test_repeat(self, size): def basic_test_repeat(self, size):
l = [] * size l = [] * size
self.assertFalse(l) self.assertFalse(l)
l = [''] * size l = [''] * size
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
l = l * 2 l = l * 2
self.assertEquals(len(l), size * 2) self.assertEqual(len(l), size * 2)
@bigmemtest(minsize=_2G // 2 + 2, memuse=24) @bigmemtest(minsize=_2G // 2 + 2, memuse=24)
def test_repeat_small(self, size): def test_repeat_small(self, size):
@ -1005,13 +1005,13 @@ class ListTest(unittest.TestCase):
def basic_test_inplace_repeat(self, size): def basic_test_inplace_repeat(self, size):
l = [''] l = ['']
l *= size l *= size
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertTrue(l[0] is l[-1]) self.assertTrue(l[0] is l[-1])
del l del l
l = [''] * size l = [''] * size
l *= 2 l *= 2
self.assertEquals(len(l), size * 2) self.assertEqual(len(l), size * 2)
self.assertTrue(l[size - 1] is l[-1]) self.assertTrue(l[size - 1] is l[-1])
@bigmemtest(minsize=_2G // 2 + 2, memuse=16) @bigmemtest(minsize=_2G // 2 + 2, memuse=16)
@ -1026,10 +1026,10 @@ class ListTest(unittest.TestCase):
l = [0] * size l = [0] * size
s = repr(l) s = repr(l)
# The repr of a list of 0's is exactly three times the list length. # The repr of a list of 0's is exactly three times the list length.
self.assertEquals(len(s), size * 3) self.assertEqual(len(s), size * 3)
self.assertEquals(s[:5], '[0, 0') self.assertEqual(s[:5], '[0, 0')
self.assertEquals(s[-5:], '0, 0]') self.assertEqual(s[-5:], '0, 0]')
self.assertEquals(s.count('0'), size) self.assertEqual(s.count('0'), size)
@bigmemtest(minsize=_2G // 3 + 2, memuse=8 + 3 * character_size) @bigmemtest(minsize=_2G // 3 + 2, memuse=8 + 3 * character_size)
def test_repr_small(self, size): def test_repr_small(self, size):
@ -1045,20 +1045,20 @@ class ListTest(unittest.TestCase):
def test_append(self, size): def test_append(self, size):
l = [object()] * size l = [object()] * size
l.append(object()) l.append(object())
self.assertEquals(len(l), size+1) self.assertEqual(len(l), size+1)
self.assertTrue(l[-3] is l[-2]) self.assertTrue(l[-3] is l[-2])
self.assertFalse(l[-2] is l[-1]) self.assertFalse(l[-2] is l[-1])
@bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5)
def test_count(self, size): def test_count(self, size):
l = [1, 2, 3, 4, 5] * size l = [1, 2, 3, 4, 5] * size
self.assertEquals(l.count(1), size) self.assertEqual(l.count(1), size)
self.assertEquals(l.count("1"), 0) self.assertEqual(l.count("1"), 0)
def basic_test_extend(self, size): def basic_test_extend(self, size):
l = [object] * size l = [object] * size
l.extend(l) l.extend(l)
self.assertEquals(len(l), size * 2) self.assertEqual(len(l), size * 2)
self.assertTrue(l[0] is l[-1]) self.assertTrue(l[0] is l[-1])
self.assertTrue(l[size - 1] is l[size + 1]) self.assertTrue(l[size - 1] is l[size + 1])
@ -1074,9 +1074,9 @@ class ListTest(unittest.TestCase):
def test_index(self, size): def test_index(self, size):
l = [1, 2, 3, 4, 5] * size l = [1, 2, 3, 4, 5] * size
size *= 5 size *= 5
self.assertEquals(l.index(1), 0) self.assertEqual(l.index(1), 0)
self.assertEquals(l.index(5, size - 5), size - 1) self.assertEqual(l.index(5, size - 5), size - 1)
self.assertEquals(l.index(5, size - 5, size), size - 1) self.assertEqual(l.index(5, size - 5, size), size - 1)
self.assertRaises(ValueError, l.index, 1, size - 4, size) self.assertRaises(ValueError, l.index, 1, size - 4, size)
self.assertRaises(ValueError, l.index, 6) self.assertRaises(ValueError, l.index, 6)
@ -1086,80 +1086,80 @@ class ListTest(unittest.TestCase):
l = [1.0] * size l = [1.0] * size
l.insert(size - 1, "A") l.insert(size - 1, "A")
size += 1 size += 1
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(l[-3:], [1.0, "A", 1.0]) self.assertEqual(l[-3:], [1.0, "A", 1.0])
l.insert(size + 1, "B") l.insert(size + 1, "B")
size += 1 size += 1
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(l[-3:], ["A", 1.0, "B"]) self.assertEqual(l[-3:], ["A", 1.0, "B"])
l.insert(1, "C") l.insert(1, "C")
size += 1 size += 1
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(l[:3], [1.0, "C", 1.0]) self.assertEqual(l[:3], [1.0, "C", 1.0])
self.assertEquals(l[size - 3:], ["A", 1.0, "B"]) self.assertEqual(l[size - 3:], ["A", 1.0, "B"])
@bigmemtest(minsize=_2G // 5 + 4, memuse=8 * 5) @bigmemtest(minsize=_2G // 5 + 4, memuse=8 * 5)
def test_pop(self, size): def test_pop(self, size):
l = ["a", "b", "c", "d", "e"] * size l = ["a", "b", "c", "d", "e"] * size
size *= 5 size *= 5
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
item = l.pop() item = l.pop()
size -= 1 size -= 1
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(item, "e") self.assertEqual(item, "e")
self.assertEquals(l[-2:], ["c", "d"]) self.assertEqual(l[-2:], ["c", "d"])
item = l.pop(0) item = l.pop(0)
size -= 1 size -= 1
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(item, "a") self.assertEqual(item, "a")
self.assertEquals(l[:2], ["b", "c"]) self.assertEqual(l[:2], ["b", "c"])
item = l.pop(size - 2) item = l.pop(size - 2)
size -= 1 size -= 1
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(item, "c") self.assertEqual(item, "c")
self.assertEquals(l[-2:], ["b", "d"]) self.assertEqual(l[-2:], ["b", "d"])
@bigmemtest(minsize=_2G + 10, memuse=8) @bigmemtest(minsize=_2G + 10, memuse=8)
def test_remove(self, size): def test_remove(self, size):
l = [10] * size l = [10] * size
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
l.remove(10) l.remove(10)
size -= 1 size -= 1
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
# Because of the earlier l.remove(), this append doesn't trigger # Because of the earlier l.remove(), this append doesn't trigger
# a resize. # a resize.
l.append(5) l.append(5)
size += 1 size += 1
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(l[-2:], [10, 5]) self.assertEqual(l[-2:], [10, 5])
l.remove(5) l.remove(5)
size -= 1 size -= 1
self.assertEquals(len(l), size) self.assertEqual(len(l), size)
self.assertEquals(l[-2:], [10, 10]) self.assertEqual(l[-2:], [10, 10])
@bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5)
def test_reverse(self, size): def test_reverse(self, size):
l = [1, 2, 3, 4, 5] * size l = [1, 2, 3, 4, 5] * size
l.reverse() l.reverse()
self.assertEquals(len(l), size * 5) self.assertEqual(len(l), size * 5)
self.assertEquals(l[-5:], [5, 4, 3, 2, 1]) self.assertEqual(l[-5:], [5, 4, 3, 2, 1])
self.assertEquals(l[:5], [5, 4, 3, 2, 1]) self.assertEqual(l[:5], [5, 4, 3, 2, 1])
@bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5) @bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5)
def test_sort(self, size): def test_sort(self, size):
l = [1, 2, 3, 4, 5] * size l = [1, 2, 3, 4, 5] * size
l.sort() l.sort()
self.assertEquals(len(l), size * 5) self.assertEqual(len(l), size * 5)
self.assertEquals(l.count(1), size) self.assertEqual(l.count(1), size)
self.assertEquals(l[:10], [1] * 10) self.assertEqual(l[:10], [1] * 10)
self.assertEquals(l[-10:], [5] * 10) self.assertEqual(l[-10:], [5] * 10)
def test_main(): def test_main():
support.run_unittest(StrTest, BytesTest, BytearrayTest, support.run_unittest(StrTest, BytesTest, BytearrayTest,

View File

@ -542,11 +542,11 @@ class BuiltinTest(unittest.TestCase):
class X: class X:
def __hash__(self): def __hash__(self):
return 2**100 return 2**100
self.assertEquals(type(hash(X())), int) self.assertEqual(type(hash(X())), int)
class Z(int): class Z(int):
def __hash__(self): def __hash__(self):
return self return self
self.assertEquals(hash(Z(42)), hash(42)) self.assertEqual(hash(Z(42)), hash(42))
def test_hex(self): def test_hex(self):
self.assertEqual(hex(16), '0x10') self.assertEqual(hex(16), '0x10')
@ -777,7 +777,7 @@ class BuiltinTest(unittest.TestCase):
self.assertEqual(next(it), 1) self.assertEqual(next(it), 1)
self.assertRaises(StopIteration, next, it) self.assertRaises(StopIteration, next, it)
self.assertRaises(StopIteration, next, it) self.assertRaises(StopIteration, next, it)
self.assertEquals(next(it, 42), 42) self.assertEqual(next(it, 42), 42)
class Iter(object): class Iter(object):
def __iter__(self): def __iter__(self):
@ -786,7 +786,7 @@ class BuiltinTest(unittest.TestCase):
raise StopIteration raise StopIteration
it = iter(Iter()) it = iter(Iter())
self.assertEquals(next(it, 42), 42) self.assertEqual(next(it, 42), 42)
self.assertRaises(StopIteration, next, it) self.assertRaises(StopIteration, next, it)
def gen(): def gen():
@ -794,9 +794,9 @@ class BuiltinTest(unittest.TestCase):
return return
it = gen() it = gen()
self.assertEquals(next(it), 1) self.assertEqual(next(it), 1)
self.assertRaises(StopIteration, next, it) self.assertRaises(StopIteration, next, it)
self.assertEquals(next(it, 42), 42) self.assertEqual(next(it, 42), 42)
def test_oct(self): def test_oct(self):
self.assertEqual(oct(100), '0o144') self.assertEqual(oct(100), '0o144')

View File

@ -266,11 +266,11 @@ class BaseBytesTest(unittest.TestCase):
def test_fromhex(self): def test_fromhex(self):
self.assertRaises(TypeError, self.type2test.fromhex) self.assertRaises(TypeError, self.type2test.fromhex)
self.assertRaises(TypeError, self.type2test.fromhex, 1) self.assertRaises(TypeError, self.type2test.fromhex, 1)
self.assertEquals(self.type2test.fromhex(''), self.type2test()) self.assertEqual(self.type2test.fromhex(''), self.type2test())
b = bytearray([0x1a, 0x2b, 0x30]) b = bytearray([0x1a, 0x2b, 0x30])
self.assertEquals(self.type2test.fromhex('1a2B30'), b) self.assertEqual(self.type2test.fromhex('1a2B30'), b)
self.assertEquals(self.type2test.fromhex(' 1A 2B 30 '), b) self.assertEqual(self.type2test.fromhex(' 1A 2B 30 '), b)
self.assertEquals(self.type2test.fromhex('0000'), b'\0\0') self.assertEqual(self.type2test.fromhex('0000'), b'\0\0')
self.assertRaises(TypeError, self.type2test.fromhex, b'1B') self.assertRaises(TypeError, self.type2test.fromhex, b'1B')
self.assertRaises(ValueError, self.type2test.fromhex, 'a') self.assertRaises(ValueError, self.type2test.fromhex, 'a')
self.assertRaises(ValueError, self.type2test.fromhex, 'rt') self.assertRaises(ValueError, self.type2test.fromhex, 'rt')
@ -626,11 +626,11 @@ class ByteArrayTest(BaseBytesTest):
data.reverse() data.reverse()
L[start:stop:step] = data L[start:stop:step] = data
b[start:stop:step] = data b[start:stop:step] = data
self.assertEquals(b, bytearray(L)) self.assertEqual(b, bytearray(L))
del L[start:stop:step] del L[start:stop:step]
del b[start:stop:step] del b[start:stop:step]
self.assertEquals(b, bytearray(L)) self.assertEqual(b, bytearray(L))
def test_setslice_trap(self): def test_setslice_trap(self):
# This test verifies that we correctly handle assigning self # This test verifies that we correctly handle assigning self
@ -809,25 +809,25 @@ class ByteArrayTest(BaseBytesTest):
resize(10) resize(10)
orig = b[:] orig = b[:]
self.assertRaises(BufferError, resize, 11) self.assertRaises(BufferError, resize, 11)
self.assertEquals(b, orig) self.assertEqual(b, orig)
self.assertRaises(BufferError, resize, 9) self.assertRaises(BufferError, resize, 9)
self.assertEquals(b, orig) self.assertEqual(b, orig)
self.assertRaises(BufferError, resize, 0) self.assertRaises(BufferError, resize, 0)
self.assertEquals(b, orig) self.assertEqual(b, orig)
# Other operations implying resize # Other operations implying resize
self.assertRaises(BufferError, b.pop, 0) self.assertRaises(BufferError, b.pop, 0)
self.assertEquals(b, orig) self.assertEqual(b, orig)
self.assertRaises(BufferError, b.remove, b[1]) self.assertRaises(BufferError, b.remove, b[1])
self.assertEquals(b, orig) self.assertEqual(b, orig)
def delitem(): def delitem():
del b[1] del b[1]
self.assertRaises(BufferError, delitem) self.assertRaises(BufferError, delitem)
self.assertEquals(b, orig) self.assertEqual(b, orig)
# deleting a non-contiguous slice # deleting a non-contiguous slice
def delslice(): def delslice():
b[1:-1:2] = b"" b[1:-1:2] = b""
self.assertRaises(BufferError, delslice) self.assertRaises(BufferError, delslice)
self.assertEquals(b, orig) self.assertEqual(b, orig)
class AssortedBytesTest(unittest.TestCase): class AssortedBytesTest(unittest.TestCase):

View File

@ -262,7 +262,7 @@ class CalendarTestCase(unittest.TestCase):
return return
calendar.LocaleHTMLCalendar(locale='').formatmonthname(2010, 10) calendar.LocaleHTMLCalendar(locale='').formatmonthname(2010, 10)
new_october = calendar.TextCalendar().formatmonthname(2010, 10, 10) new_october = calendar.TextCalendar().formatmonthname(2010, 10, 10)
self.assertEquals(old_october, new_october) self.assertEqual(old_october, new_october)
class MonthCalendarTestCase(unittest.TestCase): class MonthCalendarTestCase(unittest.TestCase):

View File

@ -897,8 +897,7 @@ class SafeConfigParserTestCaseTrickyFile(CfgParserTestCaseClass):
self.assertEqual(len(cf.get('corruption', 'value').split('\n')), 10) self.assertEqual(len(cf.get('corruption', 'value').split('\n')), 10)
longname = 'yeah, sections can be indented as well' longname = 'yeah, sections can be indented as well'
self.assertFalse(cf.getboolean(longname, 'are they subsections')) self.assertFalse(cf.getboolean(longname, 'are they subsections'))
self.assertEquals(cf.get(longname, 'lets use some Unicode'), self.assertEqual(cf.get(longname, 'lets use some Unicode'), '片仮名')
'片仮名')
self.assertEqual(len(cf.items('another one!')), 5) # 4 in section and self.assertEqual(len(cf.items('another one!')), 5) # 4 in section and
# `go` from DEFAULT # `go` from DEFAULT
with self.assertRaises(configparser.InterpolationMissingOptionError): with self.assertRaises(configparser.InterpolationMissingOptionError):
@ -955,14 +954,14 @@ class SortedTestCase(RawConfigParserTestCase):
"k=v\n") "k=v\n")
output = io.StringIO() output = io.StringIO()
cf.write(output) cf.write(output)
self.assertEquals(output.getvalue(), self.assertEqual(output.getvalue(),
"[a]\n" "[a]\n"
"k = v\n\n" "k = v\n\n"
"[b]\n" "[b]\n"
"o1 = 4\n" "o1 = 4\n"
"o2 = 3\n" "o2 = 3\n"
"o3 = 2\n" "o3 = 2\n"
"o4 = 1\n\n") "o4 = 1\n\n")
class CompatibleTestCase(CfgParserTestCaseClass): class CompatibleTestCase(CfgParserTestCaseClass):

View File

@ -217,7 +217,7 @@ Content-Disposition: form-data; name="submit"
-----------------------------721837373350705526688164684-- -----------------------------721837373350705526688164684--
""" """
fs = cgi.FieldStorage(fp=StringIO(postdata), environ=env) fs = cgi.FieldStorage(fp=StringIO(postdata), environ=env)
self.assertEquals(len(fs.list), 4) self.assertEqual(len(fs.list), 4)
expect = [{'name':'id', 'filename':None, 'value':'1234'}, expect = [{'name':'id', 'filename':None, 'value':'1234'},
{'name':'title', 'filename':None, 'value':''}, {'name':'title', 'filename':None, 'value':''},
{'name':'file', 'filename':'test.txt', 'value':'Testing 123.'}, {'name':'file', 'filename':'test.txt', 'value':'Testing 123.'},
@ -225,7 +225,7 @@ Content-Disposition: form-data; name="submit"
for x in range(len(fs.list)): for x in range(len(fs.list)):
for k, exp in expect[x].items(): for k, exp in expect[x].items():
got = getattr(fs.list[x], k) got = getattr(fs.list[x], k)
self.assertEquals(got, exp) self.assertEqual(got, exp)
_qs_result = { _qs_result = {
'key1': 'value1', 'key1': 'value1',

View File

@ -27,24 +27,24 @@ codecname = 'testcodec'
class CharmapCodecTest(unittest.TestCase): class CharmapCodecTest(unittest.TestCase):
def test_constructorx(self): def test_constructorx(self):
self.assertEquals(str(b'abc', codecname), 'abc') self.assertEqual(str(b'abc', codecname), 'abc')
self.assertEquals(str(b'xdef', codecname), 'abcdef') self.assertEqual(str(b'xdef', codecname), 'abcdef')
self.assertEquals(str(b'defx', codecname), 'defabc') self.assertEqual(str(b'defx', codecname), 'defabc')
self.assertEquals(str(b'dxf', codecname), 'dabcf') self.assertEqual(str(b'dxf', codecname), 'dabcf')
self.assertEquals(str(b'dxfx', codecname), 'dabcfabc') self.assertEqual(str(b'dxfx', codecname), 'dabcfabc')
def test_encodex(self): def test_encodex(self):
self.assertEquals('abc'.encode(codecname), b'abc') self.assertEqual('abc'.encode(codecname), b'abc')
self.assertEquals('xdef'.encode(codecname), b'abcdef') self.assertEqual('xdef'.encode(codecname), b'abcdef')
self.assertEquals('defx'.encode(codecname), b'defabc') self.assertEqual('defx'.encode(codecname), b'defabc')
self.assertEquals('dxf'.encode(codecname), b'dabcf') self.assertEqual('dxf'.encode(codecname), b'dabcf')
self.assertEquals('dxfx'.encode(codecname), b'dabcfabc') self.assertEqual('dxfx'.encode(codecname), b'dabcfabc')
def test_constructory(self): def test_constructory(self):
self.assertEquals(str(b'ydef', codecname), 'def') self.assertEqual(str(b'ydef', codecname), 'def')
self.assertEquals(str(b'defy', codecname), 'def') self.assertEqual(str(b'defy', codecname), 'def')
self.assertEquals(str(b'dyf', codecname), 'df') self.assertEqual(str(b'dyf', codecname), 'df')
self.assertEquals(str(b'dyfy', codecname), 'df') self.assertEqual(str(b'dyfy', codecname), 'df')
def test_maptoundefined(self): def test_maptoundefined(self):
self.assertRaises(UnicodeError, str, b'abc\001', codecname) self.assertRaises(UnicodeError, str, b'abc\001', codecname)

View File

@ -436,7 +436,7 @@ class ClassTests(unittest.TestCase):
del testme del testme
import gc import gc
gc.collect() gc.collect()
self.assertEquals(["crab people, crab people"], x) self.assertEqual(["crab people, crab people"], x)
def testBadTypeReturned(self): def testBadTypeReturned(self):
# return values of some method are type-checked # return values of some method are type-checked
@ -529,17 +529,17 @@ class ClassTests(unittest.TestCase):
a1 = A(1) a1 = A(1)
a2 = A(2) a2 = A(2)
self.assertEquals(a1.f, a1.f) self.assertEqual(a1.f, a1.f)
self.assertNotEquals(a1.f, a2.f) self.assertNotEqual(a1.f, a2.f)
self.assertNotEquals(a1.f, a1.g) self.assertNotEqual(a1.f, a1.g)
self.assertEquals(a1.f, A(1).f) self.assertEqual(a1.f, A(1).f)
self.assertEquals(hash(a1.f), hash(a1.f)) self.assertEqual(hash(a1.f), hash(a1.f))
self.assertEquals(hash(a1.f), hash(A(1).f)) self.assertEqual(hash(a1.f), hash(A(1).f))
self.assertNotEquals(A.f, a1.f) self.assertNotEqual(A.f, a1.f)
self.assertNotEquals(A.f, A.g) self.assertNotEqual(A.f, A.g)
self.assertEquals(B.f, A.f) self.assertEqual(B.f, A.f)
self.assertEquals(hash(B.f), hash(A.f)) self.assertEqual(hash(B.f), hash(A.f))
# the following triggers a SystemError in 2.4 # the following triggers a SystemError in 2.4
a = A(hash(A.f)^(-1)) a = A(hash(A.f)^(-1))

View File

@ -128,9 +128,9 @@ class CodeTest(unittest.TestCase):
def test_newempty(self): def test_newempty(self):
co = _testcapi.code_newempty("filename", "funcname", 15) co = _testcapi.code_newempty("filename", "funcname", 15)
self.assertEquals(co.co_filename, "filename") self.assertEqual(co.co_filename, "filename")
self.assertEquals(co.co_name, "funcname") self.assertEqual(co.co_name, "funcname")
self.assertEquals(co.co_firstlineno, 15) self.assertEqual(co.co_firstlineno, 15)
class CodeWeakRefTest(unittest.TestCase): class CodeWeakRefTest(unittest.TestCase):

View File

@ -186,7 +186,7 @@ class CodecCallbackTest(unittest.TestCase):
charmap = dict((ord(c), bytes(2*c.upper(), 'ascii')) for c in "abcdefgh") charmap = dict((ord(c), bytes(2*c.upper(), 'ascii')) for c in "abcdefgh")
sin = "abc" sin = "abc"
sout = b"AABBCC" sout = b"AABBCC"
self.assertEquals(codecs.charmap_encode(sin, "strict", charmap)[0], sout) self.assertEqual(codecs.charmap_encode(sin, "strict", charmap)[0], sout)
sin = "abcA" sin = "abcA"
self.assertRaises(UnicodeError, codecs.charmap_encode, sin, "strict", charmap) self.assertRaises(UnicodeError, codecs.charmap_encode, sin, "strict", charmap)
@ -194,7 +194,7 @@ class CodecCallbackTest(unittest.TestCase):
charmap[ord("?")] = b"XYZ" charmap[ord("?")] = b"XYZ"
sin = "abcDEF" sin = "abcDEF"
sout = b"AABBCCXYZXYZXYZ" sout = b"AABBCCXYZXYZXYZ"
self.assertEquals(codecs.charmap_encode(sin, "replace", charmap)[0], sout) self.assertEqual(codecs.charmap_encode(sin, "replace", charmap)[0], sout)
charmap[ord("?")] = "XYZ" # wrong type in mapping charmap[ord("?")] = "XYZ" # wrong type in mapping
self.assertRaises(TypeError, codecs.charmap_encode, sin, "replace", charmap) self.assertRaises(TypeError, codecs.charmap_encode, sin, "replace", charmap)
@ -327,7 +327,7 @@ class CodecCallbackTest(unittest.TestCase):
# check with the correct number and type of arguments # check with the correct number and type of arguments
exc = exctype(*args) exc = exctype(*args)
self.assertEquals(str(exc), msg) self.assertEqual(str(exc), msg)
def test_unicodeencodeerror(self): def test_unicodeencodeerror(self):
self.check_exceptionobjectargs( self.check_exceptionobjectargs(
@ -437,17 +437,17 @@ class CodecCallbackTest(unittest.TestCase):
UnicodeError("ouch") UnicodeError("ouch")
) )
# If the correct exception is passed in, "ignore" returns an empty replacement # If the correct exception is passed in, "ignore" returns an empty replacement
self.assertEquals( self.assertEqual(
codecs.ignore_errors( codecs.ignore_errors(
UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")), UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")),
("", 1) ("", 1)
) )
self.assertEquals( self.assertEqual(
codecs.ignore_errors( codecs.ignore_errors(
UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")), UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")),
("", 1) ("", 1)
) )
self.assertEquals( self.assertEqual(
codecs.ignore_errors( codecs.ignore_errors(
UnicodeTranslateError("\u3042", 0, 1, "ouch")), UnicodeTranslateError("\u3042", 0, 1, "ouch")),
("", 1) ("", 1)
@ -477,17 +477,17 @@ class CodecCallbackTest(unittest.TestCase):
BadObjectUnicodeDecodeError() BadObjectUnicodeDecodeError()
) )
# With the correct exception, "replace" returns an "?" or "\ufffd" replacement # With the correct exception, "replace" returns an "?" or "\ufffd" replacement
self.assertEquals( self.assertEqual(
codecs.replace_errors( codecs.replace_errors(
UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")), UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")),
("?", 1) ("?", 1)
) )
self.assertEquals( self.assertEqual(
codecs.replace_errors( codecs.replace_errors(
UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")), UnicodeDecodeError("ascii", bytearray(b"\xff"), 0, 1, "ouch")),
("\ufffd", 1) ("\ufffd", 1)
) )
self.assertEquals( self.assertEqual(
codecs.replace_errors( codecs.replace_errors(
UnicodeTranslateError("\u3042", 0, 1, "ouch")), UnicodeTranslateError("\u3042", 0, 1, "ouch")),
("\ufffd", 1) ("\ufffd", 1)
@ -520,7 +520,7 @@ class CodecCallbackTest(unittest.TestCase):
# Use the correct exception # Use the correct exception
cs = (0, 1, 9, 10, 99, 100, 999, 1000, 9999, 10000, 0x3042) cs = (0, 1, 9, 10, 99, 100, 999, 1000, 9999, 10000, 0x3042)
s = "".join(chr(c) for c in cs) s = "".join(chr(c) for c in cs)
self.assertEquals( self.assertEqual(
codecs.xmlcharrefreplace_errors( codecs.xmlcharrefreplace_errors(
UnicodeEncodeError("ascii", s, 0, len(s), "ouch") UnicodeEncodeError("ascii", s, 0, len(s), "ouch")
), ),
@ -552,52 +552,52 @@ class CodecCallbackTest(unittest.TestCase):
UnicodeTranslateError("\u3042", 0, 1, "ouch") UnicodeTranslateError("\u3042", 0, 1, "ouch")
) )
# Use the correct exception # Use the correct exception
self.assertEquals( self.assertEqual(
codecs.backslashreplace_errors( codecs.backslashreplace_errors(
UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")), UnicodeEncodeError("ascii", "\u3042", 0, 1, "ouch")),
("\\u3042", 1) ("\\u3042", 1)
) )
self.assertEquals( self.assertEqual(
codecs.backslashreplace_errors( codecs.backslashreplace_errors(
UnicodeEncodeError("ascii", "\x00", 0, 1, "ouch")), UnicodeEncodeError("ascii", "\x00", 0, 1, "ouch")),
("\\x00", 1) ("\\x00", 1)
) )
self.assertEquals( self.assertEqual(
codecs.backslashreplace_errors( codecs.backslashreplace_errors(
UnicodeEncodeError("ascii", "\xff", 0, 1, "ouch")), UnicodeEncodeError("ascii", "\xff", 0, 1, "ouch")),
("\\xff", 1) ("\\xff", 1)
) )
self.assertEquals( self.assertEqual(
codecs.backslashreplace_errors( codecs.backslashreplace_errors(
UnicodeEncodeError("ascii", "\u0100", 0, 1, "ouch")), UnicodeEncodeError("ascii", "\u0100", 0, 1, "ouch")),
("\\u0100", 1) ("\\u0100", 1)
) )
self.assertEquals( self.assertEqual(
codecs.backslashreplace_errors( codecs.backslashreplace_errors(
UnicodeEncodeError("ascii", "\uffff", 0, 1, "ouch")), UnicodeEncodeError("ascii", "\uffff", 0, 1, "ouch")),
("\\uffff", 1) ("\\uffff", 1)
) )
# 1 on UCS-4 builds, 2 on UCS-2 # 1 on UCS-4 builds, 2 on UCS-2
len_wide = len("\U00010000") len_wide = len("\U00010000")
self.assertEquals( self.assertEqual(
codecs.backslashreplace_errors( codecs.backslashreplace_errors(
UnicodeEncodeError("ascii", "\U00010000", UnicodeEncodeError("ascii", "\U00010000",
0, len_wide, "ouch")), 0, len_wide, "ouch")),
("\\U00010000", len_wide) ("\\U00010000", len_wide)
) )
self.assertEquals( self.assertEqual(
codecs.backslashreplace_errors( codecs.backslashreplace_errors(
UnicodeEncodeError("ascii", "\U0010ffff", UnicodeEncodeError("ascii", "\U0010ffff",
0, len_wide, "ouch")), 0, len_wide, "ouch")),
("\\U0010ffff", len_wide) ("\\U0010ffff", len_wide)
) )
# Lone surrogates (regardless of unicode width) # Lone surrogates (regardless of unicode width)
self.assertEquals( self.assertEqual(
codecs.backslashreplace_errors( codecs.backslashreplace_errors(
UnicodeEncodeError("ascii", "\ud800", 0, 1, "ouch")), UnicodeEncodeError("ascii", "\ud800", 0, 1, "ouch")),
("\\ud800", 1) ("\\ud800", 1)
) )
self.assertEquals( self.assertEqual(
codecs.backslashreplace_errors( codecs.backslashreplace_errors(
UnicodeEncodeError("ascii", "\udfff", 0, 1, "ouch")), UnicodeEncodeError("ascii", "\udfff", 0, 1, "ouch")),
("\\udfff", 1) ("\\udfff", 1)
@ -630,14 +630,14 @@ class CodecCallbackTest(unittest.TestCase):
) )
def test_lookup(self): def test_lookup(self):
self.assertEquals(codecs.strict_errors, codecs.lookup_error("strict")) self.assertEqual(codecs.strict_errors, codecs.lookup_error("strict"))
self.assertEquals(codecs.ignore_errors, codecs.lookup_error("ignore")) self.assertEqual(codecs.ignore_errors, codecs.lookup_error("ignore"))
self.assertEquals(codecs.strict_errors, codecs.lookup_error("strict")) self.assertEqual(codecs.strict_errors, codecs.lookup_error("strict"))
self.assertEquals( self.assertEqual(
codecs.xmlcharrefreplace_errors, codecs.xmlcharrefreplace_errors,
codecs.lookup_error("xmlcharrefreplace") codecs.lookup_error("xmlcharrefreplace")
) )
self.assertEquals( self.assertEqual(
codecs.backslashreplace_errors, codecs.backslashreplace_errors,
codecs.lookup_error("backslashreplace") codecs.lookup_error("backslashreplace")
) )
@ -713,11 +713,11 @@ class CodecCallbackTest(unittest.TestCase):
# Valid negative position # Valid negative position
handler.pos = -1 handler.pos = -1
self.assertEquals(b"\xff0".decode("ascii", "test.posreturn"), "<?>0") self.assertEqual(b"\xff0".decode("ascii", "test.posreturn"), "<?>0")
# Valid negative position # Valid negative position
handler.pos = -2 handler.pos = -2
self.assertEquals(b"\xff0".decode("ascii", "test.posreturn"), "<?><?>") self.assertEqual(b"\xff0".decode("ascii", "test.posreturn"), "<?><?>")
# Negative position out of bounds # Negative position out of bounds
handler.pos = -3 handler.pos = -3
@ -725,11 +725,11 @@ class CodecCallbackTest(unittest.TestCase):
# Valid positive position # Valid positive position
handler.pos = 1 handler.pos = 1
self.assertEquals(b"\xff0".decode("ascii", "test.posreturn"), "<?>0") self.assertEqual(b"\xff0".decode("ascii", "test.posreturn"), "<?>0")
# Largest valid positive position (one beyond end of input) # Largest valid positive position (one beyond end of input)
handler.pos = 2 handler.pos = 2
self.assertEquals(b"\xff0".decode("ascii", "test.posreturn"), "<?>") self.assertEqual(b"\xff0".decode("ascii", "test.posreturn"), "<?>")
# Invalid positive position # Invalid positive position
handler.pos = 3 handler.pos = 3
@ -737,7 +737,7 @@ class CodecCallbackTest(unittest.TestCase):
# Restart at the "0" # Restart at the "0"
handler.pos = 6 handler.pos = 6
self.assertEquals(b"\\uyyyy0".decode("raw-unicode-escape", "test.posreturn"), "<?>0") self.assertEqual(b"\\uyyyy0".decode("raw-unicode-escape", "test.posreturn"), "<?>0")
class D(dict): class D(dict):
def __getitem__(self, key): def __getitem__(self, key):
@ -767,11 +767,11 @@ class CodecCallbackTest(unittest.TestCase):
# Valid negative position # Valid negative position
handler.pos = -1 handler.pos = -1
self.assertEquals("\xff0".encode("ascii", "test.posreturn"), b"<?>0") self.assertEqual("\xff0".encode("ascii", "test.posreturn"), b"<?>0")
# Valid negative position # Valid negative position
handler.pos = -2 handler.pos = -2
self.assertEquals("\xff0".encode("ascii", "test.posreturn"), b"<?><?>") self.assertEqual("\xff0".encode("ascii", "test.posreturn"), b"<?><?>")
# Negative position out of bounds # Negative position out of bounds
handler.pos = -3 handler.pos = -3
@ -779,11 +779,11 @@ class CodecCallbackTest(unittest.TestCase):
# Valid positive position # Valid positive position
handler.pos = 1 handler.pos = 1
self.assertEquals("\xff0".encode("ascii", "test.posreturn"), b"<?>0") self.assertEqual("\xff0".encode("ascii", "test.posreturn"), b"<?>0")
# Largest valid positive position (one beyond end of input # Largest valid positive position (one beyond end of input
handler.pos = 2 handler.pos = 2
self.assertEquals("\xff0".encode("ascii", "test.posreturn"), b"<?>") self.assertEqual("\xff0".encode("ascii", "test.posreturn"), b"<?>")
# Invalid positive position # Invalid positive position
handler.pos = 3 handler.pos = 3

View File

@ -299,7 +299,7 @@ class UTF32Test(ReadTest):
# try to read it back # try to read it back
s = io.BytesIO(d) s = io.BytesIO(d)
f = reader(s) f = reader(s)
self.assertEquals(f.read(), "spamspam") self.assertEqual(f.read(), "spamspam")
def test_badbom(self): def test_badbom(self):
s = io.BytesIO(4*b"\xff") s = io.BytesIO(4*b"\xff")
@ -463,7 +463,7 @@ class UTF16Test(ReadTest):
# try to read it back # try to read it back
s = io.BytesIO(d) s = io.BytesIO(d)
f = reader(s) f = reader(s)
self.assertEquals(f.read(), "spamspam") self.assertEqual(f.read(), "spamspam")
def test_badbom(self): def test_badbom(self):
s = io.BytesIO(b"\xff\xff") s = io.BytesIO(b"\xff\xff")
@ -607,10 +607,10 @@ class UTF8Test(ReadTest):
b'[?]') b'[?]')
def test_surrogatepass_handler(self): def test_surrogatepass_handler(self):
self.assertEquals("abc\ud800def".encode("utf-8", "surrogatepass"), self.assertEqual("abc\ud800def".encode("utf-8", "surrogatepass"),
b"abc\xed\xa0\x80def") b"abc\xed\xa0\x80def")
self.assertEquals(b"abc\xed\xa0\x80def".decode("utf-8", "surrogatepass"), self.assertEqual(b"abc\xed\xa0\x80def".decode("utf-8", "surrogatepass"),
"abc\ud800def") "abc\ud800def")
self.assertTrue(codecs.lookup_error("surrogatepass")) self.assertTrue(codecs.lookup_error("surrogatepass"))
class UTF7Test(ReadTest): class UTF7Test(ReadTest):
@ -681,7 +681,7 @@ class UTF8SigTest(ReadTest):
def test_bug1601501(self): def test_bug1601501(self):
# SF bug #1601501: check that the codec works with a buffer # SF bug #1601501: check that the codec works with a buffer
self.assertEquals(str(b"\xef\xbb\xbf", "utf-8-sig"), "") self.assertEqual(str(b"\xef\xbb\xbf", "utf-8-sig"), "")
def test_bom(self): def test_bom(self):
d = codecs.getincrementaldecoder("utf-8-sig")() d = codecs.getincrementaldecoder("utf-8-sig")()
@ -734,7 +734,7 @@ class UTF8SigTest(ReadTest):
class EscapeDecodeTest(unittest.TestCase): class EscapeDecodeTest(unittest.TestCase):
def test_empty(self): def test_empty(self):
self.assertEquals(codecs.escape_decode(""), ("", 0)) self.assertEqual(codecs.escape_decode(""), ("", 0))
class RecodingTest(unittest.TestCase): class RecodingTest(unittest.TestCase):
def test_recoding(self): def test_recoding(self):
@ -861,16 +861,16 @@ class PunycodeTest(unittest.TestCase):
# code produces only lower case. Converting just puny to # code produces only lower case. Converting just puny to
# lower is also insufficient, since some of the input characters # lower is also insufficient, since some of the input characters
# are upper case. # are upper case.
self.assertEquals( self.assertEqual(
str(uni.encode("punycode"), "ascii").lower(), str(uni.encode("punycode"), "ascii").lower(),
str(puny, "ascii").lower() str(puny, "ascii").lower()
) )
def test_decode(self): def test_decode(self):
for uni, puny in punycode_testcases: for uni, puny in punycode_testcases:
self.assertEquals(uni, puny.decode("punycode")) self.assertEqual(uni, puny.decode("punycode"))
puny = puny.decode("ascii").encode("ascii") puny = puny.decode("ascii").encode("ascii")
self.assertEquals(uni, puny.decode("punycode")) self.assertEqual(uni, puny.decode("punycode"))
class UnicodeInternalTest(unittest.TestCase): class UnicodeInternalTest(unittest.TestCase):
def test_bug1251300(self): def test_bug1251300(self):
@ -892,7 +892,7 @@ class UnicodeInternalTest(unittest.TestCase):
for internal, uni in ok: for internal, uni in ok:
if sys.byteorder == "little": if sys.byteorder == "little":
internal = bytes(reversed(internal)) internal = bytes(reversed(internal))
self.assertEquals(uni, internal.decode("unicode_internal")) self.assertEqual(uni, internal.decode("unicode_internal"))
for internal in not_ok: for internal in not_ok:
if sys.byteorder == "little": if sys.byteorder == "little":
internal = bytes(reversed(internal)) internal = bytes(reversed(internal))
@ -904,10 +904,10 @@ class UnicodeInternalTest(unittest.TestCase):
try: try:
b"\x00\x00\x00\x00\x00\x11\x11\x00".decode("unicode_internal") b"\x00\x00\x00\x00\x00\x11\x11\x00".decode("unicode_internal")
except UnicodeDecodeError as ex: except UnicodeDecodeError as ex:
self.assertEquals("unicode_internal", ex.encoding) self.assertEqual("unicode_internal", ex.encoding)
self.assertEquals(b"\x00\x00\x00\x00\x00\x11\x11\x00", ex.object) self.assertEqual(b"\x00\x00\x00\x00\x00\x11\x11\x00", ex.object)
self.assertEquals(4, ex.start) self.assertEqual(4, ex.start)
self.assertEquals(8, ex.end) self.assertEqual(8, ex.end)
else: else:
self.fail() self.fail()
@ -919,15 +919,15 @@ class UnicodeInternalTest(unittest.TestCase):
ignored = decoder(bytes("%s\x22\x22\x22\x22%s" % (ab[:4], ab[4:]), ignored = decoder(bytes("%s\x22\x22\x22\x22%s" % (ab[:4], ab[4:]),
"ascii"), "ascii"),
"UnicodeInternalTest") "UnicodeInternalTest")
self.assertEquals(("ab", 12), ignored) self.assertEqual(("ab", 12), ignored)
def test_encode_length(self): def test_encode_length(self):
# Issue 3739 # Issue 3739
encoder = codecs.getencoder("unicode_internal") encoder = codecs.getencoder("unicode_internal")
self.assertEquals(encoder("a")[1], 1) self.assertEqual(encoder("a")[1], 1)
self.assertEquals(encoder("\xe9\u0142")[1], 2) self.assertEqual(encoder("\xe9\u0142")[1], 2)
self.assertEquals(codecs.escape_encode(br'\x00')[1], 4) self.assertEqual(codecs.escape_encode(br'\x00')[1], 4)
# From http://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html # From http://www.gnu.org/software/libidn/draft-josefsson-idn-test-vectors.html
nameprep_tests = [ nameprep_tests = [
@ -1098,101 +1098,101 @@ class NameprepTest(unittest.TestCase):
else: else:
prepped = str(prepped, "utf-8", "surrogatepass") prepped = str(prepped, "utf-8", "surrogatepass")
try: try:
self.assertEquals(nameprep(orig), prepped) self.assertEqual(nameprep(orig), prepped)
except Exception as e: except Exception as e:
raise support.TestFailed("Test 3.%d: %s" % (pos+1, str(e))) raise support.TestFailed("Test 3.%d: %s" % (pos+1, str(e)))
class IDNACodecTest(unittest.TestCase): class IDNACodecTest(unittest.TestCase):
def test_builtin_decode(self): def test_builtin_decode(self):
self.assertEquals(str(b"python.org", "idna"), "python.org") self.assertEqual(str(b"python.org", "idna"), "python.org")
self.assertEquals(str(b"python.org.", "idna"), "python.org.") self.assertEqual(str(b"python.org.", "idna"), "python.org.")
self.assertEquals(str(b"xn--pythn-mua.org", "idna"), "pyth\xf6n.org") self.assertEqual(str(b"xn--pythn-mua.org", "idna"), "pyth\xf6n.org")
self.assertEquals(str(b"xn--pythn-mua.org.", "idna"), "pyth\xf6n.org.") self.assertEqual(str(b"xn--pythn-mua.org.", "idna"), "pyth\xf6n.org.")
def test_builtin_encode(self): def test_builtin_encode(self):
self.assertEquals("python.org".encode("idna"), b"python.org") self.assertEqual("python.org".encode("idna"), b"python.org")
self.assertEquals("python.org.".encode("idna"), b"python.org.") self.assertEqual("python.org.".encode("idna"), b"python.org.")
self.assertEquals("pyth\xf6n.org".encode("idna"), b"xn--pythn-mua.org") self.assertEqual("pyth\xf6n.org".encode("idna"), b"xn--pythn-mua.org")
self.assertEquals("pyth\xf6n.org.".encode("idna"), b"xn--pythn-mua.org.") self.assertEqual("pyth\xf6n.org.".encode("idna"), b"xn--pythn-mua.org.")
def test_stream(self): def test_stream(self):
r = codecs.getreader("idna")(io.BytesIO(b"abc")) r = codecs.getreader("idna")(io.BytesIO(b"abc"))
r.read(3) r.read(3)
self.assertEquals(r.read(), "") self.assertEqual(r.read(), "")
def test_incremental_decode(self): def test_incremental_decode(self):
self.assertEquals( self.assertEqual(
"".join(codecs.iterdecode((bytes([c]) for c in b"python.org"), "idna")), "".join(codecs.iterdecode((bytes([c]) for c in b"python.org"), "idna")),
"python.org" "python.org"
) )
self.assertEquals( self.assertEqual(
"".join(codecs.iterdecode((bytes([c]) for c in b"python.org."), "idna")), "".join(codecs.iterdecode((bytes([c]) for c in b"python.org."), "idna")),
"python.org." "python.org."
) )
self.assertEquals( self.assertEqual(
"".join(codecs.iterdecode((bytes([c]) for c in b"xn--pythn-mua.org."), "idna")), "".join(codecs.iterdecode((bytes([c]) for c in b"xn--pythn-mua.org."), "idna")),
"pyth\xf6n.org." "pyth\xf6n.org."
) )
self.assertEquals( self.assertEqual(
"".join(codecs.iterdecode((bytes([c]) for c in b"xn--pythn-mua.org."), "idna")), "".join(codecs.iterdecode((bytes([c]) for c in b"xn--pythn-mua.org."), "idna")),
"pyth\xf6n.org." "pyth\xf6n.org."
) )
decoder = codecs.getincrementaldecoder("idna")() decoder = codecs.getincrementaldecoder("idna")()
self.assertEquals(decoder.decode(b"xn--xam", ), "") self.assertEqual(decoder.decode(b"xn--xam", ), "")
self.assertEquals(decoder.decode(b"ple-9ta.o", ), "\xe4xample.") self.assertEqual(decoder.decode(b"ple-9ta.o", ), "\xe4xample.")
self.assertEquals(decoder.decode(b"rg"), "") self.assertEqual(decoder.decode(b"rg"), "")
self.assertEquals(decoder.decode(b"", True), "org") self.assertEqual(decoder.decode(b"", True), "org")
decoder.reset() decoder.reset()
self.assertEquals(decoder.decode(b"xn--xam", ), "") self.assertEqual(decoder.decode(b"xn--xam", ), "")
self.assertEquals(decoder.decode(b"ple-9ta.o", ), "\xe4xample.") self.assertEqual(decoder.decode(b"ple-9ta.o", ), "\xe4xample.")
self.assertEquals(decoder.decode(b"rg."), "org.") self.assertEqual(decoder.decode(b"rg."), "org.")
self.assertEquals(decoder.decode(b"", True), "") self.assertEqual(decoder.decode(b"", True), "")
def test_incremental_encode(self): def test_incremental_encode(self):
self.assertEquals( self.assertEqual(
b"".join(codecs.iterencode("python.org", "idna")), b"".join(codecs.iterencode("python.org", "idna")),
b"python.org" b"python.org"
) )
self.assertEquals( self.assertEqual(
b"".join(codecs.iterencode("python.org.", "idna")), b"".join(codecs.iterencode("python.org.", "idna")),
b"python.org." b"python.org."
) )
self.assertEquals( self.assertEqual(
b"".join(codecs.iterencode("pyth\xf6n.org.", "idna")), b"".join(codecs.iterencode("pyth\xf6n.org.", "idna")),
b"xn--pythn-mua.org." b"xn--pythn-mua.org."
) )
self.assertEquals( self.assertEqual(
b"".join(codecs.iterencode("pyth\xf6n.org.", "idna")), b"".join(codecs.iterencode("pyth\xf6n.org.", "idna")),
b"xn--pythn-mua.org." b"xn--pythn-mua.org."
) )
encoder = codecs.getincrementalencoder("idna")() encoder = codecs.getincrementalencoder("idna")()
self.assertEquals(encoder.encode("\xe4x"), b"") self.assertEqual(encoder.encode("\xe4x"), b"")
self.assertEquals(encoder.encode("ample.org"), b"xn--xample-9ta.") self.assertEqual(encoder.encode("ample.org"), b"xn--xample-9ta.")
self.assertEquals(encoder.encode("", True), b"org") self.assertEqual(encoder.encode("", True), b"org")
encoder.reset() encoder.reset()
self.assertEquals(encoder.encode("\xe4x"), b"") self.assertEqual(encoder.encode("\xe4x"), b"")
self.assertEquals(encoder.encode("ample.org."), b"xn--xample-9ta.org.") self.assertEqual(encoder.encode("ample.org."), b"xn--xample-9ta.org.")
self.assertEquals(encoder.encode("", True), b"") self.assertEqual(encoder.encode("", True), b"")
class CodecsModuleTest(unittest.TestCase): class CodecsModuleTest(unittest.TestCase):
def test_decode(self): def test_decode(self):
self.assertEquals(codecs.decode(b'\xe4\xf6\xfc', 'latin-1'), self.assertEqual(codecs.decode(b'\xe4\xf6\xfc', 'latin-1'),
'\xe4\xf6\xfc') '\xe4\xf6\xfc')
self.assertRaises(TypeError, codecs.decode) self.assertRaises(TypeError, codecs.decode)
self.assertEquals(codecs.decode(b'abc'), 'abc') self.assertEqual(codecs.decode(b'abc'), 'abc')
self.assertRaises(UnicodeDecodeError, codecs.decode, b'\xff', 'ascii') self.assertRaises(UnicodeDecodeError, codecs.decode, b'\xff', 'ascii')
def test_encode(self): def test_encode(self):
self.assertEquals(codecs.encode('\xe4\xf6\xfc', 'latin-1'), self.assertEqual(codecs.encode('\xe4\xf6\xfc', 'latin-1'),
b'\xe4\xf6\xfc') b'\xe4\xf6\xfc')
self.assertRaises(TypeError, codecs.encode) self.assertRaises(TypeError, codecs.encode)
self.assertRaises(LookupError, codecs.encode, "foo", "__spam__") self.assertRaises(LookupError, codecs.encode, "foo", "__spam__")
self.assertEquals(codecs.encode('abc'), b'abc') self.assertEqual(codecs.encode('abc'), b'abc')
self.assertRaises(UnicodeEncodeError, codecs.encode, '\xffff', 'ascii') self.assertRaises(UnicodeEncodeError, codecs.encode, '\xffff', 'ascii')
def test_register(self): def test_register(self):
@ -1228,19 +1228,19 @@ class StreamReaderTest(unittest.TestCase):
def test_readlines(self): def test_readlines(self):
f = self.reader(self.stream) f = self.reader(self.stream)
self.assertEquals(f.readlines(), ['\ud55c\n', '\uae00']) self.assertEqual(f.readlines(), ['\ud55c\n', '\uae00'])
class EncodedFileTest(unittest.TestCase): class EncodedFileTest(unittest.TestCase):
def test_basic(self): def test_basic(self):
f = io.BytesIO(b'\xed\x95\x9c\n\xea\xb8\x80') f = io.BytesIO(b'\xed\x95\x9c\n\xea\xb8\x80')
ef = codecs.EncodedFile(f, 'utf-16-le', 'utf-8') ef = codecs.EncodedFile(f, 'utf-16-le', 'utf-8')
self.assertEquals(ef.read(), b'\\\xd5\n\x00\x00\xae') self.assertEqual(ef.read(), b'\\\xd5\n\x00\x00\xae')
f = io.BytesIO() f = io.BytesIO()
ef = codecs.EncodedFile(f, 'utf-8', 'latin1') ef = codecs.EncodedFile(f, 'utf-8', 'latin1')
ef.write(b'\xc3\xbc') ef.write(b'\xc3\xbc')
self.assertEquals(f.getvalue(), b'\xfc') self.assertEqual(f.getvalue(), b'\xfc')
all_unicode_encodings = [ all_unicode_encodings = [
"ascii", "ascii",
@ -1495,33 +1495,33 @@ class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling):
class CharmapTest(unittest.TestCase): class CharmapTest(unittest.TestCase):
def test_decode_with_string_map(self): def test_decode_with_string_map(self):
self.assertEquals( self.assertEqual(
codecs.charmap_decode(b"\x00\x01\x02", "strict", "abc"), codecs.charmap_decode(b"\x00\x01\x02", "strict", "abc"),
("abc", 3) ("abc", 3)
) )
self.assertEquals( self.assertEqual(
codecs.charmap_decode(b"\x00\x01\x02", "replace", "ab"), codecs.charmap_decode(b"\x00\x01\x02", "replace", "ab"),
("ab\ufffd", 3) ("ab\ufffd", 3)
) )
self.assertEquals( self.assertEqual(
codecs.charmap_decode(b"\x00\x01\x02", "replace", "ab\ufffe"), codecs.charmap_decode(b"\x00\x01\x02", "replace", "ab\ufffe"),
("ab\ufffd", 3) ("ab\ufffd", 3)
) )
self.assertEquals( self.assertEqual(
codecs.charmap_decode(b"\x00\x01\x02", "ignore", "ab"), codecs.charmap_decode(b"\x00\x01\x02", "ignore", "ab"),
("ab", 3) ("ab", 3)
) )
self.assertEquals( self.assertEqual(
codecs.charmap_decode(b"\x00\x01\x02", "ignore", "ab\ufffe"), codecs.charmap_decode(b"\x00\x01\x02", "ignore", "ab\ufffe"),
("ab", 3) ("ab", 3)
) )
allbytes = bytes(range(256)) allbytes = bytes(range(256))
self.assertEquals( self.assertEqual(
codecs.charmap_decode(allbytes, "ignore", ""), codecs.charmap_decode(allbytes, "ignore", ""),
("", len(allbytes)) ("", len(allbytes))
) )
@ -1530,14 +1530,14 @@ class WithStmtTest(unittest.TestCase):
def test_encodedfile(self): def test_encodedfile(self):
f = io.BytesIO(b"\xc3\xbc") f = io.BytesIO(b"\xc3\xbc")
with codecs.EncodedFile(f, "latin-1", "utf-8") as ef: with codecs.EncodedFile(f, "latin-1", "utf-8") as ef:
self.assertEquals(ef.read(), b"\xfc") self.assertEqual(ef.read(), b"\xfc")
def test_streamreaderwriter(self): def test_streamreaderwriter(self):
f = io.BytesIO(b"\xc3\xbc") f = io.BytesIO(b"\xc3\xbc")
info = codecs.lookup("utf-8") info = codecs.lookup("utf-8")
with codecs.StreamReaderWriter(f, info.streamreader, with codecs.StreamReaderWriter(f, info.streamreader,
info.streamwriter, 'strict') as srw: info.streamwriter, 'strict') as srw:
self.assertEquals(srw.read(), "\xfc") self.assertEqual(srw.read(), "\xfc")
class TypesTest(unittest.TestCase): class TypesTest(unittest.TestCase):
def test_decode_unicode(self): def test_decode_unicode(self):
@ -1564,10 +1564,10 @@ class TypesTest(unittest.TestCase):
def test_unicode_escape(self): def test_unicode_escape(self):
# Escape-decoding an unicode string is supported ang gives the same # Escape-decoding an unicode string is supported ang gives the same
# result as decoding the equivalent ASCII bytes string. # result as decoding the equivalent ASCII bytes string.
self.assertEquals(codecs.unicode_escape_decode(r"\u1234"), ("\u1234", 6)) self.assertEqual(codecs.unicode_escape_decode(r"\u1234"), ("\u1234", 6))
self.assertEquals(codecs.unicode_escape_decode(br"\u1234"), ("\u1234", 6)) self.assertEqual(codecs.unicode_escape_decode(br"\u1234"), ("\u1234", 6))
self.assertEquals(codecs.raw_unicode_escape_decode(r"\u1234"), ("\u1234", 6)) self.assertEqual(codecs.raw_unicode_escape_decode(r"\u1234"), ("\u1234", 6))
self.assertEquals(codecs.raw_unicode_escape_decode(br"\u1234"), ("\u1234", 6)) self.assertEqual(codecs.raw_unicode_escape_decode(br"\u1234"), ("\u1234", 6))
class SurrogateEscapeTest(unittest.TestCase): class SurrogateEscapeTest(unittest.TestCase):
@ -1618,27 +1618,27 @@ class BomTest(unittest.TestCase):
f.write(data) f.write(data)
f.write(data) f.write(data)
f.seek(0) f.seek(0)
self.assertEquals(f.read(), data * 2) self.assertEqual(f.read(), data * 2)
f.seek(0) f.seek(0)
self.assertEquals(f.read(), data * 2) self.assertEqual(f.read(), data * 2)
# Check that the BOM is written after a seek(0) # Check that the BOM is written after a seek(0)
with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f:
f.write(data[0]) f.write(data[0])
self.assertNotEquals(f.tell(), 0) self.assertNotEqual(f.tell(), 0)
f.seek(0) f.seek(0)
f.write(data) f.write(data)
f.seek(0) f.seek(0)
self.assertEquals(f.read(), data) self.assertEqual(f.read(), data)
# (StreamWriter) Check that the BOM is written after a seek(0) # (StreamWriter) Check that the BOM is written after a seek(0)
with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f: with codecs.open(support.TESTFN, 'w+', encoding=encoding) as f:
f.writer.write(data[0]) f.writer.write(data[0])
self.assertNotEquals(f.writer.tell(), 0) self.assertNotEqual(f.writer.tell(), 0)
f.writer.seek(0) f.writer.seek(0)
f.writer.write(data) f.writer.write(data)
f.seek(0) f.seek(0)
self.assertEquals(f.read(), data) self.assertEqual(f.read(), data)
# Check that the BOM is not written after a seek() at a position # Check that the BOM is not written after a seek() at a position
# different than the start # different than the start
@ -1647,7 +1647,7 @@ class BomTest(unittest.TestCase):
f.seek(f.tell()) f.seek(f.tell())
f.write(data) f.write(data)
f.seek(0) f.seek(0)
self.assertEquals(f.read(), data * 2) self.assertEqual(f.read(), data * 2)
# (StreamWriter) Check that the BOM is not written after a seek() # (StreamWriter) Check that the BOM is not written after a seek()
# at a position different than the start # at a position different than the start
@ -1656,7 +1656,7 @@ class BomTest(unittest.TestCase):
f.writer.seek(f.writer.tell()) f.writer.seek(f.writer.tell())
f.writer.write(data) f.writer.write(data)
f.seek(0) f.seek(0)
self.assertEquals(f.read(), data * 2) self.assertEqual(f.read(), data * 2)
def test_main(): def test_main():

View File

@ -37,14 +37,14 @@ class CodeopTests(unittest.TestCase):
ctx = {'a': 2} ctx = {'a': 2}
d = { 'value': eval(code,ctx) } d = { 'value': eval(code,ctx) }
r = { 'value': eval(str,ctx) } r = { 'value': eval(str,ctx) }
self.assertEquals(unify_callables(r),unify_callables(d)) self.assertEqual(unify_callables(r),unify_callables(d))
else: else:
expected = compile(str, "<input>", symbol, PyCF_DONT_IMPLY_DEDENT) expected = compile(str, "<input>", symbol, PyCF_DONT_IMPLY_DEDENT)
self.assertEquals( compile_command(str, "<input>", symbol), expected) self.assertEqual(compile_command(str, "<input>", symbol), expected)
def assertIncomplete(self, str, symbol='single'): def assertIncomplete(self, str, symbol='single'):
'''succeed iff str is the start of a valid piece of code''' '''succeed iff str is the start of a valid piece of code'''
self.assertEquals( compile_command(str, symbol=symbol), None) self.assertEqual(compile_command(str, symbol=symbol), None)
def assertInvalid(self, str, symbol='single', is_syntax=1): def assertInvalid(self, str, symbol='single', is_syntax=1):
'''succeed iff str is the start of an invalid piece of code''' '''succeed iff str is the start of an invalid piece of code'''
@ -61,12 +61,12 @@ class CodeopTests(unittest.TestCase):
# special case # special case
if not is_jython: if not is_jython:
self.assertEquals(compile_command(""), self.assertEqual(compile_command(""),
compile("pass", "<input>", 'single', compile("pass", "<input>", 'single',
PyCF_DONT_IMPLY_DEDENT)) PyCF_DONT_IMPLY_DEDENT))
self.assertEquals(compile_command("\n"), self.assertEqual(compile_command("\n"),
compile("pass", "<input>", 'single', compile("pass", "<input>", 'single',
PyCF_DONT_IMPLY_DEDENT)) PyCF_DONT_IMPLY_DEDENT))
else: else:
av("") av("")
av("\n") av("\n")
@ -290,10 +290,10 @@ class CodeopTests(unittest.TestCase):
ai("[i for i in range(10)] = (1, 2, 3)") ai("[i for i in range(10)] = (1, 2, 3)")
def test_filename(self): def test_filename(self):
self.assertEquals(compile_command("a = 1\n", "abc").co_filename, self.assertEqual(compile_command("a = 1\n", "abc").co_filename,
compile("a = 1\n", "abc", 'single').co_filename) compile("a = 1\n", "abc", 'single').co_filename)
self.assertNotEquals(compile_command("a = 1\n", "abc").co_filename, self.assertNotEqual(compile_command("a = 1\n", "abc").co_filename,
compile("a = 1\n", "def", 'single').co_filename) compile("a = 1\n", "def", 'single').co_filename)
def test_main(): def test_main():

View File

@ -701,9 +701,9 @@ class TestCounter(unittest.TestCase):
]): ]):
msg = (i, dup, words) msg = (i, dup, words)
self.assertTrue(dup is not words) self.assertTrue(dup is not words)
self.assertEquals(dup, words) self.assertEqual(dup, words)
self.assertEquals(len(dup), len(words)) self.assertEqual(len(dup), len(words))
self.assertEquals(type(dup), type(words)) self.assertEqual(type(dup), type(words))
def test_conversions(self): def test_conversions(self):
# Convert to: set, list, dict # Convert to: set, list, dict
@ -922,10 +922,10 @@ class TestOrderedDict(unittest.TestCase):
OrderedDict(od), OrderedDict(od),
]): ]):
self.assertTrue(dup is not od) self.assertTrue(dup is not od)
self.assertEquals(dup, od) self.assertEqual(dup, od)
self.assertEquals(list(dup.items()), list(od.items())) self.assertEqual(list(dup.items()), list(od.items()))
self.assertEquals(len(dup), len(od)) self.assertEqual(len(dup), len(od))
self.assertEquals(type(dup), type(od)) self.assertEqual(type(dup), type(od))
def test_yaml_linkage(self): def test_yaml_linkage(self):
# Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature. # Verify that __reduce__ is setup in a way that supports PyYAML's dump() feature.

View File

@ -432,8 +432,8 @@ class ComplexTest(unittest.TestCase):
def test_plus_minus_0j(self): def test_plus_minus_0j(self):
# test that -0j and 0j literals are not identified # test that -0j and 0j literals are not identified
z1, z2 = 0j, -0j z1, z2 = 0j, -0j
self.assertEquals(atan2(z1.imag, -1.), atan2(0., -1.)) self.assertEqual(atan2(z1.imag, -1.), atan2(0., -1.))
self.assertEquals(atan2(z2.imag, -1.), atan2(-0., -1.)) self.assertEqual(atan2(z2.imag, -1.), atan2(-0., -1.))
@unittest.skipUnless(float.__getformat__("double").startswith("IEEE"), @unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
"test requires IEEE 754 doubles") "test requires IEEE 754 doubles")

View File

@ -249,8 +249,8 @@ class WaitTests(unittest.TestCase):
[CANCELLED_FUTURE, future1, future2], [CANCELLED_FUTURE, future1, future2],
return_when=futures.FIRST_COMPLETED) return_when=futures.FIRST_COMPLETED)
self.assertEquals(set([future1]), done) self.assertEqual(set([future1]), done)
self.assertEquals(set([CANCELLED_FUTURE, future2]), not_done) self.assertEqual(set([CANCELLED_FUTURE, future2]), not_done)
finally: finally:
call1.close() call1.close()
call2.close() call2.close()
@ -264,8 +264,8 @@ class WaitTests(unittest.TestCase):
[SUCCESSFUL_FUTURE, future1], [SUCCESSFUL_FUTURE, future1],
return_when=futures.FIRST_COMPLETED) return_when=futures.FIRST_COMPLETED)
self.assertEquals(set([SUCCESSFUL_FUTURE]), finished) self.assertEqual(set([SUCCESSFUL_FUTURE]), finished)
self.assertEquals(set([future1]), pending) self.assertEqual(set([future1]), pending)
finally: finally:
call1.close() call1.close()
@ -290,8 +290,8 @@ class WaitTests(unittest.TestCase):
[future1, future2, future3], [future1, future2, future3],
return_when=futures.FIRST_EXCEPTION) return_when=futures.FIRST_EXCEPTION)
self.assertEquals(set([future1, future2]), finished) self.assertEqual(set([future1, future2]), finished)
self.assertEquals(set([future3]), pending) self.assertEqual(set([future3]), pending)
finally: finally:
call1.close() call1.close()
call2.close() call2.close()
@ -318,10 +318,10 @@ class WaitTests(unittest.TestCase):
future1, future2], future1, future2],
return_when=futures.FIRST_EXCEPTION) return_when=futures.FIRST_EXCEPTION)
self.assertEquals(set([SUCCESSFUL_FUTURE, self.assertEqual(set([SUCCESSFUL_FUTURE,
CANCELLED_AND_NOTIFIED_FUTURE, CANCELLED_AND_NOTIFIED_FUTURE,
future1]), finished) future1]), finished)
self.assertEquals(set([CANCELLED_FUTURE, future2]), pending) self.assertEqual(set([CANCELLED_FUTURE, future2]), pending)
finally: finally:
@ -337,8 +337,8 @@ class WaitTests(unittest.TestCase):
[EXCEPTION_FUTURE, future1], [EXCEPTION_FUTURE, future1],
return_when=futures.FIRST_EXCEPTION) return_when=futures.FIRST_EXCEPTION)
self.assertEquals(set([EXCEPTION_FUTURE]), finished) self.assertEqual(set([EXCEPTION_FUTURE]), finished)
self.assertEquals(set([future1]), pending) self.assertEqual(set([future1]), pending)
finally: finally:
call1.close() call1.close()
@ -361,8 +361,8 @@ class WaitTests(unittest.TestCase):
[future1, future2], [future1, future2],
return_when=futures.ALL_COMPLETED) return_when=futures.ALL_COMPLETED)
self.assertEquals(set([future1, future2]), finished) self.assertEqual(set([future1, future2]), finished)
self.assertEquals(set(), pending) self.assertEqual(set(), pending)
finally: finally:
@ -403,11 +403,11 @@ class WaitTests(unittest.TestCase):
future1, future2, future3, future4], future1, future2, future3, future4],
return_when=futures.ALL_COMPLETED) return_when=futures.ALL_COMPLETED)
self.assertEquals(set([SUCCESSFUL_FUTURE, self.assertEqual(set([SUCCESSFUL_FUTURE,
CANCELLED_AND_NOTIFIED_FUTURE, CANCELLED_AND_NOTIFIED_FUTURE,
future1, future2, future3, future4]), future1, future2, future3, future4]),
finished) finished)
self.assertEquals(set(), pending) self.assertEqual(set(), pending)
finally: finally:
call1.close() call1.close()
call2.close() call2.close()
@ -436,11 +436,11 @@ class WaitTests(unittest.TestCase):
timeout=5, timeout=5,
return_when=futures.ALL_COMPLETED) return_when=futures.ALL_COMPLETED)
self.assertEquals(set([CANCELLED_AND_NOTIFIED_FUTURE, self.assertEqual(set([CANCELLED_AND_NOTIFIED_FUTURE,
EXCEPTION_FUTURE, EXCEPTION_FUTURE,
SUCCESSFUL_FUTURE, SUCCESSFUL_FUTURE,
future1]), finished) future1]), finished)
self.assertEquals(set([future2]), pending) self.assertEqual(set([future2]), pending)
finally: finally:
@ -484,7 +484,7 @@ class AsCompletedTests(unittest.TestCase):
EXCEPTION_FUTURE, EXCEPTION_FUTURE,
SUCCESSFUL_FUTURE, SUCCESSFUL_FUTURE,
future1, future2])) future1, future2]))
self.assertEquals(set( self.assertEqual(set(
[CANCELLED_AND_NOTIFIED_FUTURE, [CANCELLED_AND_NOTIFIED_FUTURE,
EXCEPTION_FUTURE, EXCEPTION_FUTURE,
SUCCESSFUL_FUTURE, SUCCESSFUL_FUTURE,
@ -510,10 +510,10 @@ class AsCompletedTests(unittest.TestCase):
except futures.TimeoutError: except futures.TimeoutError:
pass pass
self.assertEquals(set([CANCELLED_AND_NOTIFIED_FUTURE, self.assertEqual(set([CANCELLED_AND_NOTIFIED_FUTURE,
EXCEPTION_FUTURE, EXCEPTION_FUTURE,
SUCCESSFUL_FUTURE]), SUCCESSFUL_FUTURE]),
completed_futures) completed_futures)
finally: finally:
call1.close() call1.close()
@ -536,11 +536,11 @@ class ExecutorTest(unittest.TestCase):
# ExecutorShutdownTest. # ExecutorShutdownTest.
def test_submit(self): def test_submit(self):
future = self.executor.submit(pow, 2, 8) future = self.executor.submit(pow, 2, 8)
self.assertEquals(256, future.result()) self.assertEqual(256, future.result())
def test_submit_keyword(self): def test_submit_keyword(self):
future = self.executor.submit(mul, 2, y=8) future = self.executor.submit(mul, 2, y=8)
self.assertEquals(16, future.result()) self.assertEqual(16, future.result())
def test_map(self): def test_map(self):
self.assertEqual( self.assertEqual(
@ -569,7 +569,7 @@ class ExecutorTest(unittest.TestCase):
finally: finally:
timeout_call.close() timeout_call.close()
self.assertEquals([42, 42], results) self.assertEqual([42, 42], results)
class ThreadPoolExecutorTest(ExecutorTest): class ThreadPoolExecutorTest(ExecutorTest):
def setUp(self): def setUp(self):
@ -595,7 +595,7 @@ class FutureTests(unittest.TestCase):
f = Future() f = Future()
f.add_done_callback(fn) f.add_done_callback(fn)
f.set_result(5) f.set_result(5)
self.assertEquals(5, callback_result) self.assertEqual(5, callback_result)
def test_done_callback_with_exception(self): def test_done_callback_with_exception(self):
callback_exception = None callback_exception = None
@ -606,7 +606,7 @@ class FutureTests(unittest.TestCase):
f = Future() f = Future()
f.add_done_callback(fn) f.add_done_callback(fn)
f.set_exception(Exception('test')) f.set_exception(Exception('test'))
self.assertEquals(('test',), callback_exception.args) self.assertEqual(('test',), callback_exception.args)
def test_done_callback_with_cancel(self): def test_done_callback_with_cancel(self):
was_cancelled = None was_cancelled = None
@ -657,7 +657,7 @@ class FutureTests(unittest.TestCase):
f = Future() f = Future()
f.set_result(5) f.set_result(5)
f.add_done_callback(fn) f.add_done_callback(fn)
self.assertEquals(5, callback_result) self.assertEqual(5, callback_result)
def test_done_callback_already_failed(self): def test_done_callback_already_failed(self):
callback_exception = None callback_exception = None
@ -668,7 +668,7 @@ class FutureTests(unittest.TestCase):
f = Future() f = Future()
f.set_exception(Exception('test')) f.set_exception(Exception('test'))
f.add_done_callback(fn) f.add_done_callback(fn)
self.assertEquals(('test',), callback_exception.args) self.assertEqual(('test',), callback_exception.args)
def test_done_callback_already_cancelled(self): def test_done_callback_already_cancelled(self):
was_cancelled = None was_cancelled = None
@ -707,22 +707,22 @@ class FutureTests(unittest.TestCase):
f6 = create_future(state=FINISHED, result=5) f6 = create_future(state=FINISHED, result=5)
self.assertTrue(f1.cancel()) self.assertTrue(f1.cancel())
self.assertEquals(f1._state, CANCELLED) self.assertEqual(f1._state, CANCELLED)
self.assertFalse(f2.cancel()) self.assertFalse(f2.cancel())
self.assertEquals(f2._state, RUNNING) self.assertEqual(f2._state, RUNNING)
self.assertTrue(f3.cancel()) self.assertTrue(f3.cancel())
self.assertEquals(f3._state, CANCELLED) self.assertEqual(f3._state, CANCELLED)
self.assertTrue(f4.cancel()) self.assertTrue(f4.cancel())
self.assertEquals(f4._state, CANCELLED_AND_NOTIFIED) self.assertEqual(f4._state, CANCELLED_AND_NOTIFIED)
self.assertFalse(f5.cancel()) self.assertFalse(f5.cancel())
self.assertEquals(f5._state, FINISHED) self.assertEqual(f5._state, FINISHED)
self.assertFalse(f6.cancel()) self.assertFalse(f6.cancel())
self.assertEquals(f6._state, FINISHED) self.assertEqual(f6._state, FINISHED)
def test_cancelled(self): def test_cancelled(self):
self.assertFalse(PENDING_FUTURE.cancelled()) self.assertFalse(PENDING_FUTURE.cancelled())
@ -771,7 +771,7 @@ class FutureTests(unittest.TestCase):
t = threading.Thread(target=notification) t = threading.Thread(target=notification)
t.start() t.start()
self.assertEquals(f1.result(timeout=5), 42) self.assertEqual(f1.result(timeout=5), 42)
def test_result_with_cancel(self): def test_result_with_cancel(self):
# TODO(brian@sweetapp.com): This test is timing dependant. # TODO(brian@sweetapp.com): This test is timing dependant.

View File

@ -40,7 +40,7 @@ class CopyRegTestCase(unittest.TestCase):
def test_bool(self): def test_bool(self):
import copy import copy
self.assertEquals(True, copy.copy(True)) self.assertEqual(True, copy.copy(True))
def test_extension_registry(self): def test_extension_registry(self):
mod, func, code = 'junk1 ', ' junk2', 0xabcd mod, func, code = 'junk1 ', ' junk2', 0xabcd
@ -101,16 +101,16 @@ class CopyRegTestCase(unittest.TestCase):
mod, func, code) mod, func, code)
def test_slotnames(self): def test_slotnames(self):
self.assertEquals(copyreg._slotnames(WithoutSlots), []) self.assertEqual(copyreg._slotnames(WithoutSlots), [])
self.assertEquals(copyreg._slotnames(WithWeakref), []) self.assertEqual(copyreg._slotnames(WithWeakref), [])
expected = ['_WithPrivate__spam'] expected = ['_WithPrivate__spam']
self.assertEquals(copyreg._slotnames(WithPrivate), expected) self.assertEqual(copyreg._slotnames(WithPrivate), expected)
self.assertEquals(copyreg._slotnames(WithSingleString), ['spam']) self.assertEqual(copyreg._slotnames(WithSingleString), ['spam'])
expected = ['eggs', 'spam'] expected = ['eggs', 'spam']
expected.sort() expected.sort()
result = copyreg._slotnames(WithInherited) result = copyreg._slotnames(WithInherited)
result.sort() result.sort()
self.assertEquals(result, expected) self.assertEqual(result, expected)
def test_main(): def test_main():

View File

@ -234,7 +234,7 @@ class TestBasic(unittest.TestCase):
d = deque(data[:i]) d = deque(data[:i])
r = d.reverse() r = d.reverse()
self.assertEqual(list(d), list(reversed(data[:i]))) self.assertEqual(list(d), list(reversed(data[:i])))
self.assert_(r is None) self.assertIs(r, None)
d.reverse() d.reverse()
self.assertEqual(list(d), data[:i]) self.assertEqual(list(d), data[:i])
self.assertRaises(TypeError, d.reverse, 1) # Arity is zero self.assertRaises(TypeError, d.reverse, 1) # Arity is zero

View File

@ -4205,11 +4205,11 @@ order (MRO) for bases """
__getattr__ = descr __getattr__ = descr
self.assertRaises(AttributeError, getattr, A(), "attr") self.assertRaises(AttributeError, getattr, A(), "attr")
self.assertEquals(descr.counter, 1) self.assertEqual(descr.counter, 1)
self.assertRaises(AttributeError, getattr, B(), "attr") self.assertRaises(AttributeError, getattr, B(), "attr")
self.assertEquals(descr.counter, 2) self.assertEqual(descr.counter, 2)
self.assertRaises(AttributeError, getattr, C(), "attr") self.assertRaises(AttributeError, getattr, C(), "attr")
self.assertEquals(descr.counter, 4) self.assertEqual(descr.counter, 4)
import gc import gc
class EvilGetattribute(object): class EvilGetattribute(object):
@ -4236,7 +4236,7 @@ class DictProxyTests(unittest.TestCase):
# Testing dict-proxy iterkeys... # Testing dict-proxy iterkeys...
keys = [ key for key in self.C.__dict__.keys() ] keys = [ key for key in self.C.__dict__.keys() ]
keys.sort() keys.sort()
self.assertEquals(keys, ['__dict__', '__doc__', '__module__', self.assertEqual(keys, ['__dict__', '__doc__', '__module__',
'__weakref__', 'meth']) '__weakref__', 'meth'])
def test_iter_values(self): def test_iter_values(self):

View File

@ -56,7 +56,7 @@ class TestEPoll(unittest.TestCase):
try: try:
client.connect(('127.0.0.1', self.serverSocket.getsockname()[1])) client.connect(('127.0.0.1', self.serverSocket.getsockname()[1]))
except socket.error as e: except socket.error as e:
self.assertEquals(e.args[0], errno.EINPROGRESS) self.assertEqual(e.args[0], errno.EINPROGRESS)
else: else:
raise AssertionError("Connect should have raised EINPROGRESS") raise AssertionError("Connect should have raised EINPROGRESS")
server, addr = self.serverSocket.accept() server, addr = self.serverSocket.accept()
@ -162,7 +162,7 @@ class TestEPoll(unittest.TestCase):
(server.fileno(), select.EPOLLOUT)] (server.fileno(), select.EPOLLOUT)]
expected.sort() expected.sort()
self.assertEquals(events, expected) self.assertEqual(events, expected)
self.assertFalse(then - now > 0.01, then - now) self.assertFalse(then - now > 0.01, then - now)
now = time.time() now = time.time()
@ -183,7 +183,7 @@ class TestEPoll(unittest.TestCase):
(server.fileno(), select.EPOLLIN | select.EPOLLOUT)] (server.fileno(), select.EPOLLIN | select.EPOLLOUT)]
expected.sort() expected.sort()
self.assertEquals(events, expected) self.assertEqual(events, expected)
ep.unregister(client.fileno()) ep.unregister(client.fileno())
ep.modify(server.fileno(), select.EPOLLOUT) ep.modify(server.fileno(), select.EPOLLOUT)
@ -193,7 +193,7 @@ class TestEPoll(unittest.TestCase):
self.assertFalse(then - now > 0.01) self.assertFalse(then - now > 0.01)
expected = [(server.fileno(), select.EPOLLOUT)] expected = [(server.fileno(), select.EPOLLOUT)]
self.assertEquals(events, expected) self.assertEqual(events, expected)
def test_errors(self): def test_errors(self):
self.assertRaises(ValueError, select.epoll, -2) self.assertRaises(ValueError, select.epoll, -2)

View File

@ -22,8 +22,8 @@ class ExceptionTests(unittest.TestCase):
raise exc("spam") raise exc("spam")
except exc as err: except exc as err:
buf2 = str(err) buf2 = str(err)
self.assertEquals(buf1, buf2) self.assertEqual(buf1, buf2)
self.assertEquals(exc.__name__, excname) self.assertEqual(exc.__name__, excname)
def testRaising(self): def testRaising(self):
self.raise_catch(AttributeError, "AttributeError") self.raise_catch(AttributeError, "AttributeError")
@ -156,7 +156,7 @@ class ExceptionTests(unittest.TestCase):
except TypeError as err: except TypeError as err:
exc, err, tb = sys.exc_info() exc, err, tb = sys.exc_info()
co = tb.tb_frame.f_code co = tb.tb_frame.f_code
self.assertEquals(co.co_name, "test_capi1") self.assertEqual(co.co_name, "test_capi1")
self.assertTrue(co.co_filename.endswith('test_exceptions.py')) self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
else: else:
self.fail("Expected exception") self.fail("Expected exception")
@ -168,10 +168,10 @@ class ExceptionTests(unittest.TestCase):
except RuntimeError as err: except RuntimeError as err:
exc, err, tb = sys.exc_info() exc, err, tb = sys.exc_info()
co = tb.tb_frame.f_code co = tb.tb_frame.f_code
self.assertEquals(co.co_name, "__init__") self.assertEqual(co.co_name, "__init__")
self.assertTrue(co.co_filename.endswith('test_exceptions.py')) self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
co2 = tb.tb_frame.f_back.f_code co2 = tb.tb_frame.f_back.f_code
self.assertEquals(co2.co_name, "test_capi2") self.assertEqual(co2.co_name, "test_capi2")
else: else:
self.fail("Expected exception") self.fail("Expected exception")
@ -191,10 +191,9 @@ class ExceptionTests(unittest.TestCase):
except NameError: except NameError:
pass pass
else: else:
self.assertEqual(str(WindowsError(1001)), self.assertEqual(str(WindowsError(1001)), "1001")
"1001")
self.assertEqual(str(WindowsError(1001, "message")), self.assertEqual(str(WindowsError(1001, "message")),
"[Error 1001] message") "[Error 1001] message")
self.assertEqual(WindowsError(1001, "message").errno, 22) self.assertEqual(WindowsError(1001, "message").errno, 22)
self.assertEqual(WindowsError(1001, "message").winerror, 1001) self.assertEqual(WindowsError(1001, "message").winerror, 1001)
@ -291,16 +290,16 @@ class ExceptionTests(unittest.TestCase):
raise raise
else: else:
# Verify module name # Verify module name
self.assertEquals(type(e).__module__, 'builtins') self.assertEqual(type(e).__module__, 'builtins')
# Verify no ref leaks in Exc_str() # Verify no ref leaks in Exc_str()
s = str(e) s = str(e)
for checkArgName in expected: for checkArgName in expected:
value = getattr(e, checkArgName) value = getattr(e, checkArgName)
self.assertEquals(repr(value), self.assertEqual(repr(value),
repr(expected[checkArgName]), repr(expected[checkArgName]),
'%r.%s == %r, expected %r' % ( '%r.%s == %r, expected %r' % (
e, checkArgName, e, checkArgName,
value, expected[checkArgName])) value, expected[checkArgName]))
# test for pickling support # test for pickling support
for p in [pickle]: for p in [pickle]:
@ -310,9 +309,9 @@ class ExceptionTests(unittest.TestCase):
for checkArgName in expected: for checkArgName in expected:
got = repr(getattr(new, checkArgName)) got = repr(getattr(new, checkArgName))
want = repr(expected[checkArgName]) want = repr(expected[checkArgName])
self.assertEquals(got, want, self.assertEqual(got, want,
'pickled "%r", attribute "%s' % 'pickled "%r", attribute "%s' %
(e, checkArgName)) (e, checkArgName))
def testWithTraceback(self): def testWithTraceback(self):
try: try:
@ -387,7 +386,7 @@ class ExceptionTests(unittest.TestCase):
self.fancy_arg = fancy_arg self.fancy_arg = fancy_arg
x = DerivedException(fancy_arg=42) x = DerivedException(fancy_arg=42)
self.assertEquals(x.fancy_arg, 42) self.assertEqual(x.fancy_arg, 42)
def testInfiniteRecursion(self): def testInfiniteRecursion(self):
def f(): def f():
@ -548,24 +547,24 @@ class ExceptionTests(unittest.TestCase):
yield sys.exc_info()[0] yield sys.exc_info()[0]
yield sys.exc_info()[0] yield sys.exc_info()[0]
g = yield_raise() g = yield_raise()
self.assertEquals(next(g), KeyError) self.assertEqual(next(g), KeyError)
self.assertEquals(sys.exc_info()[0], None) self.assertEqual(sys.exc_info()[0], None)
self.assertEquals(next(g), KeyError) self.assertEqual(next(g), KeyError)
self.assertEquals(sys.exc_info()[0], None) self.assertEqual(sys.exc_info()[0], None)
self.assertEquals(next(g), None) self.assertEqual(next(g), None)
# Same test, but inside an exception handler # Same test, but inside an exception handler
try: try:
raise TypeError("foo") raise TypeError("foo")
except TypeError: except TypeError:
g = yield_raise() g = yield_raise()
self.assertEquals(next(g), KeyError) self.assertEqual(next(g), KeyError)
self.assertEquals(sys.exc_info()[0], TypeError) self.assertEqual(sys.exc_info()[0], TypeError)
self.assertEquals(next(g), KeyError) self.assertEqual(next(g), KeyError)
self.assertEquals(sys.exc_info()[0], TypeError) self.assertEqual(sys.exc_info()[0], TypeError)
self.assertEquals(next(g), TypeError) self.assertEqual(next(g), TypeError)
del g del g
self.assertEquals(sys.exc_info()[0], TypeError) self.assertEqual(sys.exc_info()[0], TypeError)
def test_generator_finalizing_and_exc_info(self): def test_generator_finalizing_and_exc_info(self):
# See #7173 # See #7173
@ -593,7 +592,7 @@ class ExceptionTests(unittest.TestCase):
raise Exception(MyObject()) raise Exception(MyObject())
except: except:
pass pass
self.assertEquals(e, (None, None, None)) self.assertEqual(e, (None, None, None))
def testUnicodeChangeAttributes(self): def testUnicodeChangeAttributes(self):
# See issue 7309. This was a crasher. # See issue 7309. This was a crasher.

View File

@ -25,7 +25,7 @@ class AutoFileTests(unittest.TestCase):
# verify weak references # verify weak references
p = proxy(self.f) p = proxy(self.f)
p.write(b'teststring') p.write(b'teststring')
self.assertEquals(self.f.tell(), p.tell()) self.assertEqual(self.f.tell(), p.tell())
self.f.close() self.f.close()
self.f = None self.f = None
self.assertRaises(ReferenceError, getattr, p, 'tell') self.assertRaises(ReferenceError, getattr, p, 'tell')
@ -44,7 +44,7 @@ class AutoFileTests(unittest.TestCase):
a = array('b', b'x'*10) a = array('b', b'x'*10)
self.f = self.open(TESTFN, 'rb') self.f = self.open(TESTFN, 'rb')
n = self.f.readinto(a) n = self.f.readinto(a)
self.assertEquals(b'12', a.tobytes()[:n]) self.assertEqual(b'12', a.tobytes()[:n])
def testReadinto_text(self): def testReadinto_text(self):
# verify readinto refuses text files # verify readinto refuses text files
@ -61,7 +61,7 @@ class AutoFileTests(unittest.TestCase):
self.f.close() self.f.close()
self.f = self.open(TESTFN, 'rb') self.f = self.open(TESTFN, 'rb')
buf = self.f.read() buf = self.f.read()
self.assertEquals(buf, b'12') self.assertEqual(buf, b'12')
def testWritelinesIntegers(self): def testWritelinesIntegers(self):
# verify writelines with integers # verify writelines with integers
@ -82,7 +82,7 @@ class AutoFileTests(unittest.TestCase):
def testErrors(self): def testErrors(self):
f = self.f f = self.f
self.assertEquals(f.name, TESTFN) self.assertEqual(f.name, TESTFN)
self.assertTrue(not f.isatty()) self.assertTrue(not f.isatty())
self.assertTrue(not f.closed) self.assertTrue(not f.closed)
@ -118,12 +118,12 @@ class AutoFileTests(unittest.TestCase):
self.assertRaises(ValueError, method, *args) self.assertRaises(ValueError, method, *args)
# file is closed, __exit__ shouldn't do anything # file is closed, __exit__ shouldn't do anything
self.assertEquals(self.f.__exit__(None, None, None), None) self.assertEqual(self.f.__exit__(None, None, None), None)
# it must also return None if an exception was given # it must also return None if an exception was given
try: try:
1/0 1/0
except: except:
self.assertEquals(self.f.__exit__(*sys.exc_info()), None) self.assertEqual(self.f.__exit__(*sys.exc_info()), None)
def testReadWhenWriting(self): def testReadWhenWriting(self):
self.assertRaises(IOError, self.f.read) self.assertRaises(IOError, self.f.read)
@ -189,7 +189,7 @@ class OtherFileTests(unittest.TestCase):
f.close() f.close()
except IOError as msg: except IOError as msg:
self.fail('error setting buffer size %d: %s' % (s, str(msg))) self.fail('error setting buffer size %d: %s' % (s, str(msg)))
self.assertEquals(d, s) self.assertEqual(d, s)
def testTruncateOnWindows(self): def testTruncateOnWindows(self):
# SF bug <http://www.python.org/sf/801631> # SF bug <http://www.python.org/sf/801631>

View File

@ -27,31 +27,31 @@ class AutoFileTests(unittest.TestCase):
# verify weak references # verify weak references
p = proxy(self.f) p = proxy(self.f)
p.write(bytes(range(10))) p.write(bytes(range(10)))
self.assertEquals(self.f.tell(), p.tell()) self.assertEqual(self.f.tell(), p.tell())
self.f.close() self.f.close()
self.f = None self.f = None
self.assertRaises(ReferenceError, getattr, p, 'tell') self.assertRaises(ReferenceError, getattr, p, 'tell')
def testSeekTell(self): def testSeekTell(self):
self.f.write(bytes(range(20))) self.f.write(bytes(range(20)))
self.assertEquals(self.f.tell(), 20) self.assertEqual(self.f.tell(), 20)
self.f.seek(0) self.f.seek(0)
self.assertEquals(self.f.tell(), 0) self.assertEqual(self.f.tell(), 0)
self.f.seek(10) self.f.seek(10)
self.assertEquals(self.f.tell(), 10) self.assertEqual(self.f.tell(), 10)
self.f.seek(5, 1) self.f.seek(5, 1)
self.assertEquals(self.f.tell(), 15) self.assertEqual(self.f.tell(), 15)
self.f.seek(-5, 1) self.f.seek(-5, 1)
self.assertEquals(self.f.tell(), 10) self.assertEqual(self.f.tell(), 10)
self.f.seek(-5, 2) self.f.seek(-5, 2)
self.assertEquals(self.f.tell(), 15) self.assertEqual(self.f.tell(), 15)
def testAttributes(self): def testAttributes(self):
# verify expected attributes exist # verify expected attributes exist
f = self.f f = self.f
self.assertEquals(f.mode, "wb") self.assertEqual(f.mode, "wb")
self.assertEquals(f.closed, False) self.assertEqual(f.closed, False)
# verify the attributes are readonly # verify the attributes are readonly
for attr in 'mode', 'closed': for attr in 'mode', 'closed':
@ -65,7 +65,7 @@ class AutoFileTests(unittest.TestCase):
a = array('b', b'x'*10) a = array('b', b'x'*10)
self.f = _FileIO(TESTFN, 'r') self.f = _FileIO(TESTFN, 'r')
n = self.f.readinto(a) n = self.f.readinto(a)
self.assertEquals(array('b', [1, 2]), a[:n]) self.assertEqual(array('b', [1, 2]), a[:n])
def test_none_args(self): def test_none_args(self):
self.f.write(b"hi\nbye\nabc") self.f.write(b"hi\nbye\nabc")
@ -80,19 +80,19 @@ class AutoFileTests(unittest.TestCase):
self.assertRaises(TypeError, self.f.write, "Hello!") self.assertRaises(TypeError, self.f.write, "Hello!")
def testRepr(self): def testRepr(self):
self.assertEquals(repr(self.f), "<_io.FileIO name=%r mode=%r>" self.assertEqual(repr(self.f), "<_io.FileIO name=%r mode=%r>"
% (self.f.name, self.f.mode)) % (self.f.name, self.f.mode))
del self.f.name del self.f.name
self.assertEquals(repr(self.f), "<_io.FileIO fd=%r mode=%r>" self.assertEqual(repr(self.f), "<_io.FileIO fd=%r mode=%r>"
% (self.f.fileno(), self.f.mode)) % (self.f.fileno(), self.f.mode))
self.f.close() self.f.close()
self.assertEquals(repr(self.f), "<_io.FileIO [closed]>") self.assertEqual(repr(self.f), "<_io.FileIO [closed]>")
def testErrors(self): def testErrors(self):
f = self.f f = self.f
self.assertTrue(not f.isatty()) self.assertTrue(not f.isatty())
self.assertTrue(not f.closed) self.assertTrue(not f.closed)
#self.assertEquals(f.name, TESTFN) #self.assertEqual(f.name, TESTFN)
self.assertRaises(ValueError, f.read, 10) # Open for reading self.assertRaises(ValueError, f.read, 10) # Open for reading
f.close() f.close()
self.assertTrue(f.closed) self.assertTrue(f.closed)
@ -233,22 +233,22 @@ class OtherFileTests(unittest.TestCase):
def testAbles(self): def testAbles(self):
try: try:
f = _FileIO(TESTFN, "w") f = _FileIO(TESTFN, "w")
self.assertEquals(f.readable(), False) self.assertEqual(f.readable(), False)
self.assertEquals(f.writable(), True) self.assertEqual(f.writable(), True)
self.assertEquals(f.seekable(), True) self.assertEqual(f.seekable(), True)
f.close() f.close()
f = _FileIO(TESTFN, "r") f = _FileIO(TESTFN, "r")
self.assertEquals(f.readable(), True) self.assertEqual(f.readable(), True)
self.assertEquals(f.writable(), False) self.assertEqual(f.writable(), False)
self.assertEquals(f.seekable(), True) self.assertEqual(f.seekable(), True)
f.close() f.close()
f = _FileIO(TESTFN, "a+") f = _FileIO(TESTFN, "a+")
self.assertEquals(f.readable(), True) self.assertEqual(f.readable(), True)
self.assertEquals(f.writable(), True) self.assertEqual(f.writable(), True)
self.assertEquals(f.seekable(), True) self.assertEqual(f.seekable(), True)
self.assertEquals(f.isatty(), False) self.assertEqual(f.isatty(), False)
f.close() f.close()
if sys.platform != "win32": if sys.platform != "win32":
@ -260,14 +260,14 @@ class OtherFileTests(unittest.TestCase):
# OS'es that don't support /dev/tty. # OS'es that don't support /dev/tty.
pass pass
else: else:
self.assertEquals(f.readable(), False) self.assertEqual(f.readable(), False)
self.assertEquals(f.writable(), True) self.assertEqual(f.writable(), True)
if sys.platform != "darwin" and \ if sys.platform != "darwin" and \
'bsd' not in sys.platform and \ 'bsd' not in sys.platform and \
not sys.platform.startswith('sunos'): not sys.platform.startswith('sunos'):
# Somehow /dev/tty appears seekable on some BSDs # Somehow /dev/tty appears seekable on some BSDs
self.assertEquals(f.seekable(), False) self.assertEqual(f.seekable(), False)
self.assertEquals(f.isatty(), True) self.assertEqual(f.isatty(), True)
f.close() f.close()
finally: finally:
os.unlink(TESTFN) os.unlink(TESTFN)
@ -301,7 +301,7 @@ class OtherFileTests(unittest.TestCase):
f.write(b"abc") f.write(b"abc")
f.close() f.close()
with open(TESTFN, "rb") as f: with open(TESTFN, "rb") as f:
self.assertEquals(f.read(), b"abc") self.assertEqual(f.read(), b"abc")
finally: finally:
os.unlink(TESTFN) os.unlink(TESTFN)

View File

@ -554,9 +554,9 @@ class FormatTestCase(unittest.TestCase):
self.assertEqual(fmt % -float(arg), '-' + rhs) self.assertEqual(fmt % -float(arg), '-' + rhs)
def test_issue5864(self): def test_issue5864(self):
self.assertEquals(format(123.456, '.4'), '123.5') self.assertEqual(format(123.456, '.4'), '123.5')
self.assertEquals(format(1234.56, '.4'), '1.235e+03') self.assertEqual(format(1234.56, '.4'), '1.235e+03')
self.assertEquals(format(12345.6, '.4'), '1.235e+04') self.assertEqual(format(12345.6, '.4'), '1.235e+04')
class ReprTestCase(unittest.TestCase): class ReprTestCase(unittest.TestCase):
def test_repr(self): def test_repr(self):

View File

@ -84,16 +84,16 @@ class DummyRational(object):
class GcdTest(unittest.TestCase): class GcdTest(unittest.TestCase):
def testMisc(self): def testMisc(self):
self.assertEquals(0, gcd(0, 0)) self.assertEqual(0, gcd(0, 0))
self.assertEquals(1, gcd(1, 0)) self.assertEqual(1, gcd(1, 0))
self.assertEquals(-1, gcd(-1, 0)) self.assertEqual(-1, gcd(-1, 0))
self.assertEquals(1, gcd(0, 1)) self.assertEqual(1, gcd(0, 1))
self.assertEquals(-1, gcd(0, -1)) self.assertEqual(-1, gcd(0, -1))
self.assertEquals(1, gcd(7, 1)) self.assertEqual(1, gcd(7, 1))
self.assertEquals(-1, gcd(7, -1)) self.assertEqual(-1, gcd(7, -1))
self.assertEquals(1, gcd(-23, 15)) self.assertEqual(1, gcd(-23, 15))
self.assertEquals(12, gcd(120, 84)) self.assertEqual(12, gcd(120, 84))
self.assertEquals(-12, gcd(84, -120)) self.assertEqual(-12, gcd(84, -120))
def _components(r): def _components(r):
@ -104,8 +104,8 @@ class FractionTest(unittest.TestCase):
def assertTypedEquals(self, expected, actual): def assertTypedEquals(self, expected, actual):
"""Asserts that both the types and values are the same.""" """Asserts that both the types and values are the same."""
self.assertEquals(type(expected), type(actual)) self.assertEqual(type(expected), type(actual))
self.assertEquals(expected, actual) self.assertEqual(expected, actual)
def assertRaisesMessage(self, exc_type, message, def assertRaisesMessage(self, exc_type, message,
callable, *args, **kwargs): callable, *args, **kwargs):
@ -113,25 +113,25 @@ class FractionTest(unittest.TestCase):
try: try:
callable(*args, **kwargs) callable(*args, **kwargs)
except exc_type as e: except exc_type as e:
self.assertEquals(message, str(e)) self.assertEqual(message, str(e))
else: else:
self.fail("%s not raised" % exc_type.__name__) self.fail("%s not raised" % exc_type.__name__)
def testInit(self): def testInit(self):
self.assertEquals((0, 1), _components(F())) self.assertEqual((0, 1), _components(F()))
self.assertEquals((7, 1), _components(F(7))) self.assertEqual((7, 1), _components(F(7)))
self.assertEquals((7, 3), _components(F(F(7, 3)))) self.assertEqual((7, 3), _components(F(F(7, 3))))
self.assertEquals((-1, 1), _components(F(-1, 1))) self.assertEqual((-1, 1), _components(F(-1, 1)))
self.assertEquals((-1, 1), _components(F(1, -1))) self.assertEqual((-1, 1), _components(F(1, -1)))
self.assertEquals((1, 1), _components(F(-2, -2))) self.assertEqual((1, 1), _components(F(-2, -2)))
self.assertEquals((1, 2), _components(F(5, 10))) self.assertEqual((1, 2), _components(F(5, 10)))
self.assertEquals((7, 15), _components(F(7, 15))) self.assertEqual((7, 15), _components(F(7, 15)))
self.assertEquals((10**23, 1), _components(F(10**23))) self.assertEqual((10**23, 1), _components(F(10**23)))
self.assertEquals((3, 77), _components(F(F(3, 7), 11))) self.assertEqual((3, 77), _components(F(F(3, 7), 11)))
self.assertEquals((-9, 5), _components(F(2, F(-10, 9)))) self.assertEqual((-9, 5), _components(F(2, F(-10, 9))))
self.assertEquals((2486, 2485), _components(F(F(22, 7), F(355, 113)))) self.assertEqual((2486, 2485), _components(F(F(22, 7), F(355, 113))))
self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)", self.assertRaisesMessage(ZeroDivisionError, "Fraction(12, 0)",
F, 12, 0) F, 12, 0)
@ -143,41 +143,41 @@ class FractionTest(unittest.TestCase):
@requires_IEEE_754 @requires_IEEE_754
def testInitFromFloat(self): def testInitFromFloat(self):
self.assertEquals((5, 2), _components(F(2.5))) self.assertEqual((5, 2), _components(F(2.5)))
self.assertEquals((0, 1), _components(F(-0.0))) self.assertEqual((0, 1), _components(F(-0.0)))
self.assertEquals((3602879701896397, 36028797018963968), self.assertEqual((3602879701896397, 36028797018963968),
_components(F(0.1))) _components(F(0.1)))
self.assertRaises(TypeError, F, float('nan')) self.assertRaises(TypeError, F, float('nan'))
self.assertRaises(TypeError, F, float('inf')) self.assertRaises(TypeError, F, float('inf'))
self.assertRaises(TypeError, F, float('-inf')) self.assertRaises(TypeError, F, float('-inf'))
def testInitFromDecimal(self): def testInitFromDecimal(self):
self.assertEquals((11, 10), self.assertEqual((11, 10),
_components(F(Decimal('1.1')))) _components(F(Decimal('1.1'))))
self.assertEquals((7, 200), self.assertEqual((7, 200),
_components(F(Decimal('3.5e-2')))) _components(F(Decimal('3.5e-2'))))
self.assertEquals((0, 1), self.assertEqual((0, 1),
_components(F(Decimal('.000e20')))) _components(F(Decimal('.000e20'))))
self.assertRaises(TypeError, F, Decimal('nan')) self.assertRaises(TypeError, F, Decimal('nan'))
self.assertRaises(TypeError, F, Decimal('snan')) self.assertRaises(TypeError, F, Decimal('snan'))
self.assertRaises(TypeError, F, Decimal('inf')) self.assertRaises(TypeError, F, Decimal('inf'))
self.assertRaises(TypeError, F, Decimal('-inf')) self.assertRaises(TypeError, F, Decimal('-inf'))
def testFromString(self): def testFromString(self):
self.assertEquals((5, 1), _components(F("5"))) self.assertEqual((5, 1), _components(F("5")))
self.assertEquals((3, 2), _components(F("3/2"))) self.assertEqual((3, 2), _components(F("3/2")))
self.assertEquals((3, 2), _components(F(" \n +3/2"))) self.assertEqual((3, 2), _components(F(" \n +3/2")))
self.assertEquals((-3, 2), _components(F("-3/2 "))) self.assertEqual((-3, 2), _components(F("-3/2 ")))
self.assertEquals((13, 2), _components(F(" 013/02 \n "))) self.assertEqual((13, 2), _components(F(" 013/02 \n ")))
self.assertEquals((16, 5), _components(F(" 3.2 "))) self.assertEqual((16, 5), _components(F(" 3.2 ")))
self.assertEquals((-16, 5), _components(F(" -3.2 "))) self.assertEqual((-16, 5), _components(F(" -3.2 ")))
self.assertEquals((-3, 1), _components(F(" -3. "))) self.assertEqual((-3, 1), _components(F(" -3. ")))
self.assertEquals((3, 5), _components(F(" .6 "))) self.assertEqual((3, 5), _components(F(" .6 ")))
self.assertEquals((1, 3125), _components(F("32.e-5"))) self.assertEqual((1, 3125), _components(F("32.e-5")))
self.assertEquals((1000000, 1), _components(F("1E+06"))) self.assertEqual((1000000, 1), _components(F("1E+06")))
self.assertEquals((-12300, 1), _components(F("-1.23e4"))) self.assertEqual((-12300, 1), _components(F("-1.23e4")))
self.assertEquals((0, 1), _components(F(" .0e+0\t"))) self.assertEqual((0, 1), _components(F(" .0e+0\t")))
self.assertEquals((0, 1), _components(F("-0.000e0"))) self.assertEqual((0, 1), _components(F("-0.000e0")))
self.assertRaisesMessage( self.assertRaisesMessage(
ZeroDivisionError, "Fraction(3, 0)", ZeroDivisionError, "Fraction(3, 0)",
@ -219,33 +219,33 @@ class FractionTest(unittest.TestCase):
def testImmutable(self): def testImmutable(self):
r = F(7, 3) r = F(7, 3)
r.__init__(2, 15) r.__init__(2, 15)
self.assertEquals((7, 3), _components(r)) self.assertEqual((7, 3), _components(r))
self.assertRaises(AttributeError, setattr, r, 'numerator', 12) self.assertRaises(AttributeError, setattr, r, 'numerator', 12)
self.assertRaises(AttributeError, setattr, r, 'denominator', 6) self.assertRaises(AttributeError, setattr, r, 'denominator', 6)
self.assertEquals((7, 3), _components(r)) self.assertEqual((7, 3), _components(r))
# But if you _really_ need to: # But if you _really_ need to:
r._numerator = 4 r._numerator = 4
r._denominator = 2 r._denominator = 2
self.assertEquals((4, 2), _components(r)) self.assertEqual((4, 2), _components(r))
# Which breaks some important operations: # Which breaks some important operations:
self.assertNotEquals(F(4, 2), r) self.assertNotEqual(F(4, 2), r)
def testFromFloat(self): def testFromFloat(self):
self.assertRaises(TypeError, F.from_float, 3+4j) self.assertRaises(TypeError, F.from_float, 3+4j)
self.assertEquals((10, 1), _components(F.from_float(10))) self.assertEqual((10, 1), _components(F.from_float(10)))
bigint = 1234567890123456789 bigint = 1234567890123456789
self.assertEquals((bigint, 1), _components(F.from_float(bigint))) self.assertEqual((bigint, 1), _components(F.from_float(bigint)))
self.assertEquals((0, 1), _components(F.from_float(-0.0))) self.assertEqual((0, 1), _components(F.from_float(-0.0)))
self.assertEquals((10, 1), _components(F.from_float(10.0))) self.assertEqual((10, 1), _components(F.from_float(10.0)))
self.assertEquals((-5, 2), _components(F.from_float(-2.5))) self.assertEqual((-5, 2), _components(F.from_float(-2.5)))
self.assertEquals((99999999999999991611392, 1), self.assertEqual((99999999999999991611392, 1),
_components(F.from_float(1e23))) _components(F.from_float(1e23)))
self.assertEquals(float(10**23), float(F.from_float(1e23))) self.assertEqual(float(10**23), float(F.from_float(1e23)))
self.assertEquals((3602879701896397, 1125899906842624), self.assertEqual((3602879701896397, 1125899906842624),
_components(F.from_float(3.2))) _components(F.from_float(3.2)))
self.assertEquals(3.2, float(F.from_float(3.2))) self.assertEqual(3.2, float(F.from_float(3.2)))
inf = 1e1000 inf = 1e1000
nan = inf - inf nan = inf - inf
@ -261,13 +261,13 @@ class FractionTest(unittest.TestCase):
def testFromDecimal(self): def testFromDecimal(self):
self.assertRaises(TypeError, F.from_decimal, 3+4j) self.assertRaises(TypeError, F.from_decimal, 3+4j)
self.assertEquals(F(10, 1), F.from_decimal(10)) self.assertEqual(F(10, 1), F.from_decimal(10))
self.assertEquals(F(0), F.from_decimal(Decimal("-0"))) self.assertEqual(F(0), F.from_decimal(Decimal("-0")))
self.assertEquals(F(5, 10), F.from_decimal(Decimal("0.5"))) self.assertEqual(F(5, 10), F.from_decimal(Decimal("0.5")))
self.assertEquals(F(5, 1000), F.from_decimal(Decimal("5e-3"))) self.assertEqual(F(5, 1000), F.from_decimal(Decimal("5e-3")))
self.assertEquals(F(5000), F.from_decimal(Decimal("5e3"))) self.assertEqual(F(5000), F.from_decimal(Decimal("5e3")))
self.assertEquals(1 - F(1, 10**30), self.assertEqual(1 - F(1, 10**30),
F.from_decimal(Decimal("0." + "9" * 30))) F.from_decimal(Decimal("0." + "9" * 30)))
self.assertRaisesMessage( self.assertRaisesMessage(
TypeError, "Cannot convert Infinity to Fraction.", TypeError, "Cannot convert Infinity to Fraction.",
@ -303,15 +303,15 @@ class FractionTest(unittest.TestCase):
self.assertTypedEquals(-2, round(F(-15, 10))) self.assertTypedEquals(-2, round(F(-15, 10)))
self.assertTypedEquals(-1, round(F(-7, 10))) self.assertTypedEquals(-1, round(F(-7, 10)))
self.assertEquals(False, bool(F(0, 1))) self.assertEqual(False, bool(F(0, 1)))
self.assertEquals(True, bool(F(3, 2))) self.assertEqual(True, bool(F(3, 2)))
self.assertTypedEquals(0.1, float(F(1, 10))) self.assertTypedEquals(0.1, float(F(1, 10)))
# Check that __float__ isn't implemented by converting the # Check that __float__ isn't implemented by converting the
# numerator and denominator to float before dividing. # numerator and denominator to float before dividing.
self.assertRaises(OverflowError, float, int('2'*400+'7')) self.assertRaises(OverflowError, float, int('2'*400+'7'))
self.assertAlmostEquals(2.0/3, self.assertAlmostEqual(2.0/3,
float(F(int('2'*400+'7'), int('3'*400+'1')))) float(F(int('2'*400+'7'), int('3'*400+'1'))))
self.assertTypedEquals(0.1+0j, complex(F(1,10))) self.assertTypedEquals(0.1+0j, complex(F(1,10)))
@ -324,19 +324,19 @@ class FractionTest(unittest.TestCase):
def testArithmetic(self): def testArithmetic(self):
self.assertEquals(F(1, 2), F(1, 10) + F(2, 5)) self.assertEqual(F(1, 2), F(1, 10) + F(2, 5))
self.assertEquals(F(-3, 10), F(1, 10) - F(2, 5)) self.assertEqual(F(-3, 10), F(1, 10) - F(2, 5))
self.assertEquals(F(1, 25), F(1, 10) * F(2, 5)) self.assertEqual(F(1, 25), F(1, 10) * F(2, 5))
self.assertEquals(F(1, 4), F(1, 10) / F(2, 5)) self.assertEqual(F(1, 4), F(1, 10) / F(2, 5))
self.assertTypedEquals(2, F(9, 10) // F(2, 5)) self.assertTypedEquals(2, F(9, 10) // F(2, 5))
self.assertTypedEquals(10**23, F(10**23, 1) // F(1)) self.assertTypedEquals(10**23, F(10**23, 1) // F(1))
self.assertEquals(F(2, 3), F(-7, 3) % F(3, 2)) self.assertEqual(F(2, 3), F(-7, 3) % F(3, 2))
self.assertEquals(F(8, 27), F(2, 3) ** F(3)) self.assertEqual(F(8, 27), F(2, 3) ** F(3))
self.assertEquals(F(27, 8), F(2, 3) ** F(-3)) self.assertEqual(F(27, 8), F(2, 3) ** F(-3))
self.assertTypedEquals(2.0, F(4) ** F(1, 2)) self.assertTypedEquals(2.0, F(4) ** F(1, 2))
z = pow(F(-1), F(1, 2)) z = pow(F(-1), F(1, 2))
self.assertAlmostEquals(z.real, 0) self.assertAlmostEqual(z.real, 0)
self.assertEquals(z.imag, 1) self.assertEqual(z.imag, 1)
def testMixedArithmetic(self): def testMixedArithmetic(self):
self.assertTypedEquals(F(11, 10), F(1, 10) + 1) self.assertTypedEquals(F(11, 10), F(1, 10) + 1)
@ -387,8 +387,8 @@ class FractionTest(unittest.TestCase):
self.assertTypedEquals(0.1 + 0j, F(1, 10) ** (1.0 + 0j)) self.assertTypedEquals(0.1 + 0j, F(1, 10) ** (1.0 + 0j))
self.assertTypedEquals(4 , 2 ** F(2, 1)) self.assertTypedEquals(4 , 2 ** F(2, 1))
z = pow(-1, F(1, 2)) z = pow(-1, F(1, 2))
self.assertAlmostEquals(0, z.real) self.assertAlmostEqual(0, z.real)
self.assertEquals(1, z.imag) self.assertEqual(1, z.imag)
self.assertTypedEquals(F(1, 4) , 2 ** F(-2, 1)) self.assertTypedEquals(F(1, 4) , 2 ** F(-2, 1))
self.assertTypedEquals(2.0 , 4 ** F(1, 2)) self.assertTypedEquals(2.0 , 4 ** F(1, 2))
self.assertTypedEquals(0.25, 2.0 ** F(-2, 1)) self.assertTypedEquals(0.25, 2.0 ** F(-2, 1))
@ -534,21 +534,21 @@ class FractionTest(unittest.TestCase):
self.assertFalse(float('-inf') == F(2, 5)) self.assertFalse(float('-inf') == F(2, 5))
def testStringification(self): def testStringification(self):
self.assertEquals("Fraction(7, 3)", repr(F(7, 3))) self.assertEqual("Fraction(7, 3)", repr(F(7, 3)))
self.assertEquals("Fraction(6283185307, 2000000000)", self.assertEqual("Fraction(6283185307, 2000000000)",
repr(F('3.1415926535'))) repr(F('3.1415926535')))
self.assertEquals("Fraction(-1, 100000000000000000000)", self.assertEqual("Fraction(-1, 100000000000000000000)",
repr(F(1, -10**20))) repr(F(1, -10**20)))
self.assertEquals("7/3", str(F(7, 3))) self.assertEqual("7/3", str(F(7, 3)))
self.assertEquals("7", str(F(7, 1))) self.assertEqual("7", str(F(7, 1)))
def testHash(self): def testHash(self):
self.assertEquals(hash(2.5), hash(F(5, 2))) self.assertEqual(hash(2.5), hash(F(5, 2)))
self.assertEquals(hash(10**50), hash(F(10**50))) self.assertEqual(hash(10**50), hash(F(10**50)))
self.assertNotEquals(hash(float(10**23)), hash(F(10**23))) self.assertNotEqual(hash(float(10**23)), hash(F(10**23)))
# Check that __hash__ produces the same value as hash(), for # Check that __hash__ produces the same value as hash(), for
# consistency with int and Decimal. (See issue #10356.) # consistency with int and Decimal. (See issue #10356.)
self.assertEquals(hash(F(-1)), F(-1).__hash__()) self.assertEqual(hash(F(-1)), F(-1).__hash__())
def testApproximatePi(self): def testApproximatePi(self):
# Algorithm borrowed from # Algorithm borrowed from
@ -561,7 +561,7 @@ class FractionTest(unittest.TestCase):
d, da = d+da, da+32 d, da = d+da, da+32
t = (t * n) / d t = (t * n) / d
s += t s += t
self.assertAlmostEquals(math.pi, s) self.assertAlmostEqual(math.pi, s)
def testApproximateCos1(self): def testApproximateCos1(self):
# Algorithm borrowed from # Algorithm borrowed from
@ -575,7 +575,7 @@ class FractionTest(unittest.TestCase):
num *= x * x num *= x * x
sign *= -1 sign *= -1
s += num / fact * sign s += num / fact * sign
self.assertAlmostEquals(math.cos(1), s) self.assertAlmostEqual(math.cos(1), s)
def test_copy_deepcopy_pickle(self): def test_copy_deepcopy_pickle(self):
r = F(13, 7) r = F(13, 7)

View File

@ -22,7 +22,7 @@ class FrozenTests(unittest.TestCase):
self.assertEqual(len(dir(__phello__)), 8, dir(__phello__)) self.assertEqual(len(dir(__phello__)), 8, dir(__phello__))
else: else:
self.assertEqual(len(dir(__phello__)), 9, dir(__phello__)) self.assertEqual(len(dir(__phello__)), 9, dir(__phello__))
self.assertEquals(__phello__.__path__, [__phello__.__name__]) self.assertEqual(__phello__.__path__, [__phello__.__name__])
try: try:
import __phello__.spam import __phello__.spam

View File

@ -428,12 +428,12 @@ class TestTotalOrdering(unittest.TestCase):
self.value = value self.value = value
def __lt__(self, other): def __lt__(self, other):
return self.value < other.value return self.value < other.value
self.assert_(A(1) < A(2)) self.assertTrue(A(1) < A(2))
self.assert_(A(2) > A(1)) self.assertTrue(A(2) > A(1))
self.assert_(A(1) <= A(2)) self.assertTrue(A(1) <= A(2))
self.assert_(A(2) >= A(1)) self.assertTrue(A(2) >= A(1))
self.assert_(A(2) <= A(2)) self.assertTrue(A(2) <= A(2))
self.assert_(A(2) >= A(2)) self.assertTrue(A(2) >= A(2))
def test_total_ordering_le(self): def test_total_ordering_le(self):
@functools.total_ordering @functools.total_ordering
@ -442,12 +442,12 @@ class TestTotalOrdering(unittest.TestCase):
self.value = value self.value = value
def __le__(self, other): def __le__(self, other):
return self.value <= other.value return self.value <= other.value
self.assert_(A(1) < A(2)) self.assertTrue(A(1) < A(2))
self.assert_(A(2) > A(1)) self.assertTrue(A(2) > A(1))
self.assert_(A(1) <= A(2)) self.assertTrue(A(1) <= A(2))
self.assert_(A(2) >= A(1)) self.assertTrue(A(2) >= A(1))
self.assert_(A(2) <= A(2)) self.assertTrue(A(2) <= A(2))
self.assert_(A(2) >= A(2)) self.assertTrue(A(2) >= A(2))
def test_total_ordering_gt(self): def test_total_ordering_gt(self):
@functools.total_ordering @functools.total_ordering
@ -456,12 +456,12 @@ class TestTotalOrdering(unittest.TestCase):
self.value = value self.value = value
def __gt__(self, other): def __gt__(self, other):
return self.value > other.value return self.value > other.value
self.assert_(A(1) < A(2)) self.assertTrue(A(1) < A(2))
self.assert_(A(2) > A(1)) self.assertTrue(A(2) > A(1))
self.assert_(A(1) <= A(2)) self.assertTrue(A(1) <= A(2))
self.assert_(A(2) >= A(1)) self.assertTrue(A(2) >= A(1))
self.assert_(A(2) <= A(2)) self.assertTrue(A(2) <= A(2))
self.assert_(A(2) >= A(2)) self.assertTrue(A(2) >= A(2))
def test_total_ordering_ge(self): def test_total_ordering_ge(self):
@functools.total_ordering @functools.total_ordering
@ -470,24 +470,24 @@ class TestTotalOrdering(unittest.TestCase):
self.value = value self.value = value
def __ge__(self, other): def __ge__(self, other):
return self.value >= other.value return self.value >= other.value
self.assert_(A(1) < A(2)) self.assertTrue(A(1) < A(2))
self.assert_(A(2) > A(1)) self.assertTrue(A(2) > A(1))
self.assert_(A(1) <= A(2)) self.assertTrue(A(1) <= A(2))
self.assert_(A(2) >= A(1)) self.assertTrue(A(2) >= A(1))
self.assert_(A(2) <= A(2)) self.assertTrue(A(2) <= A(2))
self.assert_(A(2) >= A(2)) self.assertTrue(A(2) >= A(2))
def test_total_ordering_no_overwrite(self): def test_total_ordering_no_overwrite(self):
# new methods should not overwrite existing # new methods should not overwrite existing
@functools.total_ordering @functools.total_ordering
class A(int): class A(int):
pass pass
self.assert_(A(1) < A(2)) self.assertTrue(A(1) < A(2))
self.assert_(A(2) > A(1)) self.assertTrue(A(2) > A(1))
self.assert_(A(1) <= A(2)) self.assertTrue(A(1) <= A(2))
self.assert_(A(2) >= A(1)) self.assertTrue(A(2) >= A(1))
self.assert_(A(2) <= A(2)) self.assertTrue(A(2) <= A(2))
self.assert_(A(2) >= A(2)) self.assertTrue(A(2) >= A(2))
def test_no_operations_defined(self): def test_no_operations_defined(self):
with self.assertRaises(ValueError): with self.assertRaises(ValueError):
@ -507,9 +507,9 @@ class TestLRU(unittest.TestCase):
x, y = choice(domain), choice(domain) x, y = choice(domain), choice(domain)
actual = f(x, y) actual = f(x, y)
expected = orig(x, y) expected = orig(x, y)
self.assertEquals(actual, expected) self.assertEqual(actual, expected)
self.assert_(f.cache_hits > f.cache_misses) self.assertTrue(f.cache_hits > f.cache_misses)
self.assertEquals(f.cache_hits + f.cache_misses, 1000) self.assertEqual(f.cache_hits + f.cache_misses, 1000)
f.cache_clear() # test clearing f.cache_clear() # test clearing
self.assertEqual(f.cache_hits, 0) self.assertEqual(f.cache_hits, 0)

View File

@ -129,7 +129,7 @@ class DebuggerTests(unittest.TestCase):
'') '')
# Ensure no unexpected error messages: # Ensure no unexpected error messages:
self.assertEquals(err, '') self.assertEqual(err, '')
return out return out
@ -159,8 +159,8 @@ class DebuggerTests(unittest.TestCase):
def assertEndsWith(self, actual, exp_end): def assertEndsWith(self, actual, exp_end):
'''Ensure that the given "actual" string ends with "exp_end"''' '''Ensure that the given "actual" string ends with "exp_end"'''
self.assert_(actual.endswith(exp_end), self.assertTrue(actual.endswith(exp_end),
msg='%r did not end with %r' % (actual, exp_end)) msg='%r did not end with %r' % (actual, exp_end))
def assertMultilineMatches(self, actual, pattern): def assertMultilineMatches(self, actual, pattern):
m = re.match(pattern, actual, re.DOTALL) m = re.match(pattern, actual, re.DOTALL)
@ -182,9 +182,9 @@ class PrettyPrintTests(DebuggerTests):
cmds_after_breakpoint) cmds_after_breakpoint)
if not exp_repr: if not exp_repr:
exp_repr = repr(val) exp_repr = repr(val)
self.assertEquals(gdb_repr, exp_repr, self.assertEqual(gdb_repr, exp_repr,
('%r did not equal expected %r; full output was:\n%s' ('%r did not equal expected %r; full output was:\n%s'
% (gdb_repr, exp_repr, gdb_output))) % (gdb_repr, exp_repr, gdb_output)))
def test_int(self): def test_int(self):
'Verify the pretty-printing of various "int"/long values' 'Verify the pretty-printing of various "int"/long values'
@ -274,7 +274,7 @@ class PrettyPrintTests(DebuggerTests):
gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b']) gdb_repr, gdb_output = self.get_gdb_repr('''s = set(['a','b'])
s.pop() s.pop()
id(s)''') id(s)''')
self.assertEquals(gdb_repr, "{'b'}") self.assertEqual(gdb_repr, "{'b'}")
def test_frozensets(self): def test_frozensets(self):
'Verify the pretty-printing of frozensets' 'Verify the pretty-printing of frozensets'
@ -290,8 +290,8 @@ try:
except RuntimeError as e: except RuntimeError as e:
id(e) id(e)
''') ''')
self.assertEquals(gdb_repr, self.assertEqual(gdb_repr,
"RuntimeError('I am an error',)") "RuntimeError('I am an error',)")
# Test division by zero: # Test division by zero:
@ -301,8 +301,8 @@ try:
except ZeroDivisionError as e: except ZeroDivisionError as e:
id(e) id(e)
''') ''')
self.assertEquals(gdb_repr, self.assertEqual(gdb_repr,
"ZeroDivisionError('division by zero',)") "ZeroDivisionError('division by zero',)")
def test_modern_class(self): def test_modern_class(self):
'Verify the pretty-printing of new-style class instances' 'Verify the pretty-printing of new-style class instances'
@ -382,7 +382,7 @@ id(foo)''')
'backtrace']) 'backtrace'])
) )
self.assertEquals(gdb_repr, '0x0') self.assertEqual(gdb_repr, '0x0')
def test_NULL_ob_type(self): def test_NULL_ob_type(self):
'Ensure that a PyObject* with NULL ob_type is handled gracefully' 'Ensure that a PyObject* with NULL ob_type is handled gracefully'
@ -422,11 +422,11 @@ id(foo)''')
into an infinite loop:''' into an infinite loop:'''
gdb_repr, gdb_output = \ gdb_repr, gdb_output = \
self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)") self.get_gdb_repr("a = [3, 4, 5] ; a.append(a) ; id(a)")
self.assertEquals(gdb_repr, '[3, 4, 5, [...]]') self.assertEqual(gdb_repr, '[3, 4, 5, [...]]')
gdb_repr, gdb_output = \ gdb_repr, gdb_output = \
self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)") self.get_gdb_repr("a = [3, 4, 5] ; b = [a] ; a.append(b) ; id(a)")
self.assertEquals(gdb_repr, '[3, 4, 5, [[...]]]') self.assertEqual(gdb_repr, '[3, 4, 5, [[...]]]')
def test_selfreferential_dict(self): def test_selfreferential_dict(self):
'''Ensure that a reference loop involving a dict doesn't lead proxyval '''Ensure that a reference loop involving a dict doesn't lead proxyval
@ -434,7 +434,7 @@ id(foo)''')
gdb_repr, gdb_output = \ gdb_repr, gdb_output = \
self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)") self.get_gdb_repr("a = {} ; b = {'bar':a} ; a['foo'] = b ; id(a)")
self.assertEquals(gdb_repr, "{'foo': {'bar': {...}}}") self.assertEqual(gdb_repr, "{'foo': {'bar': {...}}}")
def test_selfreferential_old_style_instance(self): def test_selfreferential_old_style_instance(self):
gdb_repr, gdb_output = \ gdb_repr, gdb_output = \
@ -479,30 +479,30 @@ id(a)''')
def test_truncation(self): def test_truncation(self):
'Verify that very long output is truncated' 'Verify that very long output is truncated'
gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))') gdb_repr, gdb_output = self.get_gdb_repr('id(list(range(1000)))')
self.assertEquals(gdb_repr, self.assertEqual(gdb_repr,
"[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, " "[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, "
"14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, " "14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, "
"27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, " "27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, "
"40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, " "40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, "
"53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, " "53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 63, 64, 65, "
"66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, " "66, 67, 68, 69, 70, 71, 72, 73, 74, 75, 76, 77, 78, "
"79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, " "79, 80, 81, 82, 83, 84, 85, 86, 87, 88, 89, 90, 91, "
"92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, " "92, 93, 94, 95, 96, 97, 98, 99, 100, 101, 102, 103, "
"104, 105, 106, 107, 108, 109, 110, 111, 112, 113, " "104, 105, 106, 107, 108, 109, 110, 111, 112, 113, "
"114, 115, 116, 117, 118, 119, 120, 121, 122, 123, " "114, 115, 116, 117, 118, 119, 120, 121, 122, 123, "
"124, 125, 126, 127, 128, 129, 130, 131, 132, 133, " "124, 125, 126, 127, 128, 129, 130, 131, 132, 133, "
"134, 135, 136, 137, 138, 139, 140, 141, 142, 143, " "134, 135, 136, 137, 138, 139, 140, 141, 142, 143, "
"144, 145, 146, 147, 148, 149, 150, 151, 152, 153, " "144, 145, 146, 147, 148, 149, 150, 151, 152, 153, "
"154, 155, 156, 157, 158, 159, 160, 161, 162, 163, " "154, 155, 156, 157, 158, 159, 160, 161, 162, 163, "
"164, 165, 166, 167, 168, 169, 170, 171, 172, 173, " "164, 165, 166, 167, 168, 169, 170, 171, 172, 173, "
"174, 175, 176, 177, 178, 179, 180, 181, 182, 183, " "174, 175, 176, 177, 178, 179, 180, 181, 182, 183, "
"184, 185, 186, 187, 188, 189, 190, 191, 192, 193, " "184, 185, 186, 187, 188, 189, 190, 191, 192, 193, "
"194, 195, 196, 197, 198, 199, 200, 201, 202, 203, " "194, 195, 196, 197, 198, 199, 200, 201, 202, 203, "
"204, 205, 206, 207, 208, 209, 210, 211, 212, 213, " "204, 205, 206, 207, 208, 209, 210, 211, 212, 213, "
"214, 215, 216, 217, 218, 219, 220, 221, 222, 223, " "214, 215, 216, 217, 218, 219, 220, 221, 222, 223, "
"224, 225, 226...(truncated)") "224, 225, 226...(truncated)")
self.assertEquals(len(gdb_repr), self.assertEqual(len(gdb_repr),
1024 + len('...(truncated)')) 1024 + len('...(truncated)'))
def test_builtin_method(self): def test_builtin_method(self):
gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)') gdb_repr, gdb_output = self.get_gdb_repr('import sys; id(sys.stdout.readlines)')

View File

@ -220,7 +220,7 @@ class Tuple_TestCase(unittest.TestCase):
from _testcapi import getargs_tuple from _testcapi import getargs_tuple
ret = getargs_tuple(1, (2, 3)) ret = getargs_tuple(1, (2, 3))
self.assertEquals(ret, (1,2,3)) self.assertEqual(ret, (1,2,3))
# make sure invalid tuple arguments are handled correctly # make sure invalid tuple arguments are handled correctly
class seq: class seq:
@ -233,28 +233,28 @@ class Tuple_TestCase(unittest.TestCase):
class Keywords_TestCase(unittest.TestCase): class Keywords_TestCase(unittest.TestCase):
def test_positional_args(self): def test_positional_args(self):
# using all positional args # using all positional args
self.assertEquals( self.assertEqual(
getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), 10), getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), 10),
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
) )
def test_mixed_args(self): def test_mixed_args(self):
# positional and keyword args # positional and keyword args
self.assertEquals( self.assertEqual(
getargs_keywords((1,2), 3, (4,(5,6)), arg4=(7,8,9), arg5=10), getargs_keywords((1,2), 3, (4,(5,6)), arg4=(7,8,9), arg5=10),
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
) )
def test_keyword_args(self): def test_keyword_args(self):
# all keywords # all keywords
self.assertEquals( self.assertEqual(
getargs_keywords(arg1=(1,2), arg2=3, arg3=(4,(5,6)), arg4=(7,8,9), arg5=10), getargs_keywords(arg1=(1,2), arg2=3, arg3=(4,(5,6)), arg4=(7,8,9), arg5=10),
(1, 2, 3, 4, 5, 6, 7, 8, 9, 10) (1, 2, 3, 4, 5, 6, 7, 8, 9, 10)
) )
def test_optional_args(self): def test_optional_args(self):
# missing optional keyword args, skipping tuples # missing optional keyword args, skipping tuples
self.assertEquals( self.assertEqual(
getargs_keywords(arg1=(1,2), arg2=3, arg5=10), getargs_keywords(arg1=(1,2), arg2=3, arg5=10),
(1, 2, 3, -1, -1, -1, -1, -1, -1, 10) (1, 2, 3, -1, -1, -1, -1, -1, -1, 10)
) )
@ -264,7 +264,7 @@ class Keywords_TestCase(unittest.TestCase):
try: try:
getargs_keywords(arg1=(1,2)) getargs_keywords(arg1=(1,2))
except TypeError as err: except TypeError as err:
self.assertEquals(str(err), "Required argument 'arg2' (pos 2) not found") self.assertEqual(str(err), "Required argument 'arg2' (pos 2) not found")
else: else:
self.fail('TypeError should have been raised') self.fail('TypeError should have been raised')
@ -272,7 +272,7 @@ class Keywords_TestCase(unittest.TestCase):
try: try:
getargs_keywords((1,2),3,(4,(5,6)),(7,8,9),10,111) getargs_keywords((1,2),3,(4,(5,6)),(7,8,9),10,111)
except TypeError as err: except TypeError as err:
self.assertEquals(str(err), "function takes at most 5 arguments (6 given)") self.assertEqual(str(err), "function takes at most 5 arguments (6 given)")
else: else:
self.fail('TypeError should have been raised') self.fail('TypeError should have been raised')
@ -281,7 +281,7 @@ class Keywords_TestCase(unittest.TestCase):
try: try:
getargs_keywords((1,2),3,arg5=10,arg666=666) getargs_keywords((1,2),3,arg5=10,arg666=666)
except TypeError as err: except TypeError as err:
self.assertEquals(str(err), "'arg666' is an invalid keyword argument for this function") self.assertEqual(str(err), "'arg666' is an invalid keyword argument for this function")
else: else:
self.fail('TypeError should have been raised') self.fail('TypeError should have been raised')
@ -289,7 +289,7 @@ class Keywords_TestCase(unittest.TestCase):
try: try:
getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), **{'\uDC80': 10}) getargs_keywords((1,2), 3, (4,(5,6)), (7,8,9), **{'\uDC80': 10})
except TypeError as err: except TypeError as err:
self.assertEquals(str(err), "'\udc80' is an invalid keyword argument for this function") self.assertEqual(str(err), "'\udc80' is an invalid keyword argument for this function")
else: else:
self.fail('TypeError should have been raised') self.fail('TypeError should have been raised')

View File

@ -175,9 +175,9 @@ class GetoptTests(unittest.TestCase):
def test_issue4629(self): def test_issue4629(self):
longopts, shortopts = getopt.getopt(['--help='], '', ['help=']) longopts, shortopts = getopt.getopt(['--help='], '', ['help='])
self.assertEquals(longopts, [('--help', '')]) self.assertEqual(longopts, [('--help', '')])
longopts, shortopts = getopt.getopt(['--help=x'], '', ['help=']) longopts, shortopts = getopt.getopt(['--help=x'], '', ['help='])
self.assertEquals(longopts, [('--help', 'x')]) self.assertEqual(longopts, [('--help', 'x')])
self.assertRaises(getopt.GetoptError, getopt.getopt, ['--help='], '', ['help']) self.assertRaises(getopt.GetoptError, getopt.getopt, ['--help='], '', ['help'])
def test_main(): def test_main():

View File

@ -59,8 +59,8 @@ class GlobTests(unittest.TestCase):
if set(type(x) for x in tmp) == uniset: if set(type(x) for x in tmp) == uniset:
u1 = glob.glob('*') u1 = glob.glob('*')
u2 = glob.glob('./*') u2 = glob.glob('./*')
self.assertEquals(set(type(r) for r in u1), uniset) self.assertEqual(set(type(r) for r in u1), uniset)
self.assertEquals(set(type(r) for r in u2), uniset) self.assertEqual(set(type(r) for r in u2), uniset)
def test_glob_one_directory(self): def test_glob_one_directory(self):
eq = self.assertSequencesEqual_noorder eq = self.assertSequencesEqual_noorder

View File

@ -113,7 +113,7 @@ class TestGzip(unittest.TestCase):
ztxt = zgfile.read(8192) ztxt = zgfile.read(8192)
contents += ztxt contents += ztxt
if not ztxt: break if not ztxt: break
self.assertEquals(contents, b'a'*201) self.assertEqual(contents, b'a'*201)
def test_buffered_reader(self): def test_buffered_reader(self):
# Issue #7471: a GzipFile can be wrapped in a BufferedReader for # Issue #7471: a GzipFile can be wrapped in a BufferedReader for
@ -177,7 +177,7 @@ class TestGzip(unittest.TestCase):
f.read(10) f.read(10)
f.seek(10, whence=1) f.seek(10, whence=1)
y = f.read(10) y = f.read(10)
self.assertEquals(y, data1[20:30]) self.assertEqual(y, data1[20:30])
def test_seek_write(self): def test_seek_write(self):
# Try seek, write test # Try seek, write test

Some files were not shown because too many files have changed in this diff Show More