summaryrefslogtreecommitdiff
path: root/Lib/test
diff options
context:
space:
mode:
Diffstat (limited to 'Lib/test')
-rw-r--r--Lib/test/mapping_tests.py92
-rw-r--r--Lib/test/pickletester.py26
-rw-r--r--Lib/test/test___all__.py2
-rw-r--r--Lib/test/test___future__.py4
-rw-r--r--Lib/test/test_abc.py52
-rw-r--r--Lib/test/test_abstract_numbers.py12
-rwxr-xr-xLib/test/test_array.py74
-rw-r--r--Lib/test/test_ast.py10
-rw-r--r--Lib/test/test_augassign.py12
-rw-r--r--Lib/test/test_base64.py2
-rw-r--r--Lib/test/test_bigmem.py138
-rwxr-xr-xLib/test/test_binascii.py8
-rw-r--r--Lib/test/test_binop.py8
-rw-r--r--Lib/test/test_bisect.py18
-rw-r--r--Lib/test/test_bool.py10
-rw-r--r--Lib/test/test_bufio.py2
-rw-r--r--Lib/test/test_builtin.py74
-rw-r--r--Lib/test/test_bytes.py112
-rw-r--r--Lib/test/test_capi.py4
-rw-r--r--Lib/test/test_cfgparser.py20
-rw-r--r--Lib/test/test_cgi.py4
-rwxr-xr-xLib/test/test_cmath.py56
-rw-r--r--Lib/test/test_cmd_line.py6
-rw-r--r--Lib/test/test_cmd_line_script.py8
-rw-r--r--Lib/test/test_codecs.py10
-rw-r--r--Lib/test/test_codeop.py6
-rw-r--r--Lib/test/test_collections.py144
-rw-r--r--Lib/test/test_compile.py10
-rw-r--r--Lib/test/test_complex.py10
-rw-r--r--Lib/test/test_contains.py36
-rw-r--r--Lib/test/test_contextlib.py20
-rw-r--r--Lib/test/test_copy.py124
-rw-r--r--Lib/test/test_copyreg.py8
-rw-r--r--Lib/test/test_csv.py8
-rw-r--r--Lib/test/test_datetime.py338
-rw-r--r--Lib/test/test_dbm.py6
-rw-r--r--Lib/test/test_dbm_dumb.py2
-rwxr-xr-xLib/test/test_dbm_gnu.py8
-rwxr-xr-xLib/test/test_dbm_ndbm.py4
-rw-r--r--Lib/test/test_decimal.py88
-rw-r--r--Lib/test/test_defaultdict.py24
-rw-r--r--Lib/test/test_deque.py10
-rw-r--r--Lib/test/test_descr.py318
-rw-r--r--Lib/test/test_dict.py52
-rw-r--r--Lib/test/test_dictviews.py22
-rw-r--r--Lib/test/test_docxmlrpc.py8
-rw-r--r--Lib/test/test_dummy_thread.py38
-rw-r--r--Lib/test/test_epoll.py20
-rwxr-xr-xLib/test/test_errno.py6
-rw-r--r--Lib/test/test_exceptions.py50
-rw-r--r--Lib/test/test_file.py8
-rw-r--r--Lib/test/test_filecmp.py26
-rw-r--r--Lib/test/test_fileinput.py6
-rw-r--r--Lib/test/test_fileio.py12
-rw-r--r--Lib/test/test_float.py60
-rw-r--r--Lib/test/test_fnmatch.py4
-rw-r--r--Lib/test/test_ftplib.py4
-rw-r--r--Lib/test/test_funcattrs.py18
-rw-r--r--Lib/test/test_functools.py18
-rw-r--r--Lib/test/test_genericpath.py4
-rw-r--r--Lib/test/test_getargs2.py142
-rw-r--r--Lib/test/test_getopt.py10
-rw-r--r--Lib/test/test_gettext.py2
-rw-r--r--Lib/test/test_grammar.py26
-rwxr-xr-xLib/test/test_grp.py8
-rw-r--r--Lib/test/test_gzip.py6
-rw-r--r--Lib/test/test_hash.py2
-rw-r--r--Lib/test/test_hashlib.py2
-rw-r--r--Lib/test/test_heapq.py2
-rw-r--r--Lib/test/test_hmac.py8
-rw-r--r--Lib/test/test_http_cookiejar.py220
-rw-r--r--Lib/test/test_httplib.py4
-rw-r--r--Lib/test/test_httpservers.py4
-rw-r--r--Lib/test/test_imp.py2
-rw-r--r--Lib/test/test_import.py14
-rw-r--r--Lib/test/test_importhooks.py2
-rw-r--r--Lib/test/test_index.py22
-rw-r--r--Lib/test/test_inspect.py66
-rw-r--r--Lib/test/test_int.py12
-rw-r--r--Lib/test/test_io.py26
-rw-r--r--Lib/test/test_ioctl.py4
-rw-r--r--Lib/test/test_iter.py22
-rw-r--r--Lib/test/test_itertools.py14
-rw-r--r--Lib/test/test_kqueue.py10
-rw-r--r--Lib/test/test_largefile.py2
-rw-r--r--Lib/test/test_list.py8
-rw-r--r--Lib/test/test_logging.py52
-rw-r--r--Lib/test/test_long.py26
-rw-r--r--Lib/test/test_macpath.py42
-rw-r--r--Lib/test/test_mailbox.py174
-rw-r--r--Lib/test/test_math.py148
-rw-r--r--Lib/test/test_memoryio.py4
-rw-r--r--Lib/test/test_memoryview.py10
-rw-r--r--Lib/test/test_mimetypes.py2
-rw-r--r--Lib/test/test_minidom.py2
-rw-r--r--Lib/test/test_mmap.py4
-rw-r--r--Lib/test/test_module.py4
-rw-r--r--Lib/test/test_modulefinder.py6
-rw-r--r--Lib/test/test_multibytecodec.py4
-rw-r--r--Lib/test/test_multibytecodec_support.py4
-rw-r--r--Lib/test/test_netrc.py6
-rw-r--r--Lib/test/test_normalization.py14
-rw-r--r--Lib/test/test_opcodes.py2
-rw-r--r--Lib/test/test_operator.py272
-rw-r--r--Lib/test/test_optparse.py64
-rw-r--r--Lib/test/test_os.py14
-rw-r--r--Lib/test/test_ossaudiodev.py8
-rw-r--r--Lib/test/test_parser.py18
-rw-r--r--Lib/test/test_peepholer.py62
-rw-r--r--Lib/test/test_pep247.py6
-rw-r--r--Lib/test/test_pep277.py4
-rw-r--r--Lib/test/test_pep3120.py2
-rw-r--r--Lib/test/test_pep352.py10
-rw-r--r--Lib/test/test_pkg.py22
-rw-r--r--Lib/test/test_pkgimport.py2
-rw-r--r--Lib/test/test_platform.py6
-rw-r--r--Lib/test/test_poplib.py2
-rw-r--r--Lib/test/test_posix.py18
-rw-r--r--Lib/test/test_posixpath.py28
-rw-r--r--Lib/test/test_pprint.py8
-rw-r--r--Lib/test/test_property.py4
-rw-r--r--Lib/test/test_pwd.py18
-rw-r--r--Lib/test/test_pyclbr.py8
-rw-r--r--Lib/test/test_pydoc.py6
-rw-r--r--Lib/test/test_queue.py28
-rw-r--r--Lib/test/test_raise.py34
-rw-r--r--Lib/test/test_random.py30
-rw-r--r--Lib/test/test_range.py12
-rw-r--r--Lib/test/test_re.py2
-rw-r--r--Lib/test/test_reprlib.py20
-rw-r--r--Lib/test/test_richcmp.py18
-rw-r--r--Lib/test/test_robotparser.py4
-rw-r--r--Lib/test/test_runpy.py58
-rw-r--r--Lib/test/test_scope.py10
-rw-r--r--Lib/test/test_set.py118
-rw-r--r--Lib/test/test_shutil.py24
-rw-r--r--Lib/test/test_signal.py6
-rw-r--r--Lib/test/test_site.py32
-rw-r--r--Lib/test/test_slice.py2
-rw-r--r--Lib/test/test_socket.py54
-rw-r--r--Lib/test/test_stringprep.py80
-rw-r--r--Lib/test/test_strptime.py94
-rw-r--r--Lib/test/test_struct.py4
-rw-r--r--Lib/test/test_structseq.py16
-rw-r--r--Lib/test/test_subprocess.py14
-rw-r--r--Lib/test/test_symtable.py2
-rw-r--r--Lib/test/test_sys.py102
-rw-r--r--Lib/test/test_tarfile.py86
-rw-r--r--Lib/test/test_tempfile.py112
-rw-r--r--Lib/test/test_threading.py30
-rw-r--r--Lib/test/test_threading_local.py2
-rw-r--r--Lib/test/test_time.py48
-rw-r--r--Lib/test/test_timeout.py16
-rw-r--r--Lib/test/test_tokenize.py2
-rw-r--r--Lib/test/test_traceback.py50
-rw-r--r--Lib/test/test_tuple.py12
-rw-r--r--Lib/test/test_types.py4
-rw-r--r--Lib/test/test_unary.py18
-rw-r--r--Lib/test/test_unicode.py76
-rw-r--r--Lib/test/test_unicode_file.py38
-rw-r--r--Lib/test/test_unicodedata.py14
-rw-r--r--Lib/test/test_urllib.py26
-rw-r--r--Lib/test/test_urllib2.py58
-rw-r--r--Lib/test/test_urllib2_localnet.py6
-rw-r--r--Lib/test/test_urllib2net.py6
-rw-r--r--Lib/test/test_urllibnet.py22
-rw-r--r--Lib/test/test_userdict.py14
-rw-r--r--Lib/test/test_uuid.py8
-rw-r--r--Lib/test/test_warnings.py64
-rw-r--r--Lib/test/test_weakref.py164
-rw-r--r--Lib/test/test_weakset.py80
-rw-r--r--Lib/test/test_winreg.py2
-rwxr-xr-xLib/test/test_wsgiref.py44
-rw-r--r--Lib/test/test_xdrlib.py6
-rw-r--r--Lib/test/test_xmlrpc.py16
-rw-r--r--Lib/test/test_xmlrpc_net.py2
-rw-r--r--Lib/test/test_zipfile.py76
-rw-r--r--Lib/test/test_zipimport.py4
-rw-r--r--Lib/test/test_zipimport_support.py8
-rw-r--r--Lib/test/test_zlib.py20
180 files changed, 2954 insertions, 2954 deletions
diff --git a/Lib/test/mapping_tests.py b/Lib/test/mapping_tests.py
index b8bbc9a229..c34bd59e9c 100644
--- a/Lib/test/mapping_tests.py
+++ b/Lib/test/mapping_tests.py
@@ -50,15 +50,15 @@ class BasicTestMappingProtocol(unittest.TestCase):
for key, value in self.reference.items():
self.assertEqual(d[key], value)
knownkey = list(self.other.keys())[0]
- self.failUnlessRaises(KeyError, lambda:d[knownkey])
+ self.assertRaises(KeyError, lambda:d[knownkey])
#len
self.assertEqual(len(p), 0)
self.assertEqual(len(d), len(self.reference))
#__contains__
for k in self.reference:
- self.assert_(k in d)
+ self.assertTrue(k in d)
for k in self.other:
- self.failIf(k in d)
+ self.assertFalse(k in d)
#cmp
self.assertEqual(p, p)
self.assertEqual(d, d)
@@ -69,10 +69,10 @@ class BasicTestMappingProtocol(unittest.TestCase):
if not d: self.fail("Full mapping must compare to True")
# keys(), items(), iterkeys() ...
def check_iterandlist(iter, lst, ref):
- self.assert_(hasattr(iter, '__next__'))
- self.assert_(hasattr(iter, '__iter__'))
+ self.assertTrue(hasattr(iter, '__next__'))
+ self.assertTrue(hasattr(iter, '__iter__'))
x = list(iter)
- self.assert_(set(x)==set(lst)==set(ref))
+ self.assertTrue(set(x)==set(lst)==set(ref))
check_iterandlist(iter(d.keys()), list(d.keys()),
self.reference.keys())
check_iterandlist(iter(d), list(d.keys()), self.reference.keys())
@@ -85,7 +85,7 @@ class BasicTestMappingProtocol(unittest.TestCase):
knownkey, knownvalue = next(iter(self.other.items()))
self.assertEqual(d.get(key, knownvalue), value)
self.assertEqual(d.get(knownkey, knownvalue), knownvalue)
- self.failIf(knownkey in d)
+ self.assertFalse(knownkey in d)
def test_write(self):
# Test for write operations on mapping
@@ -96,7 +96,7 @@ class BasicTestMappingProtocol(unittest.TestCase):
self.assertEqual(p[key], value)
for key in self.reference.keys():
del p[key]
- self.failUnlessRaises(KeyError, lambda:p[key])
+ self.assertRaises(KeyError, lambda:p[key])
p = self._empty_mapping()
#update
p.update(self.reference)
@@ -115,16 +115,16 @@ class BasicTestMappingProtocol(unittest.TestCase):
self.assertEqual(d[knownkey], knownvalue)
#pop
self.assertEqual(d.pop(knownkey), knownvalue)
- self.failIf(knownkey in d)
+ self.assertFalse(knownkey in d)
self.assertRaises(KeyError, d.pop, knownkey)
default = 909
d[knownkey] = knownvalue
self.assertEqual(d.pop(knownkey, default), knownvalue)
- self.failIf(knownkey in d)
+ self.assertFalse(knownkey in d)
self.assertEqual(d.pop(knownkey, default), default)
#popitem
key, value = d.popitem()
- self.failIf(key in d)
+ self.assertFalse(key in d)
self.assertEqual(value, self.reference[key])
p=self._empty_mapping()
self.assertRaises(KeyError, p.popitem)
@@ -133,17 +133,17 @@ class BasicTestMappingProtocol(unittest.TestCase):
self.assertEqual(self._empty_mapping(), self._empty_mapping())
def test_bool(self):
- self.assert_(not self._empty_mapping())
- self.assert_(self.reference)
- self.assert_(bool(self._empty_mapping()) is False)
- self.assert_(bool(self.reference) is True)
+ self.assertTrue(not self._empty_mapping())
+ self.assertTrue(self.reference)
+ self.assertTrue(bool(self._empty_mapping()) is False)
+ self.assertTrue(bool(self.reference) is True)
def test_keys(self):
d = self._empty_mapping()
self.assertEqual(list(d.keys()), [])
d = self.reference
- self.assert_(list(self.inmapping.keys())[0] in d.keys())
- self.assert_(list(self.other.keys())[0] not in d.keys())
+ self.assertTrue(list(self.inmapping.keys())[0] in d.keys())
+ self.assertTrue(list(self.other.keys())[0] not in d.keys())
self.assertRaises(TypeError, d.keys, None)
def test_values(self):
@@ -268,10 +268,10 @@ class BasicTestMappingProtocol(unittest.TestCase):
def test_get(self):
d = self._empty_mapping()
- self.assert_(d.get(list(self.other.keys())[0]) is None)
+ self.assertTrue(d.get(list(self.other.keys())[0]) is None)
self.assertEqual(d.get(list(self.other.keys())[0], 3), 3)
d = self.reference
- self.assert_(d.get(list(self.other.keys())[0]) is None)
+ self.assertTrue(d.get(list(self.other.keys())[0]) is None)
self.assertEqual(d.get(list(self.other.keys())[0], 3), 3)
self.assertEqual(d.get(list(self.inmapping.keys())[0]),
list(self.inmapping.values())[0])
@@ -304,15 +304,15 @@ class BasicTestMappingProtocol(unittest.TestCase):
class TestMappingProtocol(BasicTestMappingProtocol):
def test_constructor(self):
BasicTestMappingProtocol.test_constructor(self)
- self.assert_(self._empty_mapping() is not self._empty_mapping())
+ self.assertTrue(self._empty_mapping() is not self._empty_mapping())
self.assertEqual(self.type2test(x=1, y=2), {"x": 1, "y": 2})
def test_bool(self):
BasicTestMappingProtocol.test_bool(self)
- self.assert_(not self._empty_mapping())
- self.assert_(self._full_mapping({"x": "y"}))
- self.assert_(bool(self._empty_mapping()) is False)
- self.assert_(bool(self._full_mapping({"x": "y"})) is True)
+ self.assertTrue(not self._empty_mapping())
+ self.assertTrue(self._full_mapping({"x": "y"}))
+ self.assertTrue(bool(self._empty_mapping()) is False)
+ self.assertTrue(bool(self._full_mapping({"x": "y"})) is True)
def test_keys(self):
BasicTestMappingProtocol.test_keys(self)
@@ -320,9 +320,9 @@ class TestMappingProtocol(BasicTestMappingProtocol):
self.assertEqual(list(d.keys()), [])
d = self._full_mapping({'a': 1, 'b': 2})
k = d.keys()
- self.assert_('a' in k)
- self.assert_('b' in k)
- self.assert_('c' not in k)
+ self.assertTrue('a' in k)
+ self.assertTrue('b' in k)
+ self.assertTrue('c' not in k)
def test_values(self):
BasicTestMappingProtocol.test_values(self)
@@ -337,12 +337,12 @@ class TestMappingProtocol(BasicTestMappingProtocol):
def test_contains(self):
d = self._empty_mapping()
- self.assert_(not ('a' in d))
- self.assert_('a' not in d)
+ self.assertTrue(not ('a' in d))
+ self.assertTrue('a' not in d)
d = self._full_mapping({'a': 1, 'b': 2})
- self.assert_('a' in d)
- self.assert_('b' in d)
- self.assert_('c' not in d)
+ self.assertTrue('a' in d)
+ self.assertTrue('b' in d)
+ self.assertTrue('c' not in d)
self.assertRaises(TypeError, d.__contains__)
@@ -421,7 +421,7 @@ class TestMappingProtocol(BasicTestMappingProtocol):
def test_fromkeys(self):
self.assertEqual(self.type2test.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
d = self._empty_mapping()
- self.assert_(not(d.fromkeys('abc') is d))
+ self.assertTrue(not(d.fromkeys('abc') is d))
self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0})
self.assertEqual(d.fromkeys([]), {})
@@ -432,17 +432,17 @@ class TestMappingProtocol(BasicTestMappingProtocol):
class dictlike(self.type2test): pass
self.assertEqual(dictlike.fromkeys('a'), {'a':None})
self.assertEqual(dictlike().fromkeys('a'), {'a':None})
- self.assert_(dictlike.fromkeys('a').__class__ is dictlike)
- self.assert_(dictlike().fromkeys('a').__class__ is dictlike)
+ self.assertTrue(dictlike.fromkeys('a').__class__ is dictlike)
+ self.assertTrue(dictlike().fromkeys('a').__class__ is dictlike)
# FIXME: the following won't work with UserDict, because it's an old style class
- # self.assert_(type(dictlike.fromkeys('a')) is dictlike)
+ # self.assertTrue(type(dictlike.fromkeys('a')) is dictlike)
class mydict(self.type2test):
def __new__(cls):
return collections.UserDict()
ud = mydict.fromkeys('ab')
self.assertEqual(ud, {'a':None, 'b':None})
# FIXME: the following won't work with UserDict, because it's an old style class
- # self.assert_(isinstance(ud, collections.UserDict))
+ # self.assertTrue(isinstance(ud, collections.UserDict))
self.assertRaises(TypeError, dict.fromkeys)
class Exc(Exception): pass
@@ -472,16 +472,16 @@ class TestMappingProtocol(BasicTestMappingProtocol):
self.assertEqual(d.copy(), {1:1, 2:2, 3:3})
d = self._empty_mapping()
self.assertEqual(d.copy(), d)
- self.assert_(isinstance(d.copy(), d.__class__))
+ self.assertTrue(isinstance(d.copy(), d.__class__))
self.assertRaises(TypeError, d.copy, None)
def test_get(self):
BasicTestMappingProtocol.test_get(self)
d = self._empty_mapping()
- self.assert_(d.get('c') is None)
+ self.assertTrue(d.get('c') is None)
self.assertEqual(d.get('c', 3), 3)
d = self._full_mapping({'a' : 1, 'b' : 2})
- self.assert_(d.get('c') is None)
+ self.assertTrue(d.get('c') is None)
self.assertEqual(d.get('c', 3), 3)
self.assertEqual(d.get('a'), 1)
self.assertEqual(d.get('a', 3), 1)
@@ -489,9 +489,9 @@ class TestMappingProtocol(BasicTestMappingProtocol):
def test_setdefault(self):
BasicTestMappingProtocol.test_setdefault(self)
d = self._empty_mapping()
- self.assert_(d.setdefault('key0') is None)
+ self.assertTrue(d.setdefault('key0') is None)
d.setdefault('key0', [])
- self.assert_(d.setdefault('key0') is None)
+ self.assertTrue(d.setdefault('key0') is None)
d.setdefault('key', []).append(3)
self.assertEqual(d['key'][0], 3)
d.setdefault('key', []).append(4)
@@ -517,9 +517,9 @@ class TestMappingProtocol(BasicTestMappingProtocol):
self.assertEqual(va, int(ka))
kb, vb = tb = b.popitem()
self.assertEqual(vb, int(kb))
- self.assert_(not(copymode < 0 and ta != tb))
- self.assert_(not a)
- self.assert_(not b)
+ self.assertTrue(not(copymode < 0 and ta != tb))
+ self.assertTrue(not a)
+ self.assertTrue(not b)
def test_pop(self):
BasicTestMappingProtocol.test_pop(self)
@@ -577,7 +577,7 @@ class TestHashMappingProtocol(TestMappingProtocol):
return collections.UserDict()
ud = mydict.fromkeys('ab')
self.assertEqual(ud, {'a':None, 'b':None})
- self.assert_(isinstance(ud, collections.UserDict))
+ self.assertTrue(isinstance(ud, collections.UserDict))
def test_pop(self):
TestMappingProtocol.test_pop(self)
diff --git a/Lib/test/pickletester.py b/Lib/test/pickletester.py
index 3ed26b8346..19704ae7ce 100644
--- a/Lib/test/pickletester.py
+++ b/Lib/test/pickletester.py
@@ -449,7 +449,7 @@ class AbstractPickleTests(unittest.TestCase):
s = self.dumps(l, proto)
x = self.loads(s)
self.assertEqual(len(x), 1)
- self.assert_(x is x[0])
+ self.assertTrue(x is x[0])
def test_recursive_tuple(self):
t = ([],)
@@ -459,7 +459,7 @@ class AbstractPickleTests(unittest.TestCase):
x = self.loads(s)
self.assertEqual(len(x), 1)
self.assertEqual(len(x[0]), 1)
- self.assert_(x is x[0][0])
+ self.assertTrue(x is x[0][0])
def test_recursive_dict(self):
d = {}
@@ -468,7 +468,7 @@ class AbstractPickleTests(unittest.TestCase):
s = self.dumps(d, proto)
x = self.loads(s)
self.assertEqual(list(x.keys()), [1])
- self.assert_(x[1] is x)
+ self.assertTrue(x[1] is x)
def test_recursive_inst(self):
i = C()
@@ -477,7 +477,7 @@ class AbstractPickleTests(unittest.TestCase):
s = self.dumps(i, 2)
x = self.loads(s)
self.assertEqual(dir(x), dir(i))
- self.assert_(x.attr is x)
+ self.assertTrue(x.attr is x)
def test_recursive_multi(self):
l = []
@@ -491,7 +491,7 @@ class AbstractPickleTests(unittest.TestCase):
self.assertEqual(len(x), 1)
self.assertEqual(dir(x[0]), dir(i))
self.assertEqual(list(x[0].attr.keys()), [1])
- self.assert_(x[0].attr[1] is x)
+ self.assertTrue(x[0].attr[1] is x)
def test_get(self):
self.assertRaises(KeyError, self.loads, b'g0\np0')
@@ -639,7 +639,7 @@ class AbstractPickleTests(unittest.TestCase):
try:
self.loads(badpickle)
except ValueError as detail:
- self.failUnless(str(detail).startswith(
+ self.assertTrue(str(detail).startswith(
"unsupported pickle protocol"))
else:
self.fail("expected bad protocol number to raise ValueError")
@@ -720,7 +720,7 @@ class AbstractPickleTests(unittest.TestCase):
for x in None, False, True:
s = self.dumps(x, proto)
y = self.loads(s)
- self.assert_(x is y, (proto, x, s, y))
+ self.assertTrue(x is y, (proto, x, s, y))
expected = expected_opcode[proto, x]
self.assertEqual(opcode_in_pickle(expected, s), True)
@@ -770,8 +770,8 @@ class AbstractPickleTests(unittest.TestCase):
# Dump using protocol 1 for comparison.
s1 = self.dumps(x, 1)
- self.assert_(__name__.encode("utf-8") in s1)
- self.assert_(b"MyList" in s1)
+ self.assertTrue(__name__.encode("utf-8") in s1)
+ self.assertTrue(b"MyList" in s1)
self.assertEqual(opcode_in_pickle(opcode, s1), False)
y = self.loads(s1)
@@ -780,8 +780,8 @@ class AbstractPickleTests(unittest.TestCase):
# Dump using protocol 2 for test.
s2 = self.dumps(x, 2)
- self.assert_(__name__.encode("utf-8") not in s2)
- self.assert_(b"MyList" not in s2)
+ self.assertTrue(__name__.encode("utf-8") not in s2)
+ self.assertTrue(b"MyList" not in s2)
self.assertEqual(opcode_in_pickle(opcode, s2), True, repr(s2))
y = self.loads(s2)
@@ -825,7 +825,7 @@ class AbstractPickleTests(unittest.TestCase):
if proto == 0:
self.assertEqual(num_appends, 0)
else:
- self.failUnless(num_appends >= 2)
+ self.assertTrue(num_appends >= 2)
def test_dict_chunking(self):
n = 10 # too small to chunk
@@ -848,7 +848,7 @@ class AbstractPickleTests(unittest.TestCase):
if proto == 0:
self.assertEqual(num_setitems, 0)
else:
- self.failUnless(num_setitems >= 2)
+ self.assertTrue(num_setitems >= 2)
def test_simple_newobj(self):
x = object.__new__(SimpleNewObj) # avoid __init__
diff --git a/Lib/test/test___all__.py b/Lib/test/test___all__.py
index 4b56749abe..8ebe568bdb 100644
--- a/Lib/test/test___all__.py
+++ b/Lib/test/test___all__.py
@@ -17,7 +17,7 @@ class AllTest(unittest.TestCase):
# Silent fail here seems the best route since some modules
# may not be available in all environments.
return
- self.failUnless(hasattr(sys.modules[modname], "__all__"),
+ self.assertTrue(hasattr(sys.modules[modname], "__all__"),
"%s has no __all__ attribute" % modname)
names = {}
exec("from %s import *" % modname, names)
diff --git a/Lib/test/test___future__.py b/Lib/test/test___future__.py
index 77006e1abc..ef81788c68 100644
--- a/Lib/test/test___future__.py
+++ b/Lib/test/test___future__.py
@@ -15,7 +15,7 @@ class FutureTest(unittest.TestCase):
for name in dir(__future__):
obj = getattr(__future__, name, None)
if obj is not None and isinstance(obj, __future__._Feature):
- self.assert_(
+ self.assertTrue(
name in given_feature_names,
"%r should have been in all_feature_names" % name
)
@@ -30,7 +30,7 @@ class FutureTest(unittest.TestCase):
optional = value.getOptionalRelease()
mandatory = value.getMandatoryRelease()
- a = self.assert_
+ a = self.assertTrue
e = self.assertEqual
def check(t, name):
a(isinstance(t, tuple), "%s isn't tuple" % name)
diff --git a/Lib/test/test_abc.py b/Lib/test/test_abc.py
index 4965c4277d..c3482d6f63 100644
--- a/Lib/test/test_abc.py
+++ b/Lib/test/test_abc.py
@@ -42,23 +42,23 @@ class TestABC(unittest.TestCase):
def bar(self): pass # concrete
self.assertEqual(C.__abstractmethods__, {"foo"})
self.assertRaises(TypeError, C) # because foo is abstract
- self.assert_(isabstract(C))
+ self.assertTrue(isabstract(C))
class D(C):
def bar(self): pass # concrete override of concrete
self.assertEqual(D.__abstractmethods__, {"foo"})
self.assertRaises(TypeError, D) # because foo is still abstract
- self.assert_(isabstract(D))
+ self.assertTrue(isabstract(D))
class E(D):
def foo(self): pass
self.assertEqual(E.__abstractmethods__, set())
E() # now foo is concrete, too
- self.failIf(isabstract(E))
+ self.assertFalse(isabstract(E))
class F(E):
@abstractthing
def bar(self): pass # abstract override of concrete
self.assertEqual(F.__abstractmethods__, {"bar"})
self.assertRaises(TypeError, F) # because bar is abstract now
- self.assert_(isabstract(F))
+ self.assertTrue(isabstract(F))
def test_subclass_oldstyle_class(self):
class A:
@@ -142,41 +142,41 @@ class TestABC(unittest.TestCase):
def test_registration_transitiveness(self):
class A(metaclass=abc.ABCMeta):
pass
- self.failUnless(issubclass(A, A))
- self.failUnless(issubclass(A, (A,)))
+ self.assertTrue(issubclass(A, A))
+ self.assertTrue(issubclass(A, (A,)))
class B(metaclass=abc.ABCMeta):
pass
- self.failIf(issubclass(A, B))
- self.failIf(issubclass(A, (B,)))
- self.failIf(issubclass(B, A))
- self.failIf(issubclass(B, (A,)))
+ self.assertFalse(issubclass(A, B))
+ self.assertFalse(issubclass(A, (B,)))
+ self.assertFalse(issubclass(B, A))
+ self.assertFalse(issubclass(B, (A,)))
class C(metaclass=abc.ABCMeta):
pass
A.register(B)
class B1(B):
pass
- self.failUnless(issubclass(B1, A))
- self.failUnless(issubclass(B1, (A,)))
+ self.assertTrue(issubclass(B1, A))
+ self.assertTrue(issubclass(B1, (A,)))
class C1(C):
pass
B1.register(C1)
- self.failIf(issubclass(C, B))
- self.failIf(issubclass(C, (B,)))
- self.failIf(issubclass(C, B1))
- self.failIf(issubclass(C, (B1,)))
- self.failUnless(issubclass(C1, A))
- self.failUnless(issubclass(C1, (A,)))
- self.failUnless(issubclass(C1, B))
- self.failUnless(issubclass(C1, (B,)))
- self.failUnless(issubclass(C1, B1))
- self.failUnless(issubclass(C1, (B1,)))
+ self.assertFalse(issubclass(C, B))
+ self.assertFalse(issubclass(C, (B,)))
+ self.assertFalse(issubclass(C, B1))
+ self.assertFalse(issubclass(C, (B1,)))
+ self.assertTrue(issubclass(C1, A))
+ self.assertTrue(issubclass(C1, (A,)))
+ self.assertTrue(issubclass(C1, B))
+ self.assertTrue(issubclass(C1, (B,)))
+ self.assertTrue(issubclass(C1, B1))
+ self.assertTrue(issubclass(C1, (B1,)))
C1.register(int)
class MyInt(int):
pass
- self.failUnless(issubclass(MyInt, A))
- self.failUnless(issubclass(MyInt, (A,)))
- self.failUnless(isinstance(42, A))
- self.failUnless(isinstance(42, (A,)))
+ self.assertTrue(issubclass(MyInt, A))
+ self.assertTrue(issubclass(MyInt, (A,)))
+ self.assertTrue(isinstance(42, A))
+ self.assertTrue(isinstance(42, (A,)))
def test_all_new_methods_are_called(self):
class A(metaclass=abc.ABCMeta):
diff --git a/Lib/test/test_abstract_numbers.py b/Lib/test/test_abstract_numbers.py
index e20f2d42c0..d0164c07b8 100644
--- a/Lib/test/test_abstract_numbers.py
+++ b/Lib/test/test_abstract_numbers.py
@@ -9,8 +9,8 @@ from test import support
class TestNumbers(unittest.TestCase):
def test_int(self):
- self.failUnless(issubclass(int, Integral))
- self.failUnless(issubclass(int, Complex))
+ self.assertTrue(issubclass(int, Integral))
+ self.assertTrue(issubclass(int, Complex))
self.assertEqual(7, int(7).real)
self.assertEqual(0, int(7).imag)
@@ -19,16 +19,16 @@ class TestNumbers(unittest.TestCase):
self.assertEqual(1, int(7).denominator)
def test_float(self):
- self.failIf(issubclass(float, Rational))
- self.failUnless(issubclass(float, Real))
+ self.assertFalse(issubclass(float, Rational))
+ self.assertTrue(issubclass(float, Real))
self.assertEqual(7.3, float(7.3).real)
self.assertEqual(0, float(7.3).imag)
self.assertEqual(7.3, float(7.3).conjugate())
def test_complex(self):
- self.failIf(issubclass(complex, Real))
- self.failUnless(issubclass(complex, Complex))
+ self.assertFalse(issubclass(complex, Real))
+ self.assertTrue(issubclass(complex, Complex))
c1, c2 = complex(3, 2), complex(4,1)
# XXX: This is not ideal, but see the comment in math_trunc().
diff --git a/Lib/test/test_array.py b/Lib/test/test_array.py
index 8e228391bc..7ae34a99a9 100755
--- a/Lib/test/test_array.py
+++ b/Lib/test/test_array.py
@@ -49,7 +49,7 @@ class BaseTest(unittest.TestCase):
def test_constructor(self):
a = array.array(self.typecode)
self.assertEqual(a.typecode, self.typecode)
- self.assert_(a.itemsize>=self.minitemsize)
+ self.assertTrue(a.itemsize>=self.minitemsize)
self.assertRaises(TypeError, array.array, self.typecode, None)
def test_len(self):
@@ -64,10 +64,10 @@ class BaseTest(unittest.TestCase):
a = array.array(self.typecode, self.example)
self.assertRaises(TypeError, a.buffer_info, 42)
bi = a.buffer_info()
- self.assert_(isinstance(bi, tuple))
+ self.assertTrue(isinstance(bi, tuple))
self.assertEqual(len(bi), 2)
- self.assert_(isinstance(bi[0], int))
- self.assert_(isinstance(bi[1], int))
+ self.assertTrue(isinstance(bi[0], int))
+ self.assertTrue(isinstance(bi[1], int))
self.assertEqual(bi[1], len(a))
def test_byteswap(self):
@@ -216,39 +216,39 @@ class BaseTest(unittest.TestCase):
def test_cmp(self):
a = array.array(self.typecode, self.example)
- self.assert_((a == 42) is False)
- self.assert_((a != 42) is True)
+ self.assertTrue((a == 42) is False)
+ self.assertTrue((a != 42) is True)
- self.assert_((a == a) is True)
- self.assert_((a != a) is False)
- self.assert_((a < a) is False)
- self.assert_((a <= a) is True)
- self.assert_((a > a) is False)
- self.assert_((a >= a) is True)
+ self.assertTrue((a == a) is True)
+ self.assertTrue((a != a) is False)
+ self.assertTrue((a < a) is False)
+ self.assertTrue((a <= a) is True)
+ self.assertTrue((a > a) is False)
+ self.assertTrue((a >= a) is True)
al = array.array(self.typecode, self.smallerexample)
ab = array.array(self.typecode, self.biggerexample)
- self.assert_((a == 2*a) is False)
- self.assert_((a != 2*a) is True)
- self.assert_((a < 2*a) is True)
- self.assert_((a <= 2*a) is True)
- self.assert_((a > 2*a) is False)
- self.assert_((a >= 2*a) is False)
-
- self.assert_((a == al) is False)
- self.assert_((a != al) is True)
- self.assert_((a < al) is False)
- self.assert_((a <= al) is False)
- self.assert_((a > al) is True)
- self.assert_((a >= al) is True)
-
- self.assert_((a == ab) is False)
- self.assert_((a != ab) is True)
- self.assert_((a < ab) is True)
- self.assert_((a <= ab) is True)
- self.assert_((a > ab) is False)
- self.assert_((a >= ab) is False)
+ self.assertTrue((a == 2*a) is False)
+ self.assertTrue((a != 2*a) is True)
+ self.assertTrue((a < 2*a) is True)
+ self.assertTrue((a <= 2*a) is True)
+ self.assertTrue((a > 2*a) is False)
+ self.assertTrue((a >= 2*a) is False)
+
+ self.assertTrue((a == al) is False)
+ self.assertTrue((a != al) is True)
+ self.assertTrue((a < al) is False)
+ self.assertTrue((a <= al) is False)
+ self.assertTrue((a > al) is True)
+ self.assertTrue((a >= al) is True)
+
+ self.assertTrue((a == ab) is False)
+ self.assertTrue((a != ab) is True)
+ self.assertTrue((a < ab) is True)
+ self.assertTrue((a <= ab) is True)
+ self.assertTrue((a > ab) is False)
+ self.assertTrue((a >= ab) is False)
def test_add(self):
a = array.array(self.typecode, self.example) \
@@ -267,7 +267,7 @@ class BaseTest(unittest.TestCase):
a = array.array(self.typecode, self.example[::-1])
b = a
a += array.array(self.typecode, 2*self.example)
- self.assert_(a is b)
+ self.assertTrue(a is b)
self.assertEqual(
a,
array.array(self.typecode, self.example[::-1]+2*self.example)
@@ -310,22 +310,22 @@ class BaseTest(unittest.TestCase):
b = a
a *= 5
- self.assert_(a is b)
+ self.assertTrue(a is b)
self.assertEqual(
a,
array.array(self.typecode, 5*self.example)
)
a *= 0
- self.assert_(a is b)
+ self.assertTrue(a is b)
self.assertEqual(a, array.array(self.typecode))
a *= 1000
- self.assert_(a is b)
+ self.assertTrue(a is b)
self.assertEqual(a, array.array(self.typecode))
a *= -1
- self.assert_(a is b)
+ self.assertTrue(a is b)
self.assertEqual(a, array.array(self.typecode))
a = array.array(self.typecode, self.example)
diff --git a/Lib/test/test_ast.py b/Lib/test/test_ast.py
index 021ae95bb2..63e9763514 100644
--- a/Lib/test/test_ast.py
+++ b/Lib/test/test_ast.py
@@ -116,20 +116,20 @@ eval_tests = [
class AST_Tests(unittest.TestCase):
- def _assert_order(self, ast_node, parent_pos):
+ def _assertTrueorder(self, ast_node, parent_pos):
if not isinstance(ast_node, ast.AST) or ast_node._fields is None:
return
if isinstance(ast_node, (ast.expr, ast.stmt, ast.excepthandler)):
node_pos = (ast_node.lineno, ast_node.col_offset)
- self.assert_(node_pos >= parent_pos)
+ self.assertTrue(node_pos >= parent_pos)
parent_pos = (ast_node.lineno, ast_node.col_offset)
for name in ast_node._fields:
value = getattr(ast_node, name)
if isinstance(value, list):
for child in value:
- self._assert_order(child, parent_pos)
+ self._assertTrueorder(child, parent_pos)
elif value is not None:
- self._assert_order(value, parent_pos)
+ self._assertTrueorder(value, parent_pos)
def test_snippets(self):
for input, output, kind in ((exec_tests, exec_results, "exec"),
@@ -138,7 +138,7 @@ class AST_Tests(unittest.TestCase):
for i, o in zip(input, output):
ast_tree = compile(i, "?", kind, ast.PyCF_ONLY_AST)
self.assertEquals(to_tuple(ast_tree), o)
- self._assert_order(ast_tree, (0, 0))
+ self._assertTrueorder(ast_tree, (0, 0))
def test_slice(self):
slc = ast.parse("x[::]").body[0].value.slice
diff --git a/Lib/test/test_augassign.py b/Lib/test/test_augassign.py
index e03b4d4e5c..8567821c88 100644
--- a/Lib/test/test_augassign.py
+++ b/Lib/test/test_augassign.py
@@ -60,7 +60,7 @@ class AugAssignTest(unittest.TestCase):
y[1:2] += [1]
self.assertEquals(x, [1, 2, 1, 2, 3])
- self.assert_(x is y)
+ self.assertTrue(x is y)
def testCustomMethods1(self):
@@ -85,23 +85,23 @@ class AugAssignTest(unittest.TestCase):
y = x
x += 10
- self.assert_(isinstance(x, aug_test))
- self.assert_(y is not x)
+ self.assertTrue(isinstance(x, aug_test))
+ self.assertTrue(y is not x)
self.assertEquals(x.val, 11)
x = aug_test2(2)
y = x
x += 10
- self.assert_(y is x)
+ self.assertTrue(y is x)
self.assertEquals(x.val, 12)
x = aug_test3(3)
y = x
x += 10
- self.assert_(isinstance(x, aug_test3))
- self.assert_(y is not x)
+ self.assertTrue(isinstance(x, aug_test3))
+ self.assertTrue(y is not x)
self.assertEquals(x.val, 13)
diff --git a/Lib/test/test_base64.py b/Lib/test/test_base64.py
index 149ac8ada1..fadee6df67 100644
--- a/Lib/test/test_base64.py
+++ b/Lib/test/test_base64.py
@@ -204,7 +204,7 @@ class BaseXYTestCase(unittest.TestCase):
self.assertRaises(TypeError, base64.b16decode, "")
def test_ErrorHeritage(self):
- self.assert_(issubclass(binascii.Error, ValueError))
+ self.assertTrue(issubclass(binascii.Error, ValueError))
diff --git a/Lib/test/test_bigmem.py b/Lib/test/test_bigmem.py
index 091893e7fe..030ada50c6 100644
--- a/Lib/test/test_bigmem.py
+++ b/Lib/test/test_bigmem.py
@@ -80,12 +80,12 @@ class BaseStrTest:
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
s = _('-') * size + SUBSTR
- self.failUnless(s.endswith(SUBSTR))
- self.failUnless(s.endswith(s))
+ self.assertTrue(s.endswith(SUBSTR))
+ self.assertTrue(s.endswith(s))
s2 = _('...') + s
- self.failUnless(s2.endswith(s))
- self.failIf(s.endswith(_('a') + SUBSTR))
- self.failIf(SUBSTR.endswith(s))
+ self.assertTrue(s2.endswith(s))
+ self.assertFalse(s.endswith(_('a') + SUBSTR))
+ self.assertFalse(SUBSTR.endswith(s))
@bigmemtest(minsize=_2G + 10, memuse=2)
def test_expandtabs(self, size):
@@ -139,27 +139,27 @@ class BaseStrTest:
_ = self.from_latin1
SUBSTR = _('123456')
s = _('a') * size + SUBSTR
- self.failUnless(s.isalnum())
+ self.assertTrue(s.isalnum())
s += _('.')
- self.failIf(s.isalnum())
+ self.assertFalse(s.isalnum())
@bigmemtest(minsize=_2G, memuse=2)
def test_isalpha(self, size):
_ = self.from_latin1
SUBSTR = _('zzzzzzz')
s = _('a') * size + SUBSTR
- self.failUnless(s.isalpha())
+ self.assertTrue(s.isalpha())
s += _('.')
- self.failIf(s.isalpha())
+ self.assertFalse(s.isalpha())
@bigmemtest(minsize=_2G, memuse=2)
def test_isdigit(self, size):
_ = self.from_latin1
SUBSTR = _('123456')
s = _('9') * size + SUBSTR
- self.failUnless(s.isdigit())
+ self.assertTrue(s.isdigit())
s += _('z')
- self.failIf(s.isdigit())
+ self.assertFalse(s.isdigit())
@bigmemtest(minsize=_2G, memuse=2)
def test_islower(self, size):
@@ -168,9 +168,9 @@ class BaseStrTest:
chr(c) for c in range(255) if not chr(c).isupper()))
repeats = size // len(chars) + 2
s = chars * repeats
- self.failUnless(s.islower())
+ self.assertTrue(s.islower())
s += _('A')
- self.failIf(s.islower())
+ self.assertFalse(s.islower())
@bigmemtest(minsize=_2G, memuse=2)
def test_isspace(self, size):
@@ -178,20 +178,20 @@ class BaseStrTest:
whitespace = _(' \f\n\r\t\v')
repeats = size // len(whitespace) + 2
s = whitespace * repeats
- self.failUnless(s.isspace())
+ self.assertTrue(s.isspace())
s += _('j')
- self.failIf(s.isspace())
+ self.assertFalse(s.isspace())
@bigmemtest(minsize=_2G, memuse=2)
def test_istitle(self, size):
_ = self.from_latin1
SUBSTR = _('123456')
s = _('').join([_('A'), _('a') * size, SUBSTR])
- self.failUnless(s.istitle())
+ self.assertTrue(s.istitle())
s += _('A')
- self.failUnless(s.istitle())
+ self.assertTrue(s.istitle())
s += _('aA')
- self.failIf(s.istitle())
+ self.assertFalse(s.istitle())
@bigmemtest(minsize=_2G, memuse=2)
def test_isupper(self, size):
@@ -200,9 +200,9 @@ class BaseStrTest:
chr(c) for c in range(255) if not chr(c).islower()))
repeats = size // len(chars) + 2
s = chars * repeats
- self.failUnless(s.isupper())
+ self.assertTrue(s.isupper())
s += _('a')
- self.failIf(s.isupper())
+ self.assertFalse(s.isupper())
@bigmemtest(minsize=_2G, memuse=2)
def test_join(self, size):
@@ -211,15 +211,15 @@ class BaseStrTest:
x = s.join([_('aaaaa'), _('bbbbb')])
self.assertEquals(x.count(_('a')), 5)
self.assertEquals(x.count(_('b')), 5)
- self.failUnless(x.startswith(_('aaaaaA')))
- self.failUnless(x.endswith(_('Abbbbb')))
+ self.assertTrue(x.startswith(_('aaaaaA')))
+ self.assertTrue(x.endswith(_('Abbbbb')))
@bigmemtest(minsize=_2G + 10, memuse=1)
def test_ljust(self, size):
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
s = SUBSTR.ljust(size)
- self.failUnless(s.startswith(SUBSTR + _(' ')))
+ self.assertTrue(s.startswith(SUBSTR + _(' ')))
self.assertEquals(len(s), size)
self.assertEquals(s.strip(), SUBSTR.strip())
@@ -244,7 +244,7 @@ class BaseStrTest:
# Type-specific optimization
if isinstance(s, (str, bytes)):
stripped = s.lstrip()
- self.failUnless(stripped is s)
+ self.assertTrue(stripped is s)
@bigmemtest(minsize=_2G + 10, memuse=2)
def test_replace(self, size):
@@ -299,7 +299,7 @@ class BaseStrTest:
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
s = SUBSTR.ljust(size)
- self.failUnless(s.startswith(SUBSTR + _(' ')))
+ self.assertTrue(s.startswith(SUBSTR + _(' ')))
self.assertEquals(len(s), size)
self.assertEquals(s.strip(), SUBSTR.strip())
@@ -316,7 +316,7 @@ class BaseStrTest:
# Type-specific optimization
if isinstance(s, (str, bytes)):
stripped = s.rstrip()
- self.failUnless(stripped is s)
+ self.assertTrue(stripped is s)
# The test takes about size bytes to build a string, and then about
# sqrt(size) substrings of sqrt(size) in size and a list to
@@ -378,9 +378,9 @@ class BaseStrTest:
_ = self.from_latin1
SUBSTR = _(' abc def ghi')
s = _('-') * size + SUBSTR
- self.failUnless(s.startswith(s))
- self.failUnless(s.startswith(_('-') * size))
- self.failIf(s.startswith(SUBSTR))
+ self.assertTrue(s.startswith(s))
+ self.assertTrue(s.startswith(_('-') * size))
+ self.assertFalse(s.startswith(SUBSTR))
@bigmemtest(minsize=_2G, memuse=1)
def test_strip(self, size):
@@ -412,8 +412,8 @@ class BaseStrTest:
SUBSTR = _('SpaaHAaaAaham')
s = SUBSTR * (size // len(SUBSTR) + 2)
s = s.title()
- self.failUnless(s.startswith((SUBSTR * 3).title()))
- self.failUnless(s.endswith(SUBSTR.lower() * 3))
+ self.assertTrue(s.startswith((SUBSTR * 3).title()))
+ self.assertTrue(s.endswith(SUBSTR.lower() * 3))
@bigmemtest(minsize=_2G, memuse=2)
def test_translate(self, size):
@@ -451,8 +451,8 @@ class BaseStrTest:
_ = self.from_latin1
SUBSTR = _('-568324723598234')
s = SUBSTR.zfill(size)
- self.failUnless(s.endswith(_('0') + SUBSTR[1:]))
- self.failUnless(s.startswith(_('-0')))
+ self.assertTrue(s.endswith(_('0') + SUBSTR[1:]))
+ self.assertTrue(s.startswith(_('-0')))
self.assertEquals(len(s), size)
self.assertEquals(s.count(_('0')), size - len(SUBSTR))
@@ -519,12 +519,12 @@ class BaseStrTest:
edge = _('-') * (size // 2)
s = _('').join([edge, SUBSTR, edge])
del edge
- self.failUnless(SUBSTR in s)
- self.failIf(SUBSTR * 2 in s)
- self.failUnless(_('-') in s)
- self.failIf(_('a') in s)
+ self.assertTrue(SUBSTR in s)
+ self.assertFalse(SUBSTR * 2 in s)
+ self.assertTrue(_('-') in s)
+ self.assertFalse(_('a') in s)
s += _('a')
- self.failUnless(_('a') in s)
+ self.assertTrue(_('a') in s)
@bigmemtest(minsize=_2G + 10, memuse=2)
def test_compare(self, size):
@@ -534,10 +534,10 @@ class BaseStrTest:
self.assertEqual(s1, s2)
del s2
s2 = s1 + _('a')
- self.failIf(s1 == s2)
+ self.assertFalse(s1 == s2)
del s2
s2 = _('.') * size
- self.failIf(s1 == s2)
+ self.assertFalse(s1 == s2)
@bigmemtest(minsize=_2G + 10, memuse=1)
def test_hash(self, size):
@@ -552,7 +552,7 @@ class BaseStrTest:
h1 = hash(s)
del s
s = _('\x00') * (size + 1)
- self.failIf(h1 == hash(s))
+ self.assertFalse(h1 == hash(s))
class StrTest(unittest.TestCase, BaseStrTest):
@@ -623,7 +623,7 @@ class StrTest(unittest.TestCase, BaseStrTest):
except MemoryError:
pass # acceptable on 32-bit
else:
- self.failUnless(s == eval(r))
+ self.assertTrue(s == eval(r))
@bigmemtest(minsize=_2G + 10, memuse=character_size * 2)
def test_format(self, size):
@@ -633,8 +633,8 @@ class StrTest(unittest.TestCase, BaseStrTest):
del sf
sf = '..%s..' % (s,)
self.assertEquals(len(sf), len(s) + 4)
- self.failUnless(sf.startswith('..-'))
- self.failUnless(sf.endswith('-..'))
+ self.assertTrue(sf.startswith('..-'))
+ self.assertTrue(sf.endswith('-..'))
del s, sf
size //= 2
@@ -682,8 +682,8 @@ class StrTest(unittest.TestCase, BaseStrTest):
s = "\uAAAA" * size
for f in (repr, ascii):
r = f(s)
- self.failUnless(len(r) > size)
- self.failUnless(r.endswith(r"\uaaaa'"), r[-10:])
+ self.assertTrue(len(r) > size)
+ self.assertTrue(r.endswith(r"\uaaaa'"), r[-10:])
del r
# The character takes 4 bytes even in UCS-2 builds because it will
@@ -693,8 +693,8 @@ class StrTest(unittest.TestCase, BaseStrTest):
s = "\U0001AAAA" * size
for f in (repr, ascii):
r = f(s)
- self.failUnless(len(r) > size)
- self.failUnless(r.endswith(r"\U0001aaaa'"), r[-12:])
+ self.assertTrue(len(r) > size)
+ self.assertTrue(r.endswith(r"\U0001aaaa'"), r[-12:])
del r
@@ -740,10 +740,10 @@ class TupleTest(unittest.TestCase):
self.assertEqual(t1, t2)
del t2
t2 = ('',) * (size + 1)
- self.failIf(t1 == t2)
+ self.assertFalse(t1 == t2)
del t2
t2 = (1,) * size
- self.failIf(t1 == t2)
+ self.assertFalse(t1 == t2)
# Test concatenating into a single tuple of more than 2G in length,
# and concatenating a tuple of more than 2G in length separately, so
@@ -768,9 +768,9 @@ class TupleTest(unittest.TestCase):
def test_contains(self, size):
t = (1, 2, 3, 4, 5) * size
self.assertEquals(len(t), size * 5)
- self.failUnless(5 in t)
- self.failIf((1, 2, 3, 4, 5) in t)
- self.failIf(0 in t)
+ self.assertTrue(5 in t)
+ self.assertFalse((1, 2, 3, 4, 5) in t)
+ self.assertFalse(0 in t)
@bigmemtest(minsize=_2G + 10, memuse=8)
def test_hash(self, size):
@@ -778,7 +778,7 @@ class TupleTest(unittest.TestCase):
h1 = hash(t1)
del t1
t2 = (0,) * (size + 1)
- self.failIf(h1 == hash(t2))
+ self.assertFalse(h1 == hash(t2))
@bigmemtest(minsize=_2G + 10, memuse=8)
def test_index_and_slice(self, size):
@@ -874,10 +874,10 @@ class ListTest(unittest.TestCase):
self.assertEqual(l1, l2)
del l2
l2 = [''] * (size + 1)
- self.failIf(l1 == l2)
+ self.assertFalse(l1 == l2)
del l2
l2 = [2] * size
- self.failIf(l1 == l2)
+ self.assertFalse(l1 == l2)
# Test concatenating into a single list of more than 2G in length,
# and concatenating a list of more than 2G in length separately, so
@@ -902,8 +902,8 @@ class ListTest(unittest.TestCase):
l = [sys.stdout] * size
l += l
self.assertEquals(len(l), size * 2)
- self.failUnless(l[0] is l[-1])
- self.failUnless(l[size - 1] is l[size + 1])
+ self.assertTrue(l[0] is l[-1])
+ self.assertTrue(l[size - 1] is l[size + 1])
@bigmemtest(minsize=_2G // 2 + 2, memuse=24)
def test_inplace_concat_small(self, size):
@@ -917,14 +917,14 @@ class ListTest(unittest.TestCase):
def test_contains(self, size):
l = [1, 2, 3, 4, 5] * size
self.assertEquals(len(l), size * 5)
- self.failUnless(5 in l)
- self.failIf([1, 2, 3, 4, 5] in l)
- self.failIf(0 in l)
+ self.assertTrue(5 in l)
+ self.assertFalse([1, 2, 3, 4, 5] in l)
+ self.assertFalse(0 in l)
@bigmemtest(minsize=_2G + 10, memuse=8)
def test_hash(self, size):
l = [0] * size
- self.failUnlessRaises(TypeError, hash, l)
+ self.assertRaises(TypeError, hash, l)
@bigmemtest(minsize=_2G + 10, memuse=8)
def test_index_and_slice(self, size):
@@ -984,7 +984,7 @@ class ListTest(unittest.TestCase):
# Like test_concat, split in two.
def basic_test_repeat(self, size):
l = [] * size
- self.failIf(l)
+ self.assertFalse(l)
l = [''] * size
self.assertEquals(len(l), size)
l = l * 2
@@ -1002,13 +1002,13 @@ class ListTest(unittest.TestCase):
l = ['']
l *= size
self.assertEquals(len(l), size)
- self.failUnless(l[0] is l[-1])
+ self.assertTrue(l[0] is l[-1])
del l
l = [''] * size
l *= 2
self.assertEquals(len(l), size * 2)
- self.failUnless(l[size - 1] is l[-1])
+ self.assertTrue(l[size - 1] is l[-1])
@bigmemtest(minsize=_2G // 2 + 2, memuse=16)
def test_inplace_repeat_small(self, size):
@@ -1042,8 +1042,8 @@ class ListTest(unittest.TestCase):
l = [object()] * size
l.append(object())
self.assertEquals(len(l), size+1)
- self.failUnless(l[-3] is l[-2])
- self.failIf(l[-2] is l[-1])
+ self.assertTrue(l[-3] is l[-2])
+ self.assertFalse(l[-2] is l[-1])
@bigmemtest(minsize=_2G // 5 + 2, memuse=8 * 5)
def test_count(self, size):
@@ -1055,8 +1055,8 @@ class ListTest(unittest.TestCase):
l = [object] * size
l.extend(l)
self.assertEquals(len(l), size * 2)
- self.failUnless(l[0] is l[-1])
- self.failUnless(l[size - 1] is l[size + 1])
+ self.assertTrue(l[0] is l[-1])
+ self.assertTrue(l[size - 1] is l[size + 1])
@bigmemtest(minsize=_2G // 2 + 2, memuse=16)
def test_extend_small(self, size):
diff --git a/Lib/test/test_binascii.py b/Lib/test/test_binascii.py
index d4ab6bf67b..65de81b8c1 100755
--- a/Lib/test/test_binascii.py
+++ b/Lib/test/test_binascii.py
@@ -14,8 +14,8 @@ class BinASCIITest(unittest.TestCase):
def test_exceptions(self):
# Check module exceptions
- self.assert_(issubclass(binascii.Error, Exception))
- self.assert_(issubclass(binascii.Incomplete, Exception))
+ self.assertTrue(issubclass(binascii.Error, Exception))
+ self.assertTrue(issubclass(binascii.Incomplete, Exception))
def test_functions(self):
# Check presence of all functions
@@ -26,10 +26,10 @@ class BinASCIITest(unittest.TestCase):
prefixes.extend(["crc_", "rlecode_", "rledecode_"])
for prefix in prefixes:
name = prefix + suffix
- self.assert_(hasattr(getattr(binascii, name), '__call__'))
+ self.assertTrue(hasattr(getattr(binascii, name), '__call__'))
self.assertRaises(TypeError, getattr(binascii, name))
for name in ("hexlify", "unhexlify"):
- self.assert_(hasattr(getattr(binascii, name), '__call__'))
+ self.assertTrue(hasattr(getattr(binascii, name), '__call__'))
self.assertRaises(TypeError, getattr(binascii, name))
def test_base64valid(self):
diff --git a/Lib/test/test_binop.py b/Lib/test/test_binop.py
index 0dc18dd93a..5d77f234fe 100644
--- a/Lib/test/test_binop.py
+++ b/Lib/test/test_binop.py
@@ -210,10 +210,10 @@ class RatTestCase(unittest.TestCase):
self.assertEqual(gcd(-10, -2), -2)
for i in range(1, 20):
for j in range(1, 20):
- self.assert_(gcd(i, j) > 0)
- self.assert_(gcd(-i, j) < 0)
- self.assert_(gcd(i, -j) > 0)
- self.assert_(gcd(-i, -j) < 0)
+ self.assertTrue(gcd(i, j) > 0)
+ self.assertTrue(gcd(-i, j) < 0)
+ self.assertTrue(gcd(i, -j) > 0)
+ self.assertTrue(gcd(-i, -j) < 0)
def test_constructor(self):
a = Rat(10, 15)
diff --git a/Lib/test/test_bisect.py b/Lib/test/test_bisect.py
index df2f8b1ddd..93b86137ac 100644
--- a/Lib/test/test_bisect.py
+++ b/Lib/test/test_bisect.py
@@ -130,14 +130,14 @@ class TestBisect(unittest.TestCase):
elem = randrange(-1, n+1)
ip = self.module.bisect_left(data, elem)
if ip < len(data):
- self.failUnless(elem <= data[ip])
+ self.assertTrue(elem <= data[ip])
if ip > 0:
- self.failUnless(data[ip-1] < elem)
+ self.assertTrue(data[ip-1] < elem)
ip = self.module.bisect_right(data, elem)
if ip < len(data):
- self.failUnless(elem < data[ip])
+ self.assertTrue(elem < data[ip])
if ip > 0:
- self.failUnless(data[ip-1] <= elem)
+ self.assertTrue(data[ip-1] <= elem)
def test_optionalSlicing(self):
for func, data, elem, expected in self.precomputedCases:
@@ -146,15 +146,15 @@ class TestBisect(unittest.TestCase):
for hi in range(3,8):
hi = min(len(data), hi)
ip = func(data, elem, lo, hi)
- self.failUnless(lo <= ip <= hi)
+ self.assertTrue(lo <= ip <= hi)
if func is self.module.bisect_left and ip < hi:
- self.failUnless(elem <= data[ip])
+ self.assertTrue(elem <= data[ip])
if func is self.module.bisect_left and ip > lo:
- self.failUnless(data[ip-1] < elem)
+ self.assertTrue(data[ip-1] < elem)
if func is self.module.bisect_right and ip < hi:
- self.failUnless(elem < data[ip])
+ self.assertTrue(elem < data[ip])
if func is self.module.bisect_right and ip > lo:
- self.failUnless(data[ip-1] <= elem)
+ self.assertTrue(data[ip-1] <= elem)
self.assertEqual(ip, max(lo, min(hi, expected)))
def test_backcompatibility(self):
diff --git a/Lib/test/test_bool.py b/Lib/test/test_bool.py
index 80229aa1f9..3a68dfce22 100644
--- a/Lib/test/test_bool.py
+++ b/Lib/test/test_bool.py
@@ -8,10 +8,10 @@ import os
class BoolTest(unittest.TestCase):
def assertIs(self, a, b):
- self.assert_(a is b)
+ self.assertTrue(a is b)
def assertIsNot(self, a, b):
- self.assert_(a is not b)
+ self.assertTrue(a is not b)
def test_subclass(self):
try:
@@ -221,15 +221,15 @@ class BoolTest(unittest.TestCase):
def test_boolean(self):
self.assertEqual(True & 1, 1)
- self.assert_(not isinstance(True & 1, bool))
+ self.assertTrue(not isinstance(True & 1, bool))
self.assertIs(True & True, True)
self.assertEqual(True | 1, 1)
- self.assert_(not isinstance(True | 1, bool))
+ self.assertTrue(not isinstance(True | 1, bool))
self.assertIs(True | True, True)
self.assertEqual(True ^ 1, 0)
- self.assert_(not isinstance(True ^ 1, bool))
+ self.assertTrue(not isinstance(True ^ 1, bool))
self.assertIs(True ^ True, False)
def test_fileclosed(self):
diff --git a/Lib/test/test_bufio.py b/Lib/test/test_bufio.py
index 7d617d3414..5ab6f5a0da 100644
--- a/Lib/test/test_bufio.py
+++ b/Lib/test/test_bufio.py
@@ -34,7 +34,7 @@ class BufferSizeTest(unittest.TestCase):
line = f.readline()
self.assertEqual(line, s)
line = f.readline()
- self.assert_(not line) # Must be at EOF
+ self.assertTrue(not line) # Must be at EOF
f.close()
finally:
support.unlink(support.TESTFN)
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index fdb0ea28f5..28fd9388f7 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -176,24 +176,24 @@ class BuiltinTest(unittest.TestCase):
def test_neg(self):
x = -sys.maxsize-1
- self.assert_(isinstance(x, int))
+ self.assertTrue(isinstance(x, int))
self.assertEqual(-x, sys.maxsize+1)
# XXX(nnorwitz): This test case for callable should probably be removed.
def test_callable(self):
- self.assert_(hasattr(len, '__call__'))
+ self.assertTrue(hasattr(len, '__call__'))
def f(): pass
- self.assert_(hasattr(f, '__call__'))
+ self.assertTrue(hasattr(f, '__call__'))
class C:
def meth(self): pass
- self.assert_(hasattr(C, '__call__'))
+ self.assertTrue(hasattr(C, '__call__'))
x = C()
- self.assert_(hasattr(x.meth, '__call__'))
- self.assert_(not hasattr(x, '__call__'))
+ self.assertTrue(hasattr(x.meth, '__call__'))
+ self.assertTrue(not hasattr(x, '__call__'))
class D(C):
def __call__(self): pass
y = D()
- self.assert_(hasattr(y, '__call__'))
+ self.assertTrue(hasattr(y, '__call__'))
y()
def test_chr(self):
@@ -220,7 +220,7 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises((OverflowError, ValueError), chr, 2**32)
def test_cmp(self):
- self.assert_(not hasattr(builtins, "cmp"))
+ self.assertTrue(not hasattr(builtins, "cmp"))
def test_compile(self):
compile('print(1)\n', '', 'exec')
@@ -252,11 +252,11 @@ class BuiltinTest(unittest.TestCase):
# dir() - local scope
local_var = 1
- self.assert_('local_var' in dir())
+ self.assertTrue('local_var' in dir())
# dir(module)
import sys
- self.assert_('exit' in dir(sys))
+ self.assertTrue('exit' in dir(sys))
# dir(module_with_invalid__dict__)
import types
@@ -266,8 +266,8 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(TypeError, dir, f)
# dir(type)
- self.assert_("strip" in dir(str))
- self.assert_("__mro__" not in dir(str))
+ self.assertTrue("strip" in dir(str))
+ self.assertTrue("__mro__" not in dir(str))
# dir(obj)
class Foo(object):
@@ -276,13 +276,13 @@ class BuiltinTest(unittest.TestCase):
self.y = 8
self.z = 9
f = Foo()
- self.assert_("y" in dir(f))
+ self.assertTrue("y" in dir(f))
# dir(obj_no__dict__)
class Foo(object):
__slots__ = []
f = Foo()
- self.assert_("__repr__" in dir(f))
+ self.assertTrue("__repr__" in dir(f))
# dir(obj_no__class__with__dict__)
# (an ugly trick to cause getattr(f, "__class__") to fail)
@@ -291,15 +291,15 @@ class BuiltinTest(unittest.TestCase):
def __init__(self):
self.bar = "wow"
f = Foo()
- self.assert_("__repr__" not in dir(f))
- self.assert_("bar" in dir(f))
+ self.assertTrue("__repr__" not in dir(f))
+ self.assertTrue("bar" in dir(f))
# dir(obj_using __dir__)
class Foo(object):
def __dir__(self):
return ["kan", "ga", "roo"]
f = Foo()
- self.assert_(dir(f) == ["ga", "kan", "roo"])
+ self.assertTrue(dir(f) == ["ga", "kan", "roo"])
# dir(obj__dir__not_list)
class Foo(object):
@@ -334,10 +334,10 @@ class BuiltinTest(unittest.TestCase):
self.assertEqual(divmod(-sys.maxsize-1, -1),
(sys.maxsize+1, 0))
- self.assert_(not fcmp(divmod(3.25, 1.0), (3.0, 0.25)))
- self.assert_(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)))
- self.assert_(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75)))
- self.assert_(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25)))
+ self.assertTrue(not fcmp(divmod(3.25, 1.0), (3.0, 0.25)))
+ self.assertTrue(not fcmp(divmod(-3.25, 1.0), (-4.0, 0.75)))
+ self.assertTrue(not fcmp(divmod(3.25, -1.0), (-4.0, -0.75)))
+ self.assertTrue(not fcmp(divmod(-3.25, -1.0), (3.0, -0.25)))
self.assertRaises(TypeError, divmod)
@@ -489,7 +489,7 @@ class BuiltinTest(unittest.TestCase):
def test_getattr(self):
import sys
- self.assert_(getattr(sys, 'stdout') is sys.stdout)
+ self.assertTrue(getattr(sys, 'stdout') is sys.stdout)
self.assertRaises(TypeError, getattr, sys, 1)
self.assertRaises(TypeError, getattr, sys, 1, "foo")
self.assertRaises(TypeError, getattr)
@@ -497,7 +497,7 @@ class BuiltinTest(unittest.TestCase):
def test_hasattr(self):
import sys
- self.assert_(hasattr(sys, 'stdout'))
+ self.assertTrue(hasattr(sys, 'stdout'))
self.assertRaises(TypeError, hasattr, sys, 1)
self.assertRaises(TypeError, hasattr)
self.assertEqual(False, hasattr(sys, chr(sys.maxunicode)))
@@ -575,11 +575,11 @@ class BuiltinTest(unittest.TestCase):
c = C()
d = D()
e = E()
- self.assert_(isinstance(c, C))
- self.assert_(isinstance(d, C))
- self.assert_(not isinstance(e, C))
- self.assert_(not isinstance(c, D))
- self.assert_(not isinstance('foo', E))
+ self.assertTrue(isinstance(c, C))
+ self.assertTrue(isinstance(d, C))
+ self.assertTrue(not isinstance(e, C))
+ self.assertTrue(not isinstance(c, D))
+ self.assertTrue(not isinstance('foo', E))
self.assertRaises(TypeError, isinstance, E, 'foo')
self.assertRaises(TypeError, isinstance)
@@ -593,9 +593,9 @@ class BuiltinTest(unittest.TestCase):
c = C()
d = D()
e = E()
- self.assert_(issubclass(D, C))
- self.assert_(issubclass(C, C))
- self.assert_(not issubclass(C, D))
+ self.assertTrue(issubclass(D, C))
+ self.assertTrue(issubclass(C, C))
+ self.assertTrue(not issubclass(C, D))
self.assertRaises(TypeError, issubclass, 'foo', E)
self.assertRaises(TypeError, issubclass, E, 'foo')
self.assertRaises(TypeError, issubclass)
@@ -958,18 +958,18 @@ class BuiltinTest(unittest.TestCase):
self.assertEqual(list(range(a+4, a, -2)), [a+4, a+2])
seq = list(range(a, b, c))
- self.assert_(a in seq)
- self.assert_(b not in seq)
+ self.assertTrue(a in seq)
+ self.assertTrue(b not in seq)
self.assertEqual(len(seq), 2)
seq = list(range(b, a, -c))
- self.assert_(b in seq)
- self.assert_(a not in seq)
+ self.assertTrue(b in seq)
+ self.assertTrue(a not in seq)
self.assertEqual(len(seq), 2)
seq = list(range(-a, -b, -c))
- self.assert_(-a in seq)
- self.assert_(-b not in seq)
+ self.assertTrue(-a in seq)
+ self.assertTrue(-b not in seq)
self.assertEqual(len(seq), 2)
self.assertRaises(TypeError, range)
diff --git a/Lib/test/test_bytes.py b/Lib/test/test_bytes.py
index 992f3d2eec..caea9094b1 100644
--- a/Lib/test/test_bytes.py
+++ b/Lib/test/test_bytes.py
@@ -102,22 +102,22 @@ class BaseBytesTest(unittest.TestCase):
b3 = self.type2test([1, 3])
self.assertEqual(b1, b2)
- self.failUnless(b2 != b3)
- self.failUnless(b1 <= b2)
- self.failUnless(b1 <= b3)
- self.failUnless(b1 < b3)
- self.failUnless(b1 >= b2)
- self.failUnless(b3 >= b2)
- self.failUnless(b3 > b2)
-
- self.failIf(b1 != b2)
- self.failIf(b2 == b3)
- self.failIf(b1 > b2)
- self.failIf(b1 > b3)
- self.failIf(b1 >= b3)
- self.failIf(b1 < b2)
- self.failIf(b3 < b2)
- self.failIf(b3 <= b2)
+ self.assertTrue(b2 != b3)
+ self.assertTrue(b1 <= b2)
+ self.assertTrue(b1 <= b3)
+ self.assertTrue(b1 < b3)
+ self.assertTrue(b1 >= b2)
+ self.assertTrue(b3 >= b2)
+ self.assertTrue(b3 > b2)
+
+ self.assertFalse(b1 != b2)
+ self.assertFalse(b2 == b3)
+ self.assertFalse(b1 > b2)
+ self.assertFalse(b1 > b3)
+ self.assertFalse(b1 >= b3)
+ self.assertFalse(b1 < b2)
+ self.assertFalse(b3 < b2)
+ self.assertFalse(b3 <= b2)
def test_compare_to_str(self):
warnings.simplefilter('ignore', BytesWarning)
@@ -220,27 +220,27 @@ class BaseBytesTest(unittest.TestCase):
def test_contains(self):
b = self.type2test(b"abc")
- self.failUnless(ord('a') in b)
- self.failUnless(int(ord('a')) in b)
- self.failIf(200 in b)
- self.failIf(200 in b)
+ self.assertTrue(ord('a') in b)
+ self.assertTrue(int(ord('a')) in b)
+ self.assertFalse(200 in b)
+ self.assertFalse(200 in b)
self.assertRaises(ValueError, lambda: 300 in b)
self.assertRaises(ValueError, lambda: -1 in b)
self.assertRaises(TypeError, lambda: None in b)
self.assertRaises(TypeError, lambda: float(ord('a')) in b)
self.assertRaises(TypeError, lambda: "a" in b)
for f in bytes, bytearray:
- self.failUnless(f(b"") in b)
- self.failUnless(f(b"a") in b)
- self.failUnless(f(b"b") in b)
- self.failUnless(f(b"c") in b)
- self.failUnless(f(b"ab") in b)
- self.failUnless(f(b"bc") in b)
- self.failUnless(f(b"abc") in b)
- self.failIf(f(b"ac") in b)
- self.failIf(f(b"d") in b)
- self.failIf(f(b"dab") in b)
- self.failIf(f(b"abd") in b)
+ self.assertTrue(f(b"") in b)
+ self.assertTrue(f(b"a") in b)
+ self.assertTrue(f(b"b") in b)
+ self.assertTrue(f(b"c") in b)
+ self.assertTrue(f(b"ab") in b)
+ self.assertTrue(f(b"bc") in b)
+ self.assertTrue(f(b"abc") in b)
+ self.assertFalse(f(b"ac") in b)
+ self.assertFalse(f(b"d") in b)
+ self.assertFalse(f(b"dab") in b)
+ self.assertFalse(f(b"abd") in b)
def test_fromhex(self):
self.assertRaises(TypeError, self.type2test.fromhex)
@@ -626,7 +626,7 @@ class ByteArrayTest(BaseBytesTest):
b += b"def"
self.assertEqual(b, b"abcdef")
self.assertEqual(b, b1)
- self.failUnless(b is b1)
+ self.assertTrue(b is b1)
b += b"xyz"
self.assertEqual(b, b"abcdefxyz")
try:
@@ -642,7 +642,7 @@ class ByteArrayTest(BaseBytesTest):
b *= 3
self.assertEqual(b, b"abcabcabc")
self.assertEqual(b, b1)
- self.failUnless(b is b1)
+ self.assertTrue(b is b1)
def test_irepeat_1char(self):
b = bytearray(b"x")
@@ -650,17 +650,17 @@ class ByteArrayTest(BaseBytesTest):
b *= 100
self.assertEqual(b, b"x"*100)
self.assertEqual(b, b1)
- self.failUnless(b is b1)
+ self.assertTrue(b is b1)
def test_alloc(self):
b = bytearray()
alloc = b.__alloc__()
- self.assert_(alloc >= 0)
+ self.assertTrue(alloc >= 0)
seq = [alloc]
for i in range(100):
b += b"x"
alloc = b.__alloc__()
- self.assert_(alloc >= len(b))
+ self.assertTrue(alloc >= len(b))
if alloc not in seq:
seq.append(alloc)
@@ -759,7 +759,7 @@ class ByteArrayTest(BaseBytesTest):
a, b, c = bytearray(b"x").partition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
- self.assert_(b is not c)
+ self.assertTrue(b is not c)
b += b"!"
self.assertEqual(c, b"")
a, b, c = bytearray(b"x").partition(b"y")
@@ -769,7 +769,7 @@ class ByteArrayTest(BaseBytesTest):
b, c, a = bytearray(b"x").rpartition(b"y")
self.assertEqual(b, b"")
self.assertEqual(c, b"")
- self.assert_(b is not c)
+ self.assertTrue(b is not c)
b += b"!"
self.assertEqual(c, b"")
c, b, a = bytearray(b"x").rpartition(b"y")
@@ -860,10 +860,10 @@ class AssortedBytesTest(unittest.TestCase):
self.assertEqual(bytes(b"abc") <= b"ab", False)
def test_doc(self):
- self.failUnless(bytearray.__doc__ != None)
- self.failUnless(bytearray.__doc__.startswith("bytearray("), bytearray.__doc__)
- self.failUnless(bytes.__doc__ != None)
- self.failUnless(bytes.__doc__.startswith("bytes("), bytes.__doc__)
+ self.assertTrue(bytearray.__doc__ != None)
+ self.assertTrue(bytearray.__doc__.startswith("bytearray("), bytearray.__doc__)
+ self.assertTrue(bytes.__doc__ != None)
+ self.assertTrue(bytes.__doc__.startswith("bytes("), bytes.__doc__)
def test_from_bytearray(self):
sample = bytes(b"Hello world\n\x80\x81\xfe\xff")
@@ -920,7 +920,7 @@ class AssortedBytesTest(unittest.TestCase):
def test_return_self(self):
# bytearray.replace must always return a new bytearray
b = bytearray()
- self.failIf(b.replace(b'', b'') is b)
+ self.assertFalse(b.replace(b'', b'') is b)
def test_compare(self):
if sys.flags.bytes_warning:
@@ -997,20 +997,20 @@ class ByteArraySubclass(bytearray):
class ByteArraySubclassTest(unittest.TestCase):
def test_basic(self):
- self.assert_(issubclass(ByteArraySubclass, bytearray))
- self.assert_(isinstance(ByteArraySubclass(), bytearray))
+ self.assertTrue(issubclass(ByteArraySubclass, bytearray))
+ self.assertTrue(isinstance(ByteArraySubclass(), bytearray))
a, b = b"abcd", b"efgh"
_a, _b = ByteArraySubclass(a), ByteArraySubclass(b)
# test comparison operators with subclass instances
- self.assert_(_a == _a)
- self.assert_(_a != _b)
- self.assert_(_a < _b)
- self.assert_(_a <= _b)
- self.assert_(_b >= _a)
- self.assert_(_b > _a)
- self.assert_(_a is not a)
+ self.assertTrue(_a == _a)
+ self.assertTrue(_a != _b)
+ self.assertTrue(_a < _b)
+ self.assertTrue(_a <= _b)
+ self.assertTrue(_b >= _a)
+ self.assertTrue(_b > _a)
+ self.assertTrue(_a is not a)
# test concat of subclass instances
self.assertEqual(a + b, _a + _b)
@@ -1018,7 +1018,7 @@ class ByteArraySubclassTest(unittest.TestCase):
self.assertEqual(a + b, _a + b)
# test repeat
- self.assert_(a*5 == _a*5)
+ self.assertTrue(a*5 == _a*5)
def test_join(self):
# Make sure join returns a NEW object for single item sequences
@@ -1026,12 +1026,12 @@ class ByteArraySubclassTest(unittest.TestCase):
# Make sure that it is of the appropriate type.
s1 = ByteArraySubclass(b"abcd")
s2 = bytearray().join([s1])
- self.assert_(s1 is not s2)
- self.assert_(type(s2) is bytearray, type(s2))
+ self.assertTrue(s1 is not s2)
+ self.assertTrue(type(s2) is bytearray, type(s2))
# Test reverse, calling join on subclass
s3 = s1.join([b"abcd"])
- self.assert_(type(s3) is bytearray)
+ self.assertTrue(type(s3) is bytearray)
def test_pickle(self):
a = ByteArraySubclass(b"abcd")
diff --git a/Lib/test/test_capi.py b/Lib/test/test_capi.py
index d3d2226320..0460679c7b 100644
--- a/Lib/test/test_capi.py
+++ b/Lib/test/test_capi.py
@@ -24,7 +24,7 @@ class CAPITest(unittest.TestCase):
def test_instancemethod(self):
inst = InstanceMethod()
self.assertEqual(id(inst), inst.id())
- self.assert_(inst.testfunction() is inst)
+ self.assertTrue(inst.testfunction() is inst)
self.assertEqual(inst.testfunction.__doc__, testfunction.__doc__)
self.assertEqual(InstanceMethod.testfunction.__doc__, testfunction.__doc__)
@@ -64,7 +64,7 @@ class TestPendingCalls(unittest.TestCase):
if context and not context.event.is_set():
continue
count += 1
- self.failUnless(count < 10000,
+ self.assertTrue(count < 10000,
"timeout waiting for %i callbacks, got %i"%(n, len(l)))
if False and support.verbose:
print("(%i)"%(len(l),))
diff --git a/Lib/test/test_cfgparser.py b/Lib/test/test_cfgparser.py
index 12fd00cbf1..a3d26400b2 100644
--- a/Lib/test/test_cfgparser.py
+++ b/Lib/test/test_cfgparser.py
@@ -76,16 +76,16 @@ class TestCaseBase(unittest.TestCase):
eq(cf.get('Spaces', 'key with spaces'), 'value')
eq(cf.get('Spaces', 'another with spaces'), 'splat!')
- self.failIf('__name__' in cf.options("Foo Bar"),
+ self.assertFalse('__name__' in cf.options("Foo Bar"),
'__name__ "option" should not be exposed by the API!')
# Make sure the right things happen for remove_option();
# added to include check for SourceForge bug #123324:
- self.failUnless(cf.remove_option('Foo Bar', 'foo'),
+ self.assertTrue(cf.remove_option('Foo Bar', 'foo'),
"remove_option() failed to report existence of option")
- self.failIf(cf.has_option('Foo Bar', 'foo'),
+ self.assertFalse(cf.has_option('Foo Bar', 'foo'),
"remove_option() failed to remove option")
- self.failIf(cf.remove_option('Foo Bar', 'foo'),
+ self.assertFalse(cf.remove_option('Foo Bar', 'foo'),
"remove_option() failed to report non-existence of option"
" that was removed")
@@ -107,10 +107,10 @@ class TestCaseBase(unittest.TestCase):
eq(cf.options("a"), ["b"])
eq(cf.get("a", "b"), "value",
"could not locate option, expecting case-insensitive option names")
- self.failUnless(cf.has_option("a", "b"))
+ self.assertTrue(cf.has_option("a", "b"))
cf.set("A", "A-B", "A-B value")
for opt in ("a-b", "A-b", "a-B", "A-B"):
- self.failUnless(
+ self.assertTrue(
cf.has_option("A", opt),
"has_option() returned false for option which should exist")
eq(cf.options("A"), ["a-b"])
@@ -127,7 +127,7 @@ class TestCaseBase(unittest.TestCase):
# SF bug #561822:
cf = self.fromstring("[section]\nnekey=nevalue\n",
defaults={"key":"value"})
- self.failUnless(cf.has_option("section", "Key"))
+ self.assertTrue(cf.has_option("section", "Key"))
def test_default_case_sensitivity(self):
@@ -163,7 +163,7 @@ class TestCaseBase(unittest.TestCase):
cf = self.newconfig()
self.assertEqual(cf.sections(), [],
"new ConfigParser should have no defined sections")
- self.failIf(cf.has_section("Foo"),
+ self.assertFalse(cf.has_section("Foo"),
"new ConfigParser should have no acknowledged sections")
self.assertRaises(configparser.NoSectionError,
cf.options, "Foo")
@@ -202,8 +202,8 @@ class TestCaseBase(unittest.TestCase):
"E5=FALSE AND MORE"
)
for x in range(1, 5):
- self.failUnless(cf.getboolean('BOOLTEST', 't%d' % x))
- self.failIf(cf.getboolean('BOOLTEST', 'f%d' % x))
+ self.assertTrue(cf.getboolean('BOOLTEST', 't%d' % x))
+ self.assertFalse(cf.getboolean('BOOLTEST', 'f%d' % x))
self.assertRaises(ValueError,
cf.getboolean, 'BOOLTEST', 'e%d' % x)
diff --git a/Lib/test/test_cgi.py b/Lib/test/test_cgi.py
index 87028b59d4..ef7dfa5361 100644
--- a/Lib/test/test_cgi.py
+++ b/Lib/test/test_cgi.py
@@ -143,7 +143,7 @@ class CgiTests(unittest.TestCase):
# test individual fields
for key in expect.keys():
expect_val = expect[key]
- self.assert_(key in fs)
+ self.assertTrue(key in fs)
if len(expect_val) > 1:
self.assertEqual(fs.getvalue(key), expect_val)
else:
@@ -194,7 +194,7 @@ class CgiTests(unittest.TestCase):
# if we're not chunking properly, readline is only called twice
# (by read_binary); if we are chunking properly, it will be called 5 times
# as long as the chunksize is 1 << 16.
- self.assert_(f.numcalls > 2)
+ self.assertTrue(f.numcalls > 2)
def test_fieldstorage_multipart(self):
#Test basic FieldStorage multipart parsing
diff --git a/Lib/test/test_cmath.py b/Lib/test/test_cmath.py
index 17cb56689f..2d2defffdc 100755
--- a/Lib/test/test_cmath.py
+++ b/Lib/test/test_cmath.py
@@ -412,7 +412,7 @@ class CMathTests(unittest.TestCase):
# real or imaginary part NaN
for z in complex_nans:
- self.assert_(math.isnan(phase(z)))
+ self.assertTrue(math.isnan(phase(z)))
def test_abs(self):
# zeros
@@ -425,18 +425,18 @@ class CMathTests(unittest.TestCase):
# real or imaginary part NaN
self.assertEqual(abs(complex(NAN, -INF)), INF)
- self.assert_(math.isnan(abs(complex(NAN, -2.3))))
- self.assert_(math.isnan(abs(complex(NAN, -0.0))))
- self.assert_(math.isnan(abs(complex(NAN, 0.0))))
- self.assert_(math.isnan(abs(complex(NAN, 2.3))))
+ self.assertTrue(math.isnan(abs(complex(NAN, -2.3))))
+ self.assertTrue(math.isnan(abs(complex(NAN, -0.0))))
+ self.assertTrue(math.isnan(abs(complex(NAN, 0.0))))
+ self.assertTrue(math.isnan(abs(complex(NAN, 2.3))))
self.assertEqual(abs(complex(NAN, INF)), INF)
self.assertEqual(abs(complex(-INF, NAN)), INF)
- self.assert_(math.isnan(abs(complex(-2.3, NAN))))
- self.assert_(math.isnan(abs(complex(-0.0, NAN))))
- self.assert_(math.isnan(abs(complex(0.0, NAN))))
- self.assert_(math.isnan(abs(complex(2.3, NAN))))
+ self.assertTrue(math.isnan(abs(complex(-2.3, NAN))))
+ self.assertTrue(math.isnan(abs(complex(-0.0, NAN))))
+ self.assertTrue(math.isnan(abs(complex(0.0, NAN))))
+ self.assertTrue(math.isnan(abs(complex(2.3, NAN))))
self.assertEqual(abs(complex(INF, NAN)), INF)
- self.assert_(math.isnan(abs(complex(NAN, NAN))))
+ self.assertTrue(math.isnan(abs(complex(NAN, NAN))))
# result overflows
if float.__getformat__("double").startswith("IEEE"):
@@ -455,26 +455,26 @@ class CMathTests(unittest.TestCase):
self.assertCEqual(rect(1, -pi/2), (0, -1.))
def test_isnan(self):
- self.failIf(cmath.isnan(1))
- self.failIf(cmath.isnan(1j))
- self.failIf(cmath.isnan(INF))
- self.assert_(cmath.isnan(NAN))
- self.assert_(cmath.isnan(complex(NAN, 0)))
- self.assert_(cmath.isnan(complex(0, NAN)))
- self.assert_(cmath.isnan(complex(NAN, NAN)))
- self.assert_(cmath.isnan(complex(NAN, INF)))
- self.assert_(cmath.isnan(complex(INF, NAN)))
+ self.assertFalse(cmath.isnan(1))
+ self.assertFalse(cmath.isnan(1j))
+ self.assertFalse(cmath.isnan(INF))
+ self.assertTrue(cmath.isnan(NAN))
+ self.assertTrue(cmath.isnan(complex(NAN, 0)))
+ self.assertTrue(cmath.isnan(complex(0, NAN)))
+ self.assertTrue(cmath.isnan(complex(NAN, NAN)))
+ self.assertTrue(cmath.isnan(complex(NAN, INF)))
+ self.assertTrue(cmath.isnan(complex(INF, NAN)))
def test_isinf(self):
- self.failIf(cmath.isinf(1))
- self.failIf(cmath.isinf(1j))
- self.failIf(cmath.isinf(NAN))
- self.assert_(cmath.isinf(INF))
- self.assert_(cmath.isinf(complex(INF, 0)))
- self.assert_(cmath.isinf(complex(0, INF)))
- self.assert_(cmath.isinf(complex(INF, INF)))
- self.assert_(cmath.isinf(complex(NAN, INF)))
- self.assert_(cmath.isinf(complex(INF, NAN)))
+ self.assertFalse(cmath.isinf(1))
+ self.assertFalse(cmath.isinf(1j))
+ self.assertFalse(cmath.isinf(NAN))
+ self.assertTrue(cmath.isinf(INF))
+ self.assertTrue(cmath.isinf(complex(INF, 0)))
+ self.assertTrue(cmath.isinf(complex(0, INF)))
+ self.assertTrue(cmath.isinf(complex(INF, INF)))
+ self.assertTrue(cmath.isinf(complex(NAN, INF)))
+ self.assertTrue(cmath.isinf(complex(INF, NAN)))
def test_main():
diff --git a/Lib/test/test_cmd_line.py b/Lib/test/test_cmd_line.py
index ef3c109950..87ae2b6619 100644
--- a/Lib/test/test_cmd_line.py
+++ b/Lib/test/test_cmd_line.py
@@ -169,7 +169,7 @@ class CmdLineTest(unittest.TestCase):
p.stdin.flush()
data, rc = _kill_python_and_exit_code(p)
self.assertEqual(rc, 0)
- self.assert_(data.startswith(b'x'), data)
+ self.assertTrue(data.startswith(b'x'), data)
def test_large_PYTHONPATH(self):
with test.support.EnvironmentVarGuard() as env:
@@ -178,8 +178,8 @@ class CmdLineTest(unittest.TestCase):
env['PYTHONPATH'] = path1 + os.pathsep + path2
p = _spawn_python('-S', '-c', 'import sys; print(sys.path)')
stdout, _ = p.communicate()
- self.assert_(path1.encode('ascii') in stdout)
- self.assert_(path2.encode('ascii') in stdout)
+ self.assertTrue(path1.encode('ascii') in stdout)
+ self.assertTrue(path2.encode('ascii') in stdout)
def test_main():
diff --git a/Lib/test/test_cmd_line_script.py b/Lib/test/test_cmd_line_script.py
index e060ec17e7..7114681719 100644
--- a/Lib/test/test_cmd_line_script.py
+++ b/Lib/test/test_cmd_line_script.py
@@ -154,9 +154,9 @@ class CmdLineTest(unittest.TestCase):
print(printed_file)
print(printed_package)
print(printed_argv0)
- self.assert_(printed_file in data)
- self.assert_(printed_package in data)
- self.assert_(printed_argv0 in data)
+ self.assertTrue(printed_file in data)
+ self.assertTrue(printed_package in data)
+ self.assertTrue(printed_argv0 in data)
def _check_import_error(self, script_name, expected_msg,
*cmd_line_switches):
@@ -166,7 +166,7 @@ class CmdLineTest(unittest.TestCase):
print('Output from test script %r:' % script_name)
print(data)
print('Expected output: %r' % expected_msg)
- self.assert_(expected_msg in data)
+ self.assertTrue(expected_msg in data)
def test_basic_script(self):
with temp_dir() as script_dir:
diff --git a/Lib/test/test_codecs.py b/Lib/test/test_codecs.py
index e060471d4b..9f734536ec 100644
--- a/Lib/test/test_codecs.py
+++ b/Lib/test/test_codecs.py
@@ -29,14 +29,14 @@ class MixInCheckStateHandling:
d = codecs.getincrementaldecoder(encoding)()
part1 = d.decode(s[:i])
state = d.getstate()
- self.assert_(isinstance(state[1], int))
+ self.assertTrue(isinstance(state[1], int))
# Check that the condition stated in the documentation for
# IncrementalDecoder.getstate() holds
if not state[1]:
# reset decoder to the default state without anything buffered
d.setstate((state[0][:0], 0))
# Feeding the previous input may not produce any output
- self.assert_(not d.decode(state[0]))
+ self.assertTrue(not d.decode(state[0]))
# The decoder must return to the same state
self.assertEqual(state, d.getstate())
# Create a new decoder and set it to the state
@@ -296,7 +296,7 @@ class UTF32Test(ReadTest):
f.write("spam")
d = s.getvalue()
# check whether there is exactly one BOM in it
- self.assert_(d == self.spamle or d == self.spambe)
+ self.assertTrue(d == self.spamle or d == self.spambe)
# try to read it back
s = io.BytesIO(d)
f = reader(s)
@@ -429,7 +429,7 @@ class UTF16Test(ReadTest):
f.write("spam")
d = s.getvalue()
# check whether there is exactly one BOM in it
- self.assert_(d == self.spamle or d == self.spambe)
+ self.assertTrue(d == self.spamle or d == self.spambe)
# try to read it back
s = io.BytesIO(d)
f = reader(s)
@@ -1335,7 +1335,7 @@ class BasicUnicodeTest(unittest.TestCase, MixInCheckStateHandling):
for c in s:
writer.write(c)
chunk = q.read()
- self.assert_(type(chunk) is bytes, type(chunk))
+ self.assertTrue(type(chunk) is bytes, type(chunk))
encodedresult += chunk
q = Queue(b"")
reader = codecs.getreader(encoding)(q)
diff --git a/Lib/test/test_codeop.py b/Lib/test/test_codeop.py
index 224a314195..d845e20118 100644
--- a/Lib/test/test_codeop.py
+++ b/Lib/test/test_codeop.py
@@ -23,7 +23,7 @@ class CodeopTests(unittest.TestCase):
'''succeed iff str is a valid piece of code'''
if is_jython:
code = compile_command(str, "<input>", symbol)
- self.assert_(code)
+ self.assertTrue(code)
if symbol == "single":
d,r = {},{}
saved_stdout = sys.stdout
@@ -52,9 +52,9 @@ class CodeopTests(unittest.TestCase):
compile_command(str,symbol=symbol)
self.fail("No exception thrown for invalid code")
except SyntaxError:
- self.assert_(is_syntax)
+ self.assertTrue(is_syntax)
except OverflowError:
- self.assert_(not is_syntax)
+ self.assertTrue(not is_syntax)
def test_valid(self):
av = self.assertValid
diff --git a/Lib/test/test_collections.py b/Lib/test/test_collections.py
index 8387564a79..ded8b70e00 100644
--- a/Lib/test/test_collections.py
+++ b/Lib/test/test_collections.py
@@ -44,9 +44,9 @@ class TestNamedTuple(unittest.TestCase):
namedtuple('_', 'a b c') # Test leading underscores in a typename
nt = namedtuple('nt', 'the quick brown fox') # check unicode input
- self.assert_("u'" not in repr(nt._fields))
+ self.assertTrue("u'" not in repr(nt._fields))
nt = namedtuple('nt', ('the', 'quick')) # check unicode input
- self.assert_("u'" not in repr(nt._fields))
+ self.assertTrue("u'" not in repr(nt._fields))
self.assertRaises(TypeError, Point._make, [11]) # catch too few args
self.assertRaises(TypeError, Point._make, [11, 22, 33]) # catch too many args
@@ -75,8 +75,8 @@ class TestNamedTuple(unittest.TestCase):
self.assertRaises(TypeError, eval, 'Point(XXX=1, y=2)', locals()) # wrong keyword argument
self.assertRaises(TypeError, eval, 'Point(x=1)', locals()) # missing keyword argument
self.assertEqual(repr(p), 'Point(x=11, y=22)')
- self.assert_('__dict__' not in dir(p)) # verify instance has no dict
- self.assert_('__weakref__' not in dir(p))
+ self.assertTrue('__dict__' not in dir(p)) # verify instance has no dict
+ self.assertTrue('__weakref__' not in dir(p))
self.assertEqual(p, Point._make([11, 22])) # test _make classmethod
self.assertEqual(p._fields, ('x', 'y')) # test _fields attribute
self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method
@@ -103,7 +103,7 @@ class TestNamedTuple(unittest.TestCase):
Point = namedtuple('Point', 'x y')
p = Point(11, 22)
- self.assert_(isinstance(p, tuple))
+ self.assertTrue(isinstance(p, tuple))
self.assertEqual(p, (11, 22)) # matches a real tuple
self.assertEqual(tuple(p), (11, 22)) # coercable to a real tuple
self.assertEqual(list(p), [11, 22]) # coercable to a list
@@ -236,8 +236,8 @@ class TestOneTrickPonyABCs(ABCTestCase):
# Check some non-hashables
non_samples = [bytearray(), list(), set(), dict()]
for x in non_samples:
- self.failIf(isinstance(x, Hashable), repr(x))
- self.failIf(issubclass(type(x), Hashable), repr(type(x)))
+ self.assertFalse(isinstance(x, Hashable), repr(x))
+ self.assertFalse(issubclass(type(x), Hashable), repr(type(x)))
# Check some hashables
samples = [None,
int(), float(), complex(),
@@ -246,23 +246,23 @@ class TestOneTrickPonyABCs(ABCTestCase):
int, list, object, type, bytes()
]
for x in samples:
- self.failUnless(isinstance(x, Hashable), repr(x))
- self.failUnless(issubclass(type(x), Hashable), repr(type(x)))
+ self.assertTrue(isinstance(x, Hashable), repr(x))
+ self.assertTrue(issubclass(type(x), Hashable), repr(type(x)))
self.assertRaises(TypeError, Hashable)
# Check direct subclassing
class H(Hashable):
def __hash__(self):
return super().__hash__()
self.assertEqual(hash(H()), 0)
- self.failIf(issubclass(int, H))
+ self.assertFalse(issubclass(int, H))
self.validate_abstract_methods(Hashable, '__hash__')
def test_Iterable(self):
# Check some non-iterables
non_samples = [None, 42, 3.14, 1j]
for x in non_samples:
- self.failIf(isinstance(x, Iterable), repr(x))
- self.failIf(issubclass(type(x), Iterable), repr(type(x)))
+ self.assertFalse(isinstance(x, Iterable), repr(x))
+ self.assertFalse(issubclass(type(x), Iterable), repr(type(x)))
# Check some iterables
samples = [bytes(), str(),
tuple(), list(), set(), frozenset(), dict(),
@@ -271,21 +271,21 @@ class TestOneTrickPonyABCs(ABCTestCase):
(x for x in []),
]
for x in samples:
- self.failUnless(isinstance(x, Iterable), repr(x))
- self.failUnless(issubclass(type(x), Iterable), repr(type(x)))
+ self.assertTrue(isinstance(x, Iterable), repr(x))
+ self.assertTrue(issubclass(type(x), Iterable), repr(type(x)))
# Check direct subclassing
class I(Iterable):
def __iter__(self):
return super().__iter__()
self.assertEqual(list(I()), [])
- self.failIf(issubclass(str, I))
+ self.assertFalse(issubclass(str, I))
self.validate_abstract_methods(Iterable, '__iter__')
def test_Iterator(self):
non_samples = [None, 42, 3.14, 1j, b"", "", (), [], {}, set()]
for x in non_samples:
- self.failIf(isinstance(x, Iterator), repr(x))
- self.failIf(issubclass(type(x), Iterator), repr(type(x)))
+ self.assertFalse(isinstance(x, Iterator), repr(x))
+ self.assertFalse(issubclass(type(x), Iterator), repr(type(x)))
samples = [iter(bytes()), iter(str()),
iter(tuple()), iter(list()), iter(dict()),
iter(set()), iter(frozenset()),
@@ -295,8 +295,8 @@ class TestOneTrickPonyABCs(ABCTestCase):
(x for x in []),
]
for x in samples:
- self.failUnless(isinstance(x, Iterator), repr(x))
- self.failUnless(issubclass(type(x), Iterator), repr(type(x)))
+ self.assertTrue(isinstance(x, Iterator), repr(x))
+ self.assertTrue(issubclass(type(x), Iterator), repr(type(x)))
self.validate_abstract_methods(Iterator, '__next__')
def test_Sized(self):
@@ -305,15 +305,15 @@ class TestOneTrickPonyABCs(ABCTestCase):
(x for x in []),
]
for x in non_samples:
- self.failIf(isinstance(x, Sized), repr(x))
- self.failIf(issubclass(type(x), Sized), repr(type(x)))
+ self.assertFalse(isinstance(x, Sized), repr(x))
+ self.assertFalse(issubclass(type(x), Sized), repr(type(x)))
samples = [bytes(), str(),
tuple(), list(), set(), frozenset(), dict(),
dict().keys(), dict().items(), dict().values(),
]
for x in samples:
- self.failUnless(isinstance(x, Sized), repr(x))
- self.failUnless(issubclass(type(x), Sized), repr(type(x)))
+ self.assertTrue(isinstance(x, Sized), repr(x))
+ self.assertTrue(issubclass(type(x), Sized), repr(type(x)))
self.validate_abstract_methods(Sized, '__len__')
def test_Container(self):
@@ -322,15 +322,15 @@ class TestOneTrickPonyABCs(ABCTestCase):
(x for x in []),
]
for x in non_samples:
- self.failIf(isinstance(x, Container), repr(x))
- self.failIf(issubclass(type(x), Container), repr(type(x)))
+ self.assertFalse(isinstance(x, Container), repr(x))
+ self.assertFalse(issubclass(type(x), Container), repr(type(x)))
samples = [bytes(), str(),
tuple(), list(), set(), frozenset(), dict(),
dict().keys(), dict().items(),
]
for x in samples:
- self.failUnless(isinstance(x, Container), repr(x))
- self.failUnless(issubclass(type(x), Container), repr(type(x)))
+ self.assertTrue(isinstance(x, Container), repr(x))
+ self.assertTrue(issubclass(type(x), Container), repr(type(x)))
self.validate_abstract_methods(Container, '__contains__')
def test_Callable(self):
@@ -340,32 +340,32 @@ class TestOneTrickPonyABCs(ABCTestCase):
(x for x in []),
]
for x in non_samples:
- self.failIf(isinstance(x, Callable), repr(x))
- self.failIf(issubclass(type(x), Callable), repr(type(x)))
+ self.assertFalse(isinstance(x, Callable), repr(x))
+ self.assertFalse(issubclass(type(x), Callable), repr(type(x)))
samples = [lambda: None,
type, int, object,
len,
list.append, [].append,
]
for x in samples:
- self.failUnless(isinstance(x, Callable), repr(x))
- self.failUnless(issubclass(type(x), Callable), repr(type(x)))
+ self.assertTrue(isinstance(x, Callable), repr(x))
+ self.assertTrue(issubclass(type(x), Callable), repr(type(x)))
self.validate_abstract_methods(Callable, '__call__')
def test_direct_subclassing(self):
for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
class C(B):
pass
- self.failUnless(issubclass(C, B))
- self.failIf(issubclass(int, C))
+ self.assertTrue(issubclass(C, B))
+ self.assertFalse(issubclass(int, C))
def test_registration(self):
for B in Hashable, Iterable, Iterator, Sized, Container, Callable:
class C:
__hash__ = None # Make sure it isn't hashable by default
- self.failIf(issubclass(C, B), B.__name__)
+ self.assertFalse(issubclass(C, B), B.__name__)
B.register(C)
- self.failUnless(issubclass(C, B))
+ self.assertTrue(issubclass(C, B))
class WithSet(MutableSet):
@@ -395,8 +395,8 @@ class TestCollectionABCs(ABCTestCase):
def test_Set(self):
for sample in [set, frozenset]:
- self.failUnless(isinstance(sample(), Set))
- self.failUnless(issubclass(sample, Set))
+ self.assertTrue(isinstance(sample(), Set))
+ self.assertTrue(issubclass(sample, Set))
self.validate_abstract_methods(Set, '__contains__', '__iter__', '__len__')
def test_hash_Set(self):
@@ -412,13 +412,13 @@ class TestCollectionABCs(ABCTestCase):
def __hash__(self):
return self._hash()
a, b = OneTwoThreeSet(), OneTwoThreeSet()
- self.failUnless(hash(a) == hash(b))
+ self.assertTrue(hash(a) == hash(b))
def test_MutableSet(self):
- self.failUnless(isinstance(set(), MutableSet))
- self.failUnless(issubclass(set, MutableSet))
- self.failIf(isinstance(frozenset(), MutableSet))
- self.failIf(issubclass(frozenset, MutableSet))
+ self.assertTrue(isinstance(set(), MutableSet))
+ self.assertTrue(issubclass(set, MutableSet))
+ self.assertFalse(isinstance(frozenset(), MutableSet))
+ self.assertFalse(issubclass(frozenset, MutableSet))
self.validate_abstract_methods(MutableSet, '__contains__', '__iter__', '__len__',
'add', 'discard')
@@ -457,46 +457,46 @@ class TestCollectionABCs(ABCTestCase):
def test_Mapping(self):
for sample in [dict]:
- self.failUnless(isinstance(sample(), Mapping))
- self.failUnless(issubclass(sample, Mapping))
+ self.assertTrue(isinstance(sample(), Mapping))
+ self.assertTrue(issubclass(sample, Mapping))
self.validate_abstract_methods(Mapping, '__contains__', '__iter__', '__len__',
'__getitem__')
def test_MutableMapping(self):
for sample in [dict]:
- self.failUnless(isinstance(sample(), MutableMapping))
- self.failUnless(issubclass(sample, MutableMapping))
+ self.assertTrue(isinstance(sample(), MutableMapping))
+ self.assertTrue(issubclass(sample, MutableMapping))
self.validate_abstract_methods(MutableMapping, '__contains__', '__iter__', '__len__',
'__getitem__', '__setitem__', '__delitem__')
def test_Sequence(self):
for sample in [tuple, list, bytes, str]:
- self.failUnless(isinstance(sample(), Sequence))
- self.failUnless(issubclass(sample, Sequence))
- self.failUnless(isinstance(range(10), Sequence))
- self.failUnless(issubclass(range, Sequence))
- self.failUnless(issubclass(str, Sequence))
+ self.assertTrue(isinstance(sample(), Sequence))
+ self.assertTrue(issubclass(sample, Sequence))
+ self.assertTrue(isinstance(range(10), Sequence))
+ self.assertTrue(issubclass(range, Sequence))
+ self.assertTrue(issubclass(str, Sequence))
self.validate_abstract_methods(Sequence, '__contains__', '__iter__', '__len__',
'__getitem__')
def test_ByteString(self):
for sample in [bytes, bytearray]:
- self.failUnless(isinstance(sample(), ByteString))
- self.failUnless(issubclass(sample, ByteString))
+ self.assertTrue(isinstance(sample(), ByteString))
+ self.assertTrue(issubclass(sample, ByteString))
for sample in [str, list, tuple]:
- self.failIf(isinstance(sample(), ByteString))
- self.failIf(issubclass(sample, ByteString))
- self.failIf(isinstance(memoryview(b""), ByteString))
- self.failIf(issubclass(memoryview, ByteString))
+ self.assertFalse(isinstance(sample(), ByteString))
+ self.assertFalse(issubclass(sample, ByteString))
+ self.assertFalse(isinstance(memoryview(b""), ByteString))
+ self.assertFalse(issubclass(memoryview, ByteString))
def test_MutableSequence(self):
for sample in [tuple, str, bytes]:
- self.failIf(isinstance(sample(), MutableSequence))
- self.failIf(issubclass(sample, MutableSequence))
+ self.assertFalse(isinstance(sample(), MutableSequence))
+ self.assertFalse(issubclass(sample, MutableSequence))
for sample in [list, bytearray]:
- self.failUnless(isinstance(sample(), MutableSequence))
- self.failUnless(issubclass(sample, MutableSequence))
- self.failIf(issubclass(str, MutableSequence))
+ self.assertTrue(isinstance(sample(), MutableSequence))
+ self.assertTrue(issubclass(sample, MutableSequence))
+ self.assertFalse(issubclass(str, MutableSequence))
self.validate_abstract_methods(MutableSequence, '__contains__', '__iter__',
'__len__', '__getitem__', '__setitem__', '__delitem__', 'insert')
@@ -506,10 +506,10 @@ class TestCounter(unittest.TestCase):
c = Counter('abcaba')
self.assertEqual(c, Counter({'a':3 , 'b': 2, 'c': 1}))
self.assertEqual(c, Counter(a=3, b=2, c=1))
- self.assert_(isinstance(c, dict))
- self.assert_(isinstance(c, Mapping))
- self.assert_(issubclass(Counter, dict))
- self.assert_(issubclass(Counter, Mapping))
+ self.assertTrue(isinstance(c, dict))
+ self.assertTrue(isinstance(c, Mapping))
+ self.assertTrue(issubclass(Counter, dict))
+ self.assertTrue(issubclass(Counter, Mapping))
self.assertEqual(len(c), 3)
self.assertEqual(sum(c.values()), 6)
self.assertEqual(sorted(c.values()), [1, 2, 3])
@@ -581,7 +581,7 @@ class TestCounter(unittest.TestCase):
Counter(words),
]):
msg = (i, dup, words)
- self.assert_(dup is not words)
+ self.assertTrue(dup is not words)
self.assertEquals(dup, words)
self.assertEquals(len(dup), len(words))
self.assertEquals(type(dup), type(words))
@@ -597,7 +597,7 @@ class TestCounter(unittest.TestCase):
def test_invariant_for_the_in_operator(self):
c = Counter(a=10, b=-2, c=0)
for elem in c:
- self.assert_(elem in c)
+ self.assertTrue(elem in c)
def test_multiset_operations(self):
# Verify that adding a zero counter will strip zeros and negatives
@@ -622,7 +622,7 @@ class TestCounter(unittest.TestCase):
self.assertEqual(numberop(p[x], q[x]), result[x],
(counterop, x, p, q))
# verify that results exclude non-positive counts
- self.assert_(x>0 for x in result.values())
+ self.assertTrue(x>0 for x in result.values())
elements = 'abcdef'
for i in range(100):
@@ -697,7 +697,7 @@ class TestOrderedDict(unittest.TestCase):
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
od = OrderedDict(pairs)
del od['a']
- self.assert_('a' not in od)
+ self.assertTrue('a' not in od)
with self.assertRaises(KeyError):
del od['a']
self.assertEqual(list(od.items()), pairs[:2] + pairs[3:])
@@ -778,7 +778,7 @@ class TestOrderedDict(unittest.TestCase):
update_test,
OrderedDict(od),
]):
- self.assert_(dup is not od)
+ self.assertTrue(dup is not od)
self.assertEquals(dup, od)
self.assertEquals(list(dup.items()), list(od.items()))
self.assertEquals(len(dup), len(od))
@@ -791,7 +791,7 @@ class TestOrderedDict(unittest.TestCase):
od = OrderedDict(pairs)
# yaml.dump(od) -->
# '!!python/object/apply:__main__.OrderedDict\n- - [a, 1]\n - [b, 2]\n'
- self.assert_(all(type(pair)==list for pair in od.__reduce__()[1]))
+ self.assertTrue(all(type(pair)==list for pair in od.__reduce__()[1]))
def test_reduce_not_too_fat(self):
# do not save instance dictionary if not needed
diff --git a/Lib/test/test_compile.py b/Lib/test/test_compile.py
index ae8a648269..32dd656e53 100644
--- a/Lib/test/test_compile.py
+++ b/Lib/test/test_compile.py
@@ -376,10 +376,10 @@ if 1:
import __mangled_mod
import __package__.module
- self.assert_("_A__mangled" in A.f.__code__.co_varnames)
- self.assert_("__not_mangled__" in A.f.__code__.co_varnames)
- self.assert_("_A__mangled_mod" in A.f.__code__.co_varnames)
- self.assert_("__package__" in A.f.__code__.co_varnames)
+ self.assertTrue("_A__mangled" in A.f.__code__.co_varnames)
+ self.assertTrue("__not_mangled__" in A.f.__code__.co_varnames)
+ self.assertTrue("_A__mangled_mod" in A.f.__code__.co_varnames)
+ self.assertTrue("__package__" in A.f.__code__.co_varnames)
def test_compile_ast(self):
fname = __file__
@@ -398,7 +398,7 @@ if 1:
for fname, code in sample_code:
co1 = compile(code, '%s1' % fname, 'exec')
ast = compile(code, '%s2' % fname, 'exec', _ast.PyCF_ONLY_AST)
- self.assert_(type(ast) == _ast.Module)
+ self.assertTrue(type(ast) == _ast.Module)
co2 = compile(ast, '%s3' % fname, 'exec')
self.assertEqual(co1, co2)
# the code object's filename comes from the second compilation step
diff --git a/Lib/test/test_complex.py b/Lib/test/test_complex.py
index f621186504..faa7e1f6be 100644
--- a/Lib/test/test_complex.py
+++ b/Lib/test/test_complex.py
@@ -35,7 +35,7 @@ class ComplexTest(unittest.TestCase):
if x == 0:
return abs(y) < eps
# check that relative difference < eps
- self.assert_(abs((x-y)/y) < eps)
+ self.assertTrue(abs((x-y)/y) < eps)
def assertFloatsAreIdentical(self, x, y):
"""assert that floats x and y are identical, in the sense that:
@@ -66,7 +66,7 @@ class ComplexTest(unittest.TestCase):
self.assertCloseAbs(x.imag, y.imag, eps)
def assertIs(self, a, b):
- self.assert_(a is b)
+ self.assertTrue(a is b)
def check_div(self, x, y):
"""Compute complex z=x*y, and check that z/x==y and z/y==x."""
@@ -174,8 +174,8 @@ class ComplexTest(unittest.TestCase):
def test_boolcontext(self):
for i in range(100):
- self.assert_(complex(random() + 1e-6, random() + 1e-6))
- self.assert_(not complex(0.0, 0.0))
+ self.assertTrue(complex(random() + 1e-6, random() + 1e-6))
+ self.assertTrue(not complex(0.0, 0.0))
def test_conjugate(self):
self.assertClose(complex(5.3, 9.8).conjugate(), 5.3-9.8j)
@@ -257,7 +257,7 @@ class ComplexTest(unittest.TestCase):
self.assertEqual(split_zeros(complex(-0., 1.).real), split_zeros(-0.))
c = 3.14 + 1j
- self.assert_(complex(c) is c)
+ self.assertTrue(complex(c) is c)
del c
self.assertRaises(TypeError, complex, "1", "1")
diff --git a/Lib/test/test_contains.py b/Lib/test/test_contains.py
index 3f0b234170..622dfd46d1 100644
--- a/Lib/test/test_contains.py
+++ b/Lib/test/test_contains.py
@@ -20,19 +20,19 @@ class TestContains(unittest.TestCase):
a = base_set(1)
b = myset(1)
c = seq(1)
- self.assert_(1 in b)
- self.assert_(0 not in b)
- self.assert_(1 in c)
- self.assert_(0 not in c)
+ self.assertTrue(1 in b)
+ self.assertTrue(0 not in b)
+ self.assertTrue(1 in c)
+ self.assertTrue(0 not in c)
self.assertRaises(TypeError, lambda: 1 in a)
self.assertRaises(TypeError, lambda: 1 not in a)
# test char in string
- self.assert_('c' in 'abc')
- self.assert_('d' not in 'abc')
+ self.assertTrue('c' in 'abc')
+ self.assertTrue('d' not in 'abc')
- self.assert_('' in '')
- self.assert_('' in 'abc')
+ self.assertTrue('' in '')
+ self.assertTrue('' in 'abc')
self.assertRaises(TypeError, lambda: None in 'abc')
@@ -40,15 +40,15 @@ class TestContains(unittest.TestCase):
# a collection of tests on builtin sequence types
a = range(10)
for i in a:
- self.assert_(i in a)
- self.assert_(16 not in a)
- self.assert_(a not in a)
+ self.assertTrue(i in a)
+ self.assertTrue(16 not in a)
+ self.assertTrue(a not in a)
a = tuple(a)
for i in a:
- self.assert_(i in a)
- self.assert_(16 not in a)
- self.assert_(a not in a)
+ self.assertTrue(i in a)
+ self.assertTrue(16 not in a)
+ self.assertTrue(a not in a)
class Deviant1:
"""Behaves strangely when compared
@@ -64,7 +64,7 @@ class TestContains(unittest.TestCase):
self.aList.remove(14)
return 0
- self.assert_(Deviant1() not in Deviant1.aList)
+ self.assertTrue(Deviant1() not in Deviant1.aList)
def test_nonreflexive(self):
# containment and equality tests involving elements that are
@@ -81,9 +81,9 @@ class TestContains(unittest.TestCase):
for constructor in constructors:
container = constructor(values)
for elem in container:
- self.assert_(elem in container)
- self.assert_(container == constructor(values))
- self.assert_(container == container)
+ self.assertTrue(elem in container)
+ self.assertTrue(container == constructor(values))
+ self.assertTrue(container == container)
def test_main():
diff --git a/Lib/test/test_contextlib.py b/Lib/test/test_contextlib.py
index f97cd81861..015a0c5195 100644
--- a/Lib/test/test_contextlib.py
+++ b/Lib/test/test_contextlib.py
@@ -54,7 +54,7 @@ class ContextManagerTestCase(unittest.TestCase):
ctx = whee()
ctx.__enter__()
# Calling __exit__ should not result in an exception
- self.failIf(ctx.__exit__(TypeError, TypeError("foo"), None))
+ self.assertFalse(ctx.__exit__(TypeError, TypeError("foo"), None))
def test_contextmanager_trap_yield_after_throw(self):
@contextmanager
@@ -261,17 +261,17 @@ class FileContextTestCase(unittest.TestCase):
try:
f = None
with open(tfn, "w") as f:
- self.failIf(f.closed)
+ self.assertFalse(f.closed)
f.write("Booh\n")
- self.failUnless(f.closed)
+ self.assertTrue(f.closed)
f = None
try:
with open(tfn, "r") as f:
- self.failIf(f.closed)
+ self.assertFalse(f.closed)
self.assertEqual(f.read(), "Booh\n")
1/0
except ZeroDivisionError:
- self.failUnless(f.closed)
+ self.assertTrue(f.closed)
else:
self.fail("Didn't raise ZeroDivisionError")
finally:
@@ -283,16 +283,16 @@ class FileContextTestCase(unittest.TestCase):
class LockContextTestCase(unittest.TestCase):
def boilerPlate(self, lock, locked):
- self.failIf(locked())
+ self.assertFalse(locked())
with lock:
- self.failUnless(locked())
- self.failIf(locked())
+ self.assertTrue(locked())
+ self.assertFalse(locked())
try:
with lock:
- self.failUnless(locked())
+ self.assertTrue(locked())
1/0
except ZeroDivisionError:
- self.failIf(locked())
+ self.assertFalse(locked())
else:
self.fail("Didn't raise ZeroDivisionError")
diff --git a/Lib/test/test_copy.py b/Lib/test/test_copy.py
index 502bf3fe92..2af21094ea 100644
--- a/Lib/test/test_copy.py
+++ b/Lib/test/test_copy.py
@@ -17,8 +17,8 @@ class TestCopy(unittest.TestCase):
# Attempt full line coverage of copy.py from top to bottom
def test_exceptions(self):
- self.assert_(copy.Error is copy.error)
- self.assert_(issubclass(copy.Error, Exception))
+ self.assertTrue(copy.Error is copy.error)
+ self.assertTrue(issubclass(copy.Error, Exception))
# The copy() method
@@ -59,7 +59,7 @@ class TestCopy(unittest.TestCase):
raise support.TestFailed("shouldn't call this")
x = C()
y = copy.copy(x)
- self.assert_(y is x)
+ self.assertTrue(y is x)
def test_copy_reduce(self):
class C(object):
@@ -67,7 +67,7 @@ class TestCopy(unittest.TestCase):
return ""
x = C()
y = copy.copy(x)
- self.assert_(y is x)
+ self.assertTrue(y is x)
def test_copy_cant(self):
class C(object):
@@ -91,7 +91,7 @@ class TestCopy(unittest.TestCase):
"hello", "hello\u1234", f.__code__,
NewStyle, range(10), Classic, max]
for x in tests:
- self.assert_(copy.copy(x) is x, repr(x))
+ self.assertTrue(copy.copy(x) is x, repr(x))
def test_copy_list(self):
x = [1, 2, 3]
@@ -185,9 +185,9 @@ class TestCopy(unittest.TestCase):
x = [x, x]
y = copy.deepcopy(x)
self.assertEqual(y, x)
- self.assert_(y is not x)
- self.assert_(y[0] is not x[0])
- self.assert_(y[0] is y[1])
+ self.assertTrue(y is not x)
+ self.assertTrue(y[0] is not x[0])
+ self.assertTrue(y[0] is y[1])
def test_deepcopy_issubclass(self):
# XXX Note: there's no way to test the TypeError coming out of
@@ -232,7 +232,7 @@ class TestCopy(unittest.TestCase):
raise support.TestFailed("shouldn't call this")
x = C()
y = copy.deepcopy(x)
- self.assert_(y is x)
+ self.assertTrue(y is x)
def test_deepcopy_reduce(self):
class C(object):
@@ -240,7 +240,7 @@ class TestCopy(unittest.TestCase):
return ""
x = C()
y = copy.deepcopy(x)
- self.assert_(y is x)
+ self.assertTrue(y is x)
def test_deepcopy_cant(self):
class C(object):
@@ -264,14 +264,14 @@ class TestCopy(unittest.TestCase):
"hello", "hello\u1234", f.__code__,
NewStyle, range(10), Classic, max]
for x in tests:
- self.assert_(copy.deepcopy(x) is x, repr(x))
+ self.assertTrue(copy.deepcopy(x) is x, repr(x))
def test_deepcopy_list(self):
x = [[1, 2], 3]
y = copy.deepcopy(x)
self.assertEqual(y, x)
- self.assert_(x is not y)
- self.assert_(x[0] is not y[0])
+ self.assertTrue(x is not y)
+ self.assertTrue(x[0] is not y[0])
def test_deepcopy_reflexive_list(self):
x = []
@@ -279,16 +279,16 @@ class TestCopy(unittest.TestCase):
y = copy.deepcopy(x)
for op in comparisons:
self.assertRaises(RuntimeError, op, y, x)
- self.assert_(y is not x)
- self.assert_(y[0] is y)
+ self.assertTrue(y is not x)
+ self.assertTrue(y[0] is y)
self.assertEqual(len(y), 1)
def test_deepcopy_tuple(self):
x = ([1, 2], 3)
y = copy.deepcopy(x)
self.assertEqual(y, x)
- self.assert_(x is not y)
- self.assert_(x[0] is not y[0])
+ self.assertTrue(x is not y)
+ self.assertTrue(x[0] is not y[0])
def test_deepcopy_reflexive_tuple(self):
x = ([],)
@@ -296,16 +296,16 @@ class TestCopy(unittest.TestCase):
y = copy.deepcopy(x)
for op in comparisons:
self.assertRaises(RuntimeError, op, y, x)
- self.assert_(y is not x)
- self.assert_(y[0] is not x[0])
- self.assert_(y[0][0] is y)
+ self.assertTrue(y is not x)
+ self.assertTrue(y[0] is not x[0])
+ self.assertTrue(y[0][0] is y)
def test_deepcopy_dict(self):
x = {"foo": [1, 2], "bar": 3}
y = copy.deepcopy(x)
self.assertEqual(y, x)
- self.assert_(x is not y)
- self.assert_(x["foo"] is not y["foo"])
+ self.assertTrue(x is not y)
+ self.assertTrue(x["foo"] is not y["foo"])
def test_deepcopy_reflexive_dict(self):
x = {}
@@ -315,15 +315,15 @@ class TestCopy(unittest.TestCase):
self.assertRaises(TypeError, op, y, x)
for op in equality_comparisons:
self.assertRaises(RuntimeError, op, y, x)
- self.assert_(y is not x)
- self.assert_(y['foo'] is y)
+ self.assertTrue(y is not x)
+ self.assertTrue(y['foo'] is y)
self.assertEqual(len(y), 1)
def test_deepcopy_keepalive(self):
memo = {}
x = 42
y = copy.deepcopy(x, memo)
- self.assert_(memo[id(x)] is x)
+ self.assertTrue(memo[id(x)] is x)
def test_deepcopy_inst_vanilla(self):
class C:
@@ -334,7 +334,7 @@ class TestCopy(unittest.TestCase):
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
- self.assert_(y.foo is not x.foo)
+ self.assertTrue(y.foo is not x.foo)
def test_deepcopy_inst_deepcopy(self):
class C:
@@ -347,8 +347,8 @@ class TestCopy(unittest.TestCase):
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
- self.assert_(y is not x)
- self.assert_(y.foo is not x.foo)
+ self.assertTrue(y is not x)
+ self.assertTrue(y.foo is not x.foo)
def test_deepcopy_inst_getinitargs(self):
class C:
@@ -361,8 +361,8 @@ class TestCopy(unittest.TestCase):
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
- self.assert_(y is not x)
- self.assert_(y.foo is not x.foo)
+ self.assertTrue(y is not x)
+ self.assertTrue(y.foo is not x.foo)
def test_deepcopy_inst_getstate(self):
class C:
@@ -375,8 +375,8 @@ class TestCopy(unittest.TestCase):
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
- self.assert_(y is not x)
- self.assert_(y.foo is not x.foo)
+ self.assertTrue(y is not x)
+ self.assertTrue(y.foo is not x.foo)
def test_deepcopy_inst_setstate(self):
class C:
@@ -389,8 +389,8 @@ class TestCopy(unittest.TestCase):
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
- self.assert_(y is not x)
- self.assert_(y.foo is not x.foo)
+ self.assertTrue(y is not x)
+ self.assertTrue(y.foo is not x.foo)
def test_deepcopy_inst_getstate_setstate(self):
class C:
@@ -405,8 +405,8 @@ class TestCopy(unittest.TestCase):
x = C([42])
y = copy.deepcopy(x)
self.assertEqual(y, x)
- self.assert_(y is not x)
- self.assert_(y.foo is not x.foo)
+ self.assertTrue(y is not x)
+ self.assertTrue(y.foo is not x.foo)
def test_deepcopy_reflexive_inst(self):
class C:
@@ -414,8 +414,8 @@ class TestCopy(unittest.TestCase):
x = C()
x.foo = x
y = copy.deepcopy(x)
- self.assert_(y is not x)
- self.assert_(y.foo is y)
+ self.assertTrue(y is not x)
+ self.assertTrue(y.foo is y)
# _reconstruct()
@@ -425,9 +425,9 @@ class TestCopy(unittest.TestCase):
return ""
x = C()
y = copy.copy(x)
- self.assert_(y is x)
+ self.assertTrue(y is x)
y = copy.deepcopy(x)
- self.assert_(y is x)
+ self.assertTrue(y is x)
def test_reconstruct_nostate(self):
class C(object):
@@ -436,9 +436,9 @@ class TestCopy(unittest.TestCase):
x = C()
x.foo = 42
y = copy.copy(x)
- self.assert_(y.__class__ is x.__class__)
+ self.assertTrue(y.__class__ is x.__class__)
y = copy.deepcopy(x)
- self.assert_(y.__class__ is x.__class__)
+ self.assertTrue(y.__class__ is x.__class__)
def test_reconstruct_state(self):
class C(object):
@@ -452,7 +452,7 @@ class TestCopy(unittest.TestCase):
self.assertEqual(y, x)
y = copy.deepcopy(x)
self.assertEqual(y, x)
- self.assert_(y.foo is not x.foo)
+ self.assertTrue(y.foo is not x.foo)
def test_reconstruct_state_setstate(self):
class C(object):
@@ -468,7 +468,7 @@ class TestCopy(unittest.TestCase):
self.assertEqual(y, x)
y = copy.deepcopy(x)
self.assertEqual(y, x)
- self.assert_(y.foo is not x.foo)
+ self.assertTrue(y.foo is not x.foo)
def test_reconstruct_reflexive(self):
class C(object):
@@ -476,8 +476,8 @@ class TestCopy(unittest.TestCase):
x = C()
x.foo = x
y = copy.deepcopy(x)
- self.assert_(y is not x)
- self.assert_(y.foo is y)
+ self.assertTrue(y is not x)
+ self.assertTrue(y.foo is y)
# Additions for Python 2.3 and pickle protocol 2
@@ -491,12 +491,12 @@ class TestCopy(unittest.TestCase):
x = C([[1, 2], 3])
y = copy.copy(x)
self.assertEqual(x, y)
- self.assert_(x is not y)
- self.assert_(x[0] is y[0])
+ self.assertTrue(x is not y)
+ self.assertTrue(x[0] is y[0])
y = copy.deepcopy(x)
self.assertEqual(x, y)
- self.assert_(x is not y)
- self.assert_(x[0] is not y[0])
+ self.assertTrue(x is not y)
+ self.assertTrue(x[0] is not y[0])
def test_reduce_5tuple(self):
class C(dict):
@@ -508,12 +508,12 @@ class TestCopy(unittest.TestCase):
x = C([("foo", [1, 2]), ("bar", 3)])
y = copy.copy(x)
self.assertEqual(x, y)
- self.assert_(x is not y)
- self.assert_(x["foo"] is y["foo"])
+ self.assertTrue(x is not y)
+ self.assertTrue(x["foo"] is y["foo"])
y = copy.deepcopy(x)
self.assertEqual(x, y)
- self.assert_(x is not y)
- self.assert_(x["foo"] is not y["foo"])
+ self.assertTrue(x is not y)
+ self.assertTrue(x["foo"] is not y["foo"])
def test_copy_slots(self):
class C(object):
@@ -521,7 +521,7 @@ class TestCopy(unittest.TestCase):
x = C()
x.foo = [42]
y = copy.copy(x)
- self.assert_(x.foo is y.foo)
+ self.assertTrue(x.foo is y.foo)
def test_deepcopy_slots(self):
class C(object):
@@ -530,7 +530,7 @@ class TestCopy(unittest.TestCase):
x.foo = [42]
y = copy.deepcopy(x)
self.assertEqual(x.foo, y.foo)
- self.assert_(x.foo is not y.foo)
+ self.assertTrue(x.foo is not y.foo)
def test_copy_list_subclass(self):
class C(list):
@@ -540,8 +540,8 @@ class TestCopy(unittest.TestCase):
y = copy.copy(x)
self.assertEqual(list(x), list(y))
self.assertEqual(x.foo, y.foo)
- self.assert_(x[0] is y[0])
- self.assert_(x.foo is y.foo)
+ self.assertTrue(x[0] is y[0])
+ self.assertTrue(x.foo is y.foo)
def test_deepcopy_list_subclass(self):
class C(list):
@@ -551,8 +551,8 @@ class TestCopy(unittest.TestCase):
y = copy.deepcopy(x)
self.assertEqual(list(x), list(y))
self.assertEqual(x.foo, y.foo)
- self.assert_(x[0] is not y[0])
- self.assert_(x.foo is not y.foo)
+ self.assertTrue(x[0] is not y[0])
+ self.assertTrue(x.foo is not y.foo)
def test_copy_tuple_subclass(self):
class C(tuple):
@@ -569,8 +569,8 @@ class TestCopy(unittest.TestCase):
self.assertEqual(tuple(x), ([1, 2], 3))
y = copy.deepcopy(x)
self.assertEqual(tuple(y), ([1, 2], 3))
- self.assert_(x is not y)
- self.assert_(x[0] is not y[0])
+ self.assertTrue(x is not y)
+ self.assertTrue(x[0] is not y[0])
def test_getstate_exc(self):
class EvilState(object):
diff --git a/Lib/test/test_copyreg.py b/Lib/test/test_copyreg.py
index 48e58ea29e..4fb89d0044 100644
--- a/Lib/test/test_copyreg.py
+++ b/Lib/test/test_copyreg.py
@@ -51,10 +51,10 @@ class CopyRegTestCase(unittest.TestCase):
mod, func, code)
copyreg.add_extension(mod, func, code)
# Should be in the registry.
- self.assert_(copyreg._extension_registry[mod, func] == code)
- self.assert_(copyreg._inverted_registry[code] == (mod, func))
+ self.assertTrue(copyreg._extension_registry[mod, func] == code)
+ self.assertTrue(copyreg._inverted_registry[code] == (mod, func))
# Shouldn't be in the cache.
- self.assert_(code not in copyreg._extension_cache)
+ self.assertTrue(code not in copyreg._extension_cache)
# Redundant registration should be OK.
copyreg.add_extension(mod, func, code) # shouldn't blow up
# Conflicting code.
@@ -81,7 +81,7 @@ class CopyRegTestCase(unittest.TestCase):
e.restore()
# Shouldn't be there anymore.
- self.assert_((mod, func) not in copyreg._extension_registry)
+ self.assertTrue((mod, func) not in copyreg._extension_registry)
# The code *may* be in copyreg._extension_registry, though, if
# we happened to pick on a registered code. So don't check for
# that.
diff --git a/Lib/test/test_csv.py b/Lib/test/test_csv.py
index 7eb3a7f20b..95105be4f3 100644
--- a/Lib/test/test_csv.py
+++ b/Lib/test/test_csv.py
@@ -315,7 +315,7 @@ class TestDialectRegistry(unittest.TestCase):
expected_dialects.sort()
csv.register_dialect(name, myexceltsv)
try:
- self.failUnless(csv.get_dialect(name).delimiter, '\t')
+ self.assertTrue(csv.get_dialect(name).delimiter, '\t')
got_dialects = csv.list_dialects()
got_dialects.sort()
self.assertEqual(expected_dialects, got_dialects)
@@ -326,8 +326,8 @@ class TestDialectRegistry(unittest.TestCase):
name = 'fedcba'
csv.register_dialect(name, delimiter=';')
try:
- self.failUnless(csv.get_dialect(name).delimiter, '\t')
- self.failUnless(list(csv.reader('X;Y;Z', name)), ['X', 'Y', 'Z'])
+ self.assertTrue(csv.get_dialect(name).delimiter, '\t')
+ self.assertTrue(list(csv.reader('X;Y;Z', name)), ['X', 'Y', 'Z'])
finally:
csv.unregister_dialect(name)
@@ -811,7 +811,7 @@ Stonecutters Seafood and Chop House, Lemont, IL, 12/19/02, Week Back
# given that all three lines in sample3 are equal,
# I think that any character could have been 'guessed' as the
# delimiter, depending on dictionary order
- self.assert_(dialect.delimiter in self.sample3)
+ self.assertTrue(dialect.delimiter in self.sample3)
dialect = sniffer.sniff(self.sample3, delimiters="?,")
self.assertEqual(dialect.delimiter, "?")
dialect = sniffer.sniff(self.sample3, delimiters="/,")
diff --git a/Lib/test/test_datetime.py b/Lib/test/test_datetime.py
index b9d5959dbe..8bf8420929 100644
--- a/Lib/test/test_datetime.py
+++ b/Lib/test/test_datetime.py
@@ -77,9 +77,9 @@ class TestTZInfo(unittest.TestCase):
def __init__(self, offset, name):
self.__offset = offset
self.__name = name
- self.failUnless(issubclass(NotEnough, tzinfo))
+ self.assertTrue(issubclass(NotEnough, tzinfo))
ne = NotEnough(3, "NotByALongShot")
- self.failUnless(isinstance(ne, tzinfo))
+ self.assertTrue(isinstance(ne, tzinfo))
dt = datetime.now()
self.assertRaises(NotImplementedError, ne.tzname, dt)
@@ -88,7 +88,7 @@ class TestTZInfo(unittest.TestCase):
def test_normal(self):
fo = FixedOffset(3, "Three")
- self.failUnless(isinstance(fo, tzinfo))
+ self.assertTrue(isinstance(fo, tzinfo))
for dt in datetime.now(), None:
self.assertEqual(fo.utcoffset(dt), timedelta(minutes=3))
self.assertEqual(fo.tzname(dt), "Three")
@@ -99,25 +99,25 @@ class TestTZInfo(unittest.TestCase):
# carry no data), but they need to be picklable anyway else
# concrete subclasses can't be pickled.
orig = tzinfo.__new__(tzinfo)
- self.failUnless(type(orig) is tzinfo)
+ self.assertTrue(type(orig) is tzinfo)
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
- self.failUnless(type(derived) is tzinfo)
+ self.assertTrue(type(derived) is tzinfo)
def test_pickling_subclass(self):
# Make sure we can pickle/unpickle an instance of a subclass.
offset = timedelta(minutes=-300)
orig = PicklableFixedOffset(offset, 'cookie')
- self.failUnless(isinstance(orig, tzinfo))
- self.failUnless(type(orig) is PicklableFixedOffset)
+ self.assertTrue(isinstance(orig, tzinfo))
+ self.assertTrue(type(orig) is PicklableFixedOffset)
self.assertEqual(orig.utcoffset(None), offset)
self.assertEqual(orig.tzname(None), 'cookie')
for pickler, unpickler, proto in pickle_choices:
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
- self.failUnless(isinstance(derived, tzinfo))
- self.failUnless(type(derived) is PicklableFixedOffset)
+ self.assertTrue(isinstance(derived, tzinfo))
+ self.assertTrue(type(derived) is PicklableFixedOffset)
self.assertEqual(derived.utcoffset(None), offset)
self.assertEqual(derived.tzname(None), 'cookie')
@@ -134,16 +134,16 @@ class HarmlessMixedComparison:
def test_harmless_mixed_comparison(self):
me = self.theclass(1, 1, 1)
- self.failIf(me == ())
- self.failUnless(me != ())
- self.failIf(() == me)
- self.failUnless(() != me)
+ self.assertFalse(me == ())
+ self.assertTrue(me != ())
+ self.assertFalse(() == me)
+ self.assertTrue(() != me)
- self.failUnless(me in [1, 20, [], me])
- self.failIf(me not in [1, 20, [], me])
+ self.assertTrue(me in [1, 20, [], me])
+ self.assertFalse(me not in [1, 20, [], me])
- self.failUnless([] in [me, 1, 20, []])
- self.failIf([] not in [me, 1, 20, []])
+ self.assertTrue([] in [me, 1, 20, []])
+ self.assertFalse([] not in [me, 1, 20, []])
def test_harmful_mixed_comparison(self):
me = self.theclass(1, 1, 1)
@@ -303,26 +303,26 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
t1 = timedelta(2, 3, 4)
t2 = timedelta(2, 3, 4)
self.assertEqual(t1, t2)
- self.failUnless(t1 <= t2)
- self.failUnless(t1 >= t2)
- self.failUnless(not t1 != t2)
- self.failUnless(not t1 < t2)
- self.failUnless(not t1 > t2)
+ self.assertTrue(t1 <= t2)
+ self.assertTrue(t1 >= t2)
+ self.assertTrue(not t1 != t2)
+ self.assertTrue(not t1 < t2)
+ self.assertTrue(not t1 > t2)
for args in (3, 3, 3), (2, 4, 4), (2, 3, 5):
t2 = timedelta(*args) # this is larger than t1
- self.failUnless(t1 < t2)
- self.failUnless(t2 > t1)
- self.failUnless(t1 <= t2)
- self.failUnless(t2 >= t1)
- self.failUnless(t1 != t2)
- self.failUnless(t2 != t1)
- self.failUnless(not t1 == t2)
- self.failUnless(not t2 == t1)
- self.failUnless(not t1 > t2)
- self.failUnless(not t2 < t1)
- self.failUnless(not t1 >= t2)
- self.failUnless(not t2 <= t1)
+ self.assertTrue(t1 < t2)
+ self.assertTrue(t2 > t1)
+ self.assertTrue(t1 <= t2)
+ self.assertTrue(t2 >= t1)
+ self.assertTrue(t1 != t2)
+ self.assertTrue(t2 != t1)
+ self.assertTrue(not t1 == t2)
+ self.assertTrue(not t2 == t1)
+ self.assertTrue(not t1 > t2)
+ self.assertTrue(not t2 < t1)
+ self.assertTrue(not t1 >= t2)
+ self.assertTrue(not t2 <= t1)
for badarg in OTHERSTUFF:
self.assertEqual(t1 == badarg, False)
@@ -368,7 +368,7 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
# Verify td -> string -> td identity.
s = repr(td)
- self.failUnless(s.startswith('datetime.'))
+ self.assertTrue(s.startswith('datetime.'))
s = s[9:]
td2 = eval(s)
self.assertEqual(td, td2)
@@ -378,10 +378,10 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
self.assertEqual(td, td2)
def test_resolution_info(self):
- self.assert_(isinstance(timedelta.min, timedelta))
- self.assert_(isinstance(timedelta.max, timedelta))
- self.assert_(isinstance(timedelta.resolution, timedelta))
- self.assert_(timedelta.max > timedelta.min)
+ self.assertTrue(isinstance(timedelta.min, timedelta))
+ self.assertTrue(isinstance(timedelta.max, timedelta))
+ self.assertTrue(isinstance(timedelta.resolution, timedelta))
+ self.assertTrue(timedelta.max > timedelta.min)
self.assertEqual(timedelta.min, timedelta(-999999999))
self.assertEqual(timedelta.max, timedelta(999999999, 24*3600-1, 1e6-1))
self.assertEqual(timedelta.resolution, timedelta(0, 0, 1))
@@ -428,11 +428,11 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
(-1, 24*3600-1, 999999))
def test_bool(self):
- self.failUnless(timedelta(1))
- self.failUnless(timedelta(0, 1))
- self.failUnless(timedelta(0, 0, 1))
- self.failUnless(timedelta(microseconds=1))
- self.failUnless(not timedelta(0))
+ self.assertTrue(timedelta(1))
+ self.assertTrue(timedelta(0, 1))
+ self.assertTrue(timedelta(0, 0, 1))
+ self.assertTrue(timedelta(microseconds=1))
+ self.assertTrue(not timedelta(0))
def test_subclass_timedelta(self):
@@ -448,17 +448,17 @@ class TestTimeDelta(HarmlessMixedComparison, unittest.TestCase):
return round(sum)
t1 = T(days=1)
- self.assert_(type(t1) is T)
+ self.assertTrue(type(t1) is T)
self.assertEqual(t1.as_hours(), 24)
t2 = T(days=-1, seconds=-3600)
- self.assert_(type(t2) is T)
+ self.assertTrue(type(t2) is T)
self.assertEqual(t2.as_hours(), -25)
t3 = t1 + t2
- self.assert_(type(t3) is timedelta)
+ self.assertTrue(type(t3) is timedelta)
t4 = T.from_td(t3)
- self.assert_(type(t4) is T)
+ self.assertTrue(type(t4) is T)
self.assertEqual(t3.days, t4.days)
self.assertEqual(t3.seconds, t4.seconds)
self.assertEqual(t3.microseconds, t4.microseconds)
@@ -521,7 +521,7 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
self.theclass.today()):
# Verify dt -> string -> date identity.
s = repr(dt)
- self.failUnless(s.startswith('datetime.'))
+ self.assertTrue(s.startswith('datetime.'))
s = s[9:]
dt2 = eval(s)
self.assertEqual(dt, dt2)
@@ -755,7 +755,7 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
# It worked or it didn't. If it didn't, assume it's reason #2, and
# let the test pass if they're within half a second of each other.
- self.failUnless(today == todayagain or
+ self.assertTrue(today == todayagain or
abs(todayagain - today) < timedelta(seconds=0.5))
def test_weekday(self):
@@ -891,10 +891,10 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
self.assertEqual(b.__format__(fmt), 'B')
def test_resolution_info(self):
- self.assert_(isinstance(self.theclass.min, self.theclass))
- self.assert_(isinstance(self.theclass.max, self.theclass))
- self.assert_(isinstance(self.theclass.resolution, timedelta))
- self.assert_(self.theclass.max > self.theclass.min)
+ self.assertTrue(isinstance(self.theclass.min, self.theclass))
+ self.assertTrue(isinstance(self.theclass.max, self.theclass))
+ self.assertTrue(isinstance(self.theclass.resolution, timedelta))
+ self.assertTrue(self.theclass.max > self.theclass.min)
def test_extreme_timedelta(self):
big = self.theclass.max - self.theclass.min
@@ -943,26 +943,26 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
t1 = self.theclass(2, 3, 4)
t2 = self.theclass(2, 3, 4)
self.assertEqual(t1, t2)
- self.failUnless(t1 <= t2)
- self.failUnless(t1 >= t2)
- self.failUnless(not t1 != t2)
- self.failUnless(not t1 < t2)
- self.failUnless(not t1 > t2)
+ self.assertTrue(t1 <= t2)
+ self.assertTrue(t1 >= t2)
+ self.assertTrue(not t1 != t2)
+ self.assertTrue(not t1 < t2)
+ self.assertTrue(not t1 > t2)
for args in (3, 3, 3), (2, 4, 4), (2, 3, 5):
t2 = self.theclass(*args) # this is larger than t1
- self.failUnless(t1 < t2)
- self.failUnless(t2 > t1)
- self.failUnless(t1 <= t2)
- self.failUnless(t2 >= t1)
- self.failUnless(t1 != t2)
- self.failUnless(t2 != t1)
- self.failUnless(not t1 == t2)
- self.failUnless(not t2 == t1)
- self.failUnless(not t1 > t2)
- self.failUnless(not t2 < t1)
- self.failUnless(not t1 >= t2)
- self.failUnless(not t2 <= t1)
+ self.assertTrue(t1 < t2)
+ self.assertTrue(t2 > t1)
+ self.assertTrue(t1 <= t2)
+ self.assertTrue(t2 >= t1)
+ self.assertTrue(t1 != t2)
+ self.assertTrue(t2 != t1)
+ self.assertTrue(not t1 == t2)
+ self.assertTrue(not t2 == t1)
+ self.assertTrue(not t1 > t2)
+ self.assertTrue(not t2 < t1)
+ self.assertTrue(not t1 >= t2)
+ self.assertTrue(not t2 <= t1)
for badarg in OTHERSTUFF:
self.assertEqual(t1 == badarg, False)
@@ -1031,8 +1031,8 @@ class TestDate(HarmlessMixedComparison, unittest.TestCase):
def test_bool(self):
# All dates are considered true.
- self.failUnless(self.theclass.min)
- self.failUnless(self.theclass.max)
+ self.assertTrue(self.theclass.min)
+ self.assertTrue(self.theclass.max)
def test_strftime_out_of_range(self):
# For nasty technical reasons, we can't handle years before 1900.
@@ -1155,7 +1155,7 @@ class TestDateTime(TestDate):
self.theclass.now()):
# Verify dt -> string -> datetime identity.
s = repr(dt)
- self.failUnless(s.startswith('datetime.'))
+ self.assertTrue(s.startswith('datetime.'))
s = s[9:]
dt2 = eval(s)
self.assertEqual(dt, dt2)
@@ -1228,7 +1228,7 @@ class TestDateTime(TestDate):
dt2 = self.theclass(2002, 3, 1, 10, 0, 0)
dt3 = self.theclass(2002, 3, 1, 9, 0, 0)
self.assertEqual(dt1, dt3)
- self.assert_(dt2 > dt3)
+ self.assertTrue(dt2 > dt3)
# Make sure comparison doesn't forget microseconds, and isn't done
# via comparing a float timestamp (an IEEE double doesn't have enough
@@ -1239,7 +1239,7 @@ class TestDateTime(TestDate):
us = timedelta(microseconds=1)
dt2 = dt1 + us
self.assertEqual(dt2 - dt1, us)
- self.assert_(dt1 < dt2)
+ self.assertTrue(dt1 < dt2)
def test_strftime_with_bad_tzname_replace(self):
# verify ok if tzinfo.tzname().replace() returns a non-string
@@ -1420,28 +1420,28 @@ class TestDateTime(TestDate):
t1 = self.theclass(*args)
t2 = self.theclass(*args)
self.assertEqual(t1, t2)
- self.failUnless(t1 <= t2)
- self.failUnless(t1 >= t2)
- self.failUnless(not t1 != t2)
- self.failUnless(not t1 < t2)
- self.failUnless(not t1 > t2)
+ self.assertTrue(t1 <= t2)
+ self.assertTrue(t1 >= t2)
+ self.assertTrue(not t1 != t2)
+ self.assertTrue(not t1 < t2)
+ self.assertTrue(not t1 > t2)
for i in range(len(args)):
newargs = args[:]
newargs[i] = args[i] + 1
t2 = self.theclass(*newargs) # this is larger than t1
- self.failUnless(t1 < t2)
- self.failUnless(t2 > t1)
- self.failUnless(t1 <= t2)
- self.failUnless(t2 >= t1)
- self.failUnless(t1 != t2)
- self.failUnless(t2 != t1)
- self.failUnless(not t1 == t2)
- self.failUnless(not t2 == t1)
- self.failUnless(not t1 > t2)
- self.failUnless(not t2 < t1)
- self.failUnless(not t1 >= t2)
- self.failUnless(not t2 <= t1)
+ self.assertTrue(t1 < t2)
+ self.assertTrue(t2 > t1)
+ self.assertTrue(t1 <= t2)
+ self.assertTrue(t2 >= t1)
+ self.assertTrue(t1 != t2)
+ self.assertTrue(t2 != t1)
+ self.assertTrue(not t1 == t2)
+ self.assertTrue(not t2 == t1)
+ self.assertTrue(not t1 > t2)
+ self.assertTrue(not t2 < t1)
+ self.assertTrue(not t1 >= t2)
+ self.assertTrue(not t2 <= t1)
# A helper for timestamp constructor tests.
@@ -1520,7 +1520,7 @@ class TestDateTime(TestDate):
if abs(from_timestamp - from_now) <= tolerance:
break
# Else try again a few times.
- self.failUnless(abs(from_timestamp - from_now) <= tolerance)
+ self.assertTrue(abs(from_timestamp - from_now) <= tolerance)
def test_strptime(self):
import _strptime
@@ -1689,7 +1689,7 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase):
# Verify t -> string -> time identity.
s = repr(t)
- self.failUnless(s.startswith('datetime.'))
+ self.assertTrue(s.startswith('datetime.'))
s = s[9:]
t2 = eval(s)
self.assertEqual(t, t2)
@@ -1704,28 +1704,28 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase):
t1 = self.theclass(*args)
t2 = self.theclass(*args)
self.assertEqual(t1, t2)
- self.failUnless(t1 <= t2)
- self.failUnless(t1 >= t2)
- self.failUnless(not t1 != t2)
- self.failUnless(not t1 < t2)
- self.failUnless(not t1 > t2)
+ self.assertTrue(t1 <= t2)
+ self.assertTrue(t1 >= t2)
+ self.assertTrue(not t1 != t2)
+ self.assertTrue(not t1 < t2)
+ self.assertTrue(not t1 > t2)
for i in range(len(args)):
newargs = args[:]
newargs[i] = args[i] + 1
t2 = self.theclass(*newargs) # this is larger than t1
- self.failUnless(t1 < t2)
- self.failUnless(t2 > t1)
- self.failUnless(t1 <= t2)
- self.failUnless(t2 >= t1)
- self.failUnless(t1 != t2)
- self.failUnless(t2 != t1)
- self.failUnless(not t1 == t2)
- self.failUnless(not t2 == t1)
- self.failUnless(not t1 > t2)
- self.failUnless(not t2 < t1)
- self.failUnless(not t1 >= t2)
- self.failUnless(not t2 <= t1)
+ self.assertTrue(t1 < t2)
+ self.assertTrue(t2 > t1)
+ self.assertTrue(t1 <= t2)
+ self.assertTrue(t2 >= t1)
+ self.assertTrue(t1 != t2)
+ self.assertTrue(t2 != t1)
+ self.assertTrue(not t1 == t2)
+ self.assertTrue(not t2 == t1)
+ self.assertTrue(not t1 > t2)
+ self.assertTrue(not t2 < t1)
+ self.assertTrue(not t1 >= t2)
+ self.assertTrue(not t2 <= t1)
for badarg in OTHERSTUFF:
self.assertEqual(t1 == badarg, False)
@@ -1876,10 +1876,10 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase):
"%s(23, 15)" % name)
def test_resolution_info(self):
- self.assert_(isinstance(self.theclass.min, self.theclass))
- self.assert_(isinstance(self.theclass.max, self.theclass))
- self.assert_(isinstance(self.theclass.resolution, timedelta))
- self.assert_(self.theclass.max > self.theclass.min)
+ self.assertTrue(isinstance(self.theclass.min, self.theclass))
+ self.assertTrue(isinstance(self.theclass.max, self.theclass))
+ self.assertTrue(isinstance(self.theclass.resolution, timedelta))
+ self.assertTrue(self.theclass.max > self.theclass.min)
def test_pickling(self):
args = 20, 59, 16, 64**2
@@ -1899,12 +1899,12 @@ class TestTime(HarmlessMixedComparison, unittest.TestCase):
def test_bool(self):
cls = self.theclass
- self.failUnless(cls(1))
- self.failUnless(cls(0, 1))
- self.failUnless(cls(0, 0, 1))
- self.failUnless(cls(0, 0, 0, 1))
- self.failUnless(not cls(0))
- self.failUnless(not cls())
+ self.assertTrue(cls(1))
+ self.assertTrue(cls(0, 1))
+ self.assertTrue(cls(0, 0, 1))
+ self.assertTrue(cls(0, 0, 0, 1))
+ self.assertTrue(not cls(0))
+ self.assertTrue(not cls())
def test_replace(self):
cls = self.theclass
@@ -2001,7 +2001,7 @@ class TZInfoBase:
def utcoffset(self, dt): pass
b = BetterTry()
t = cls(1, 1, 1, tzinfo=b)
- self.failUnless(t.tzinfo is b)
+ self.assertTrue(t.tzinfo is b)
def test_utc_offset_out_of_bounds(self):
class Edgy(tzinfo):
@@ -2040,9 +2040,9 @@ class TZInfoBase:
for t in (cls(1, 1, 1),
cls(1, 1, 1, tzinfo=None),
cls(1, 1, 1, tzinfo=C1())):
- self.failUnless(t.utcoffset() is None)
- self.failUnless(t.dst() is None)
- self.failUnless(t.tzname() is None)
+ self.assertTrue(t.utcoffset() is None)
+ self.assertTrue(t.dst() is None)
+ self.assertTrue(t.tzname() is None)
class C3(tzinfo):
def utcoffset(self, dt): return timedelta(minutes=-1439)
@@ -2137,7 +2137,7 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase):
self.assertEqual(t.minute, 0)
self.assertEqual(t.second, 0)
self.assertEqual(t.microsecond, 0)
- self.failUnless(t.tzinfo is None)
+ self.assertTrue(t.tzinfo is None)
def test_zones(self):
est = FixedOffset(-300, "EST", 1)
@@ -2152,25 +2152,25 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase):
self.assertEqual(t1.tzinfo, est)
self.assertEqual(t2.tzinfo, utc)
self.assertEqual(t3.tzinfo, met)
- self.failUnless(t4.tzinfo is None)
+ self.assertTrue(t4.tzinfo is None)
self.assertEqual(t5.tzinfo, utc)
self.assertEqual(t1.utcoffset(), timedelta(minutes=-300))
self.assertEqual(t2.utcoffset(), timedelta(minutes=0))
self.assertEqual(t3.utcoffset(), timedelta(minutes=60))
- self.failUnless(t4.utcoffset() is None)
+ self.assertTrue(t4.utcoffset() is None)
self.assertRaises(TypeError, t1.utcoffset, "no args")
self.assertEqual(t1.tzname(), "EST")
self.assertEqual(t2.tzname(), "UTC")
self.assertEqual(t3.tzname(), "MET")
- self.failUnless(t4.tzname() is None)
+ self.assertTrue(t4.tzname() is None)
self.assertRaises(TypeError, t1.tzname, "no args")
self.assertEqual(t1.dst(), timedelta(minutes=1))
self.assertEqual(t2.dst(), timedelta(minutes=-2))
self.assertEqual(t3.dst(), timedelta(minutes=3))
- self.failUnless(t4.dst() is None)
+ self.assertTrue(t4.dst() is None)
self.assertRaises(TypeError, t1.dst, "no args")
self.assertEqual(hash(t1), hash(t2))
@@ -2246,7 +2246,7 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase):
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertEqual(orig, derived)
- self.failUnless(isinstance(derived.tzinfo, PicklableFixedOffset))
+ self.assertTrue(isinstance(derived.tzinfo, PicklableFixedOffset))
self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
self.assertEqual(derived.tzname(), 'cookie')
@@ -2255,20 +2255,20 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase):
cls = self.theclass
t = cls(0, tzinfo=FixedOffset(-300, ""))
- self.failUnless(t)
+ self.assertTrue(t)
t = cls(5, tzinfo=FixedOffset(-300, ""))
- self.failUnless(t)
+ self.assertTrue(t)
t = cls(5, tzinfo=FixedOffset(300, ""))
- self.failUnless(not t)
+ self.assertTrue(not t)
t = cls(23, 59, tzinfo=FixedOffset(23*60 + 59, ""))
- self.failUnless(not t)
+ self.assertTrue(not t)
# Mostly ensuring this doesn't overflow internally.
t = cls(0, tzinfo=FixedOffset(23*60 + 59, ""))
- self.failUnless(t)
+ self.assertTrue(t)
# But this should yield a value error -- the utcoffset is bogus.
t = cls(0, tzinfo=FixedOffset(24*60, ""))
@@ -2302,13 +2302,13 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase):
# Ensure we can get rid of a tzinfo.
self.assertEqual(base.tzname(), "+100")
base2 = base.replace(tzinfo=None)
- self.failUnless(base2.tzinfo is None)
- self.failUnless(base2.tzname() is None)
+ self.assertTrue(base2.tzinfo is None)
+ self.assertTrue(base2.tzname() is None)
# Ensure we can add one.
base3 = base2.replace(tzinfo=z100)
self.assertEqual(base, base3)
- self.failUnless(base.tzinfo is base3.tzinfo)
+ self.assertTrue(base.tzinfo is base3.tzinfo)
# Out of bounds.
base = cls(1)
@@ -2345,7 +2345,7 @@ class TestTimeTZ(TestTime, TZInfoBase, unittest.TestCase):
# But if they're not identical, it isn't ignored.
t2 = t2.replace(tzinfo=Varies())
- self.failUnless(t1 < t2) # t1's offset counter still going up
+ self.assertTrue(t1 < t2) # t1's offset counter still going up
def test_subclass_timetz(self):
@@ -2401,9 +2401,9 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
tzinfo=FixedOffset(-1439, ""))
# Make sure those compare correctly, and w/o overflow.
- self.failUnless(t1 < t2)
- self.failUnless(t1 != t2)
- self.failUnless(t2 > t1)
+ self.assertTrue(t1 < t2)
+ self.assertTrue(t1 != t2)
+ self.assertTrue(t2 > t1)
self.assertEqual(t1, t1)
self.assertEqual(t2, t2)
@@ -2415,21 +2415,21 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
# Change t1 not to subtract a minute, and t1 should be larger.
t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(0, ""))
- self.failUnless(t1 > t2)
+ self.assertTrue(t1 > t2)
# Change t1 to subtract 2 minutes, and t1 should be smaller.
t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(2, ""))
- self.failUnless(t1 < t2)
+ self.assertTrue(t1 < t2)
# Back to the original t1, but make seconds resolve it.
t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""),
second=1)
- self.failUnless(t1 > t2)
+ self.assertTrue(t1 > t2)
# Likewise, but make microseconds resolve it.
t1 = self.theclass(1, 12, 31, 23, 59, tzinfo=FixedOffset(1, ""),
microsecond=1)
- self.failUnless(t1 > t2)
+ self.assertTrue(t1 > t2)
# Make t2 naive and it should fail.
t2 = self.theclass.min
@@ -2473,7 +2473,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
green = pickler.dumps(orig, proto)
derived = unpickler.loads(green)
self.assertEqual(orig, derived)
- self.failUnless(isinstance(derived.tzinfo,
+ self.assertTrue(isinstance(derived.tzinfo,
PicklableFixedOffset))
self.assertEqual(derived.utcoffset(), timedelta(minutes=-300))
self.assertEqual(derived.tzname(), 'cookie')
@@ -2544,7 +2544,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
tz55 = FixedOffset(-330, "west 5:30")
timeaware = now.time().replace(tzinfo=tz55)
nowaware = self.theclass.combine(now.date(), timeaware)
- self.failUnless(nowaware.tzinfo is tz55)
+ self.assertTrue(nowaware.tzinfo is tz55)
self.assertEqual(nowaware.timetz(), timeaware)
# Can't mix aware and non-aware.
@@ -2563,15 +2563,15 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
# Adding a delta should preserve tzinfo.
delta = timedelta(weeks=1, minutes=12, microseconds=5678)
nowawareplus = nowaware + delta
- self.failUnless(nowaware.tzinfo is tz55)
+ self.assertTrue(nowaware.tzinfo is tz55)
nowawareplus2 = delta + nowaware
- self.failUnless(nowawareplus2.tzinfo is tz55)
+ self.assertTrue(nowawareplus2.tzinfo is tz55)
self.assertEqual(nowawareplus, nowawareplus2)
# that - delta should be what we started with, and that - what we
# started with should be delta.
diff = nowawareplus - delta
- self.failUnless(diff.tzinfo is tz55)
+ self.assertTrue(diff.tzinfo is tz55)
self.assertEqual(nowaware, diff)
self.assertRaises(TypeError, lambda: delta - nowawareplus)
self.assertEqual(nowawareplus - nowaware, delta)
@@ -2580,7 +2580,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
tzr = FixedOffset(random.randrange(-1439, 1440), "randomtimezone")
# Attach it to nowawareplus.
nowawareplus = nowawareplus.replace(tzinfo=tzr)
- self.failUnless(nowawareplus.tzinfo is tzr)
+ self.assertTrue(nowawareplus.tzinfo is tzr)
# Make sure the difference takes the timezone adjustments into account.
got = nowaware - nowawareplus
# Expected: (nowaware base - nowaware offset) -
@@ -2607,7 +2607,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
off42 = FixedOffset(42, "42")
another = meth(off42)
again = meth(tz=off42)
- self.failUnless(another.tzinfo is again.tzinfo)
+ self.assertTrue(another.tzinfo is again.tzinfo)
self.assertEqual(another.utcoffset(), timedelta(minutes=42))
# Bad argument with and w/o naming the keyword.
self.assertRaises(TypeError, meth, 16)
@@ -2624,7 +2624,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
utc = FixedOffset(0, "utc", 0)
for dummy in range(3):
now = datetime.now(weirdtz)
- self.failUnless(now.tzinfo is weirdtz)
+ self.assertTrue(now.tzinfo is weirdtz)
utcnow = datetime.utcnow().replace(tzinfo=utc)
now2 = utcnow.astimezone(weirdtz)
if abs(now - now2) < timedelta(seconds=30):
@@ -2645,7 +2645,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
off42 = FixedOffset(42, "42")
another = meth(ts, off42)
again = meth(ts, tz=off42)
- self.failUnless(another.tzinfo is again.tzinfo)
+ self.assertTrue(another.tzinfo is again.tzinfo)
self.assertEqual(another.utcoffset(), timedelta(minutes=42))
# Bad argument with and w/o naming the keyword.
self.assertRaises(TypeError, meth, ts, 16)
@@ -2840,13 +2840,13 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
# Ensure we can get rid of a tzinfo.
self.assertEqual(base.tzname(), "+100")
base2 = base.replace(tzinfo=None)
- self.failUnless(base2.tzinfo is None)
- self.failUnless(base2.tzname() is None)
+ self.assertTrue(base2.tzinfo is None)
+ self.assertTrue(base2.tzname() is None)
# Ensure we can add one.
base3 = base2.replace(tzinfo=z100)
self.assertEqual(base, base3)
- self.failUnless(base.tzinfo is base3.tzinfo)
+ self.assertTrue(base.tzinfo is base3.tzinfo)
# Out of bounds.
base = cls(2000, 2, 29)
@@ -2859,20 +2859,20 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
fm5h = FixedOffset(-timedelta(hours=5), "m300")
dt = self.theclass.now(tz=f44m)
- self.failUnless(dt.tzinfo is f44m)
+ self.assertTrue(dt.tzinfo is f44m)
# Replacing with degenerate tzinfo raises an exception.
self.assertRaises(ValueError, dt.astimezone, fnone)
# Ditto with None tz.
self.assertRaises(TypeError, dt.astimezone, None)
# Replacing with same tzinfo makes no change.
x = dt.astimezone(dt.tzinfo)
- self.failUnless(x.tzinfo is f44m)
+ self.assertTrue(x.tzinfo is f44m)
self.assertEqual(x.date(), dt.date())
self.assertEqual(x.time(), dt.time())
# Replacing with different tzinfo does adjust.
got = dt.astimezone(fm5h)
- self.failUnless(got.tzinfo is fm5h)
+ self.assertTrue(got.tzinfo is fm5h)
self.assertEqual(got.utcoffset(), timedelta(hours=-5))
expected = dt - dt.utcoffset() # in effect, convert to UTC
expected += fm5h.utcoffset(dt) # and from there to local time
@@ -2880,7 +2880,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
self.assertEqual(got.date(), expected.date())
self.assertEqual(got.time(), expected.time())
self.assertEqual(got.timetz(), expected.timetz())
- self.failUnless(got.tzinfo is expected.tzinfo)
+ self.assertTrue(got.tzinfo is expected.tzinfo)
self.assertEqual(got, expected)
def test_aware_subtract(self):
@@ -2955,7 +2955,7 @@ class TestDateTimeTZ(TestDateTime, TZInfoBase, unittest.TestCase):
# But if they're not identical, it isn't ignored.
t2 = t2.replace(tzinfo=Varies())
- self.failUnless(t1 < t2) # t1's offset counter still going up
+ self.assertTrue(t1 < t2) # t1's offset counter still going up
def test_subclass_datetimetz(self):
@@ -3306,10 +3306,10 @@ class Oddballs(unittest.TestCase):
# type comparison, despite that datetime is a subclass of date.
as_date = date.today()
as_datetime = datetime.combine(as_date, time())
- self.assert_(as_date != as_datetime)
- self.assert_(as_datetime != as_date)
- self.assert_(not as_date == as_datetime)
- self.assert_(not as_datetime == as_date)
+ self.assertTrue(as_date != as_datetime)
+ self.assertTrue(as_datetime != as_date)
+ self.assertTrue(not as_date == as_datetime)
+ self.assertTrue(not as_datetime == as_date)
self.assertRaises(TypeError, lambda: as_date < as_datetime)
self.assertRaises(TypeError, lambda: as_datetime < as_date)
self.assertRaises(TypeError, lambda: as_date <= as_datetime)
diff --git a/Lib/test/test_dbm.py b/Lib/test/test_dbm.py
index 35d12e43ba..818be453f4 100644
--- a/Lib/test/test_dbm.py
+++ b/Lib/test/test_dbm.py
@@ -57,7 +57,7 @@ class AnyDBMTestCase(unittest.TestCase):
return keys
def test_error(self):
- self.assert_(issubclass(self.module.error, IOError))
+ self.assertTrue(issubclass(self.module.error, IOError))
def test_anydbm_not_existing(self):
self.assertRaises(dbm.error, dbm.open, _fname)
@@ -154,9 +154,9 @@ class WhichDBTestCase(unittest.TestCase):
self.d[k] = v
self.assertEqual(sorted(self.d.keys()), sorted(k for (k, v) in a))
for k, v in a:
- self.assert_(k in self.d)
+ self.assertTrue(k in self.d)
self.assertEqual(self.d[k], v)
- self.assert_(b'xxx' not in self.d)
+ self.assertTrue(b'xxx' not in self.d)
self.assertRaises(KeyError, lambda: self.d[b'xxx'])
self.d.close()
diff --git a/Lib/test/test_dbm_dumb.py b/Lib/test/test_dbm_dumb.py
index e2964aad73..956eec6312 100644
--- a/Lib/test/test_dbm_dumb.py
+++ b/Lib/test/test_dbm_dumb.py
@@ -118,7 +118,7 @@ class DumbDBMTestCase(unittest.TestCase):
f['1'] = 'a'
f.close()
f = dumbdbm.open(_fname, 'r')
- self.assert_('\u00fc' in f)
+ self.assertTrue('\u00fc' in f)
self.assertEqual(f['\u00fc'.encode('utf-8')],
self._dict['\u00fc'.encode('utf-8')])
self.assertEqual(f[b'1'], b'a')
diff --git a/Lib/test/test_dbm_gnu.py b/Lib/test/test_dbm_gnu.py
index 857aeb1acc..2173b92afa 100755
--- a/Lib/test/test_dbm_gnu.py
+++ b/Lib/test/test_dbm_gnu.py
@@ -24,11 +24,11 @@ class TestGdbm(unittest.TestCase):
self.g[b'bytes'] = b'data'
key_set = set(self.g.keys())
self.assertEqual(key_set, set([b'a', b'bytes', b'12345678910']))
- self.assert_(b'a' in self.g)
+ self.assertTrue(b'a' in self.g)
self.assertEqual(self.g[b'bytes'], b'data')
key = self.g.firstkey()
while key:
- self.assert_(key in key_set)
+ self.assertTrue(key in key_set)
key_set.remove(key)
key = self.g.nextkey(key)
self.assertRaises(KeyError, lambda: self.g['xxx'])
@@ -66,7 +66,7 @@ class TestGdbm(unittest.TestCase):
self.g['x'] = 'x' * 10000
size1 = os.path.getsize(filename)
- self.assert_(size0 < size1)
+ self.assertTrue(size0 < size1)
del self.g['x']
# 'size' is supposed to be the same even after deleting an entry.
@@ -74,7 +74,7 @@ class TestGdbm(unittest.TestCase):
self.g.reorganize()
size2 = os.path.getsize(filename)
- self.assert_(size1 > size2 >= size0)
+ self.assertTrue(size1 > size2 >= size0)
def test_main():
diff --git a/Lib/test/test_dbm_ndbm.py b/Lib/test/test_dbm_ndbm.py
index c5e968fde4..141d4b3034 100755
--- a/Lib/test/test_dbm_ndbm.py
+++ b/Lib/test/test_dbm_ndbm.py
@@ -19,12 +19,12 @@ class DbmTestCase(unittest.TestCase):
def test_keys(self):
self.d = dbm.ndbm.open(self.filename, 'c')
- self.assert_(self.d.keys() == [])
+ self.assertTrue(self.d.keys() == [])
self.d['a'] = 'b'
self.d[b'bytes'] = b'data'
self.d['12345678910'] = '019237410982340912840198242'
self.d.keys()
- self.assert_(b'a' in self.d)
+ self.assertTrue(b'a' in self.d)
self.assertEqual(self.d[b'bytes'], b'data')
self.d.close()
diff --git a/Lib/test/test_decimal.py b/Lib/test/test_decimal.py
index ceca186820..43f2a08e67 100644
--- a/Lib/test/test_decimal.py
+++ b/Lib/test/test_decimal.py
@@ -507,7 +507,7 @@ class DecimalExplicitConstructionTest(unittest.TestCase):
# from int
d = nc.create_decimal(456)
- self.failUnless(isinstance(d, Decimal))
+ self.assertTrue(isinstance(d, Decimal))
self.assertEqual(nc.create_decimal(45678),
nc.create_decimal('457E+2'))
@@ -1050,12 +1050,12 @@ class DecimalArithmeticOperatorsTest(unittest.TestCase):
f = Decimal('2')
for x, y in [(n, n), (n, i), (i, n), (n, f), (f, n),
(s, n), (n, s), (s, i), (i, s), (s, f), (f, s), (s, s)]:
- self.assert_(x != y)
- self.assert_(not (x == y))
- self.assert_(not (x < y))
- self.assert_(not (x <= y))
- self.assert_(not (x > y))
- self.assert_(not (x >= y))
+ self.assertTrue(x != y)
+ self.assertTrue(not (x == y))
+ self.assertTrue(not (x < y))
+ self.assertTrue(not (x <= y))
+ self.assertTrue(not (x > y))
+ self.assertTrue(not (x >= y))
# The following are two functions used to test threading in the next class
@@ -1128,18 +1128,18 @@ class DecimalUsabilityTest(unittest.TestCase):
dc = Decimal('45')
#two Decimals
- self.failUnless(dc > da)
- self.failUnless(dc >= da)
- self.failUnless(da < dc)
- self.failUnless(da <= dc)
+ self.assertTrue(dc > da)
+ self.assertTrue(dc >= da)
+ self.assertTrue(da < dc)
+ self.assertTrue(da <= dc)
self.assertEqual(da, db)
- self.failUnless(da != dc)
- self.failUnless(da <= db)
- self.failUnless(da >= db)
+ self.assertTrue(da != dc)
+ self.assertTrue(da <= db)
+ self.assertTrue(da >= db)
#a Decimal and an int
- self.failUnless(dc > 23)
- self.failUnless(23 < dc)
+ self.assertTrue(dc > 23)
+ self.assertTrue(23 < dc)
self.assertEqual(dc, 45)
#a Decimal and uncomparable
@@ -1200,8 +1200,8 @@ class DecimalUsabilityTest(unittest.TestCase):
#the same hash that to an int
self.assertEqual(hash(Decimal(23)), hash(23))
self.assertRaises(TypeError, hash, Decimal('NaN'))
- self.assert_(hash(Decimal('Inf')))
- self.assert_(hash(Decimal('-Inf')))
+ self.assertTrue(hash(Decimal('Inf')))
+ self.assertTrue(hash(Decimal('-Inf')))
# check that the value of the hash doesn't depend on the
# current context (issue #1757)
@@ -1228,22 +1228,22 @@ class DecimalUsabilityTest(unittest.TestCase):
l2 = 28
#between Decimals
- self.failUnless(min(d1,d2) is d1)
- self.failUnless(min(d2,d1) is d1)
- self.failUnless(max(d1,d2) is d2)
- self.failUnless(max(d2,d1) is d2)
+ self.assertTrue(min(d1,d2) is d1)
+ self.assertTrue(min(d2,d1) is d1)
+ self.assertTrue(max(d1,d2) is d2)
+ self.assertTrue(max(d2,d1) is d2)
#between Decimal and long
- self.failUnless(min(d1,l2) is d1)
- self.failUnless(min(l2,d1) is d1)
- self.failUnless(max(l1,d2) is d2)
- self.failUnless(max(d2,l1) is d2)
+ self.assertTrue(min(d1,l2) is d1)
+ self.assertTrue(min(l2,d1) is d1)
+ self.assertTrue(max(l1,d2) is d2)
+ self.assertTrue(max(d2,l1) is d2)
def test_as_nonzero(self):
#as false
- self.failIf(Decimal(0))
+ self.assertFalse(Decimal(0))
#as true
- self.failUnless(Decimal('0.372'))
+ self.assertTrue(Decimal('0.372'))
def test_tostring_methods(self):
#Test str and repr methods.
@@ -1513,10 +1513,10 @@ class DecimalUsabilityTest(unittest.TestCase):
class DecimalPythonAPItests(unittest.TestCase):
def test_abc(self):
- self.assert_(issubclass(Decimal, numbers.Number))
- self.assert_(not issubclass(Decimal, numbers.Real))
- self.assert_(isinstance(Decimal(0), numbers.Number))
- self.assert_(not isinstance(Decimal(0), numbers.Real))
+ self.assertTrue(issubclass(Decimal, numbers.Number))
+ self.assertTrue(not issubclass(Decimal, numbers.Real))
+ self.assertTrue(isinstance(Decimal(0), numbers.Number))
+ self.assertTrue(not isinstance(Decimal(0), numbers.Real))
def test_pickle(self):
d = Decimal('-3.141590000')
@@ -1555,9 +1555,9 @@ class DecimalPythonAPItests(unittest.TestCase):
'0.1000000000000000055511151231257827021181583404541015625')
bigint = 12345678901234567890123456789
self.assertEqual(MyDecimal.from_float(bigint), MyDecimal(bigint))
- self.assert_(MyDecimal.from_float(float('nan')).is_qnan())
- self.assert_(MyDecimal.from_float(float('inf')).is_infinite())
- self.assert_(MyDecimal.from_float(float('-inf')).is_infinite())
+ self.assertTrue(MyDecimal.from_float(float('nan')).is_qnan())
+ self.assertTrue(MyDecimal.from_float(float('inf')).is_infinite())
+ self.assertTrue(MyDecimal.from_float(float('-inf')).is_infinite())
self.assertEqual(str(MyDecimal.from_float(float('nan'))),
str(Decimal('NaN')))
self.assertEqual(str(MyDecimal.from_float(float('inf'))),
@@ -1604,8 +1604,8 @@ class ContextAPItests(unittest.TestCase):
self.assertEqual(v1, v2)
def test_equality_with_other_types(self):
- self.assert_(Decimal(10) in ['a', 1.0, Decimal(10), (1,2), {}])
- self.assert_(Decimal(10) not in ['a', 1.0, (1,2), {}])
+ self.assertTrue(Decimal(10) in ['a', 1.0, Decimal(10), (1,2), {}])
+ self.assertTrue(Decimal(10) not in ['a', 1.0, (1,2), {}])
def test_copy(self):
# All copies should be deep
@@ -1625,9 +1625,9 @@ class WithStatementTest(unittest.TestCase):
with localcontext() as enter_ctx:
set_ctx = getcontext()
final_ctx = getcontext()
- self.assert_(orig_ctx is final_ctx, 'did not restore context correctly')
- self.assert_(orig_ctx is not set_ctx, 'did not copy the context')
- self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context')
+ self.assertTrue(orig_ctx is final_ctx, 'did not restore context correctly')
+ self.assertTrue(orig_ctx is not set_ctx, 'did not copy the context')
+ self.assertTrue(set_ctx is enter_ctx, '__enter__ returned wrong context')
def test_localcontextarg(self):
# Use a copy of the supplied context in the block
@@ -1636,10 +1636,10 @@ class WithStatementTest(unittest.TestCase):
with localcontext(new_ctx) as enter_ctx:
set_ctx = getcontext()
final_ctx = getcontext()
- self.assert_(orig_ctx is final_ctx, 'did not restore context correctly')
- self.assert_(set_ctx.prec == new_ctx.prec, 'did not set correct context')
- self.assert_(new_ctx is not set_ctx, 'did not copy the context')
- self.assert_(set_ctx is enter_ctx, '__enter__ returned wrong context')
+ self.assertTrue(orig_ctx is final_ctx, 'did not restore context correctly')
+ self.assertTrue(set_ctx.prec == new_ctx.prec, 'did not set correct context')
+ self.assertTrue(new_ctx is not set_ctx, 'did not copy the context')
+ self.assertTrue(set_ctx is enter_ctx, '__enter__ returned wrong context')
class ContextFlags(unittest.TestCase):
def test_flags_irrelevant(self):
diff --git a/Lib/test/test_defaultdict.py b/Lib/test/test_defaultdict.py
index 00bd9dc516..35468b4b4f 100644
--- a/Lib/test/test_defaultdict.py
+++ b/Lib/test/test_defaultdict.py
@@ -25,21 +25,21 @@ class TestDefaultDict(unittest.TestCase):
d1[13]
d1[14]
self.assertEqual(d1, {12: [42, 24], 13: [], 14: []})
- self.assert_(d1[12] is not d1[13] is not d1[14])
+ self.assertTrue(d1[12] is not d1[13] is not d1[14])
d2 = defaultdict(list, foo=1, bar=2)
self.assertEqual(d2.default_factory, list)
self.assertEqual(d2, {"foo": 1, "bar": 2})
self.assertEqual(d2["foo"], 1)
self.assertEqual(d2["bar"], 2)
self.assertEqual(d2[42], [])
- self.assert_("foo" in d2)
- self.assert_("foo" in d2.keys())
- self.assert_("bar" in d2)
- self.assert_("bar" in d2.keys())
- self.assert_(42 in d2)
- self.assert_(42 in d2.keys())
- self.assert_(12 not in d2)
- self.assert_(12 not in d2.keys())
+ self.assertTrue("foo" in d2)
+ self.assertTrue("foo" in d2.keys())
+ self.assertTrue("bar" in d2)
+ self.assertTrue("bar" in d2.keys())
+ self.assertTrue(42 in d2)
+ self.assertTrue(42 in d2.keys())
+ self.assertTrue(12 not in d2)
+ self.assertTrue(12 not in d2.keys())
d2.default_factory = None
self.assertEqual(d2.default_factory, None)
try:
@@ -68,7 +68,7 @@ class TestDefaultDict(unittest.TestCase):
self.assertEqual(repr(d2), "defaultdict(<class 'int'>, {12: 42})")
def foo(): return 43
d3 = defaultdict(foo)
- self.assert_(d3.default_factory is foo)
+ self.assertTrue(d3.default_factory is foo)
d3[13]
self.assertEqual(repr(d3), "defaultdict(%s, {13: 43})" % repr(foo))
@@ -127,7 +127,7 @@ class TestDefaultDict(unittest.TestCase):
d2 = copy.deepcopy(d1)
self.assertEqual(d2.default_factory, foobar)
self.assertEqual(d2, d1)
- self.assert_(d1[1] is not d2[1])
+ self.assertTrue(d1[1] is not d2[1])
d1.default_factory = list
d2 = copy.deepcopy(d1)
self.assertEqual(d2.default_factory, list)
@@ -150,7 +150,7 @@ class TestDefaultDict(unittest.TestCase):
def _factory(self):
return []
d = sub()
- self.assert_(repr(d).startswith(
+ self.assertTrue(repr(d).startswith(
"defaultdict(<bound method sub._factory of defaultdict(..."))
# NOTE: printing a subclass of a builtin type does not call its
diff --git a/Lib/test/test_deque.py b/Lib/test/test_deque.py
index fab5a7c660..1a03188e12 100644
--- a/Lib/test/test_deque.py
+++ b/Lib/test/test_deque.py
@@ -188,9 +188,9 @@ class TestBasic(unittest.TestCase):
self.assertEqual(len(d), n-i)
j = random.randrange(-len(d), len(d))
val = d[j]
- self.assert_(val in d)
+ self.assertTrue(val in d)
del d[j]
- self.assert_(val not in d)
+ self.assertTrue(val not in d)
self.assertEqual(len(d), 0)
def test_rotate(self):
@@ -291,7 +291,7 @@ class TestBasic(unittest.TestCase):
self.assertRaises(RuntimeError, d.remove, 'c')
for x, y in zip(d, e):
# verify that original order and values are retained.
- self.assert_(x is y)
+ self.assertTrue(x is y)
# Handle evil mutator
for match in (True, False):
@@ -305,7 +305,7 @@ class TestBasic(unittest.TestCase):
e = eval(repr(d))
self.assertEqual(list(d), list(e))
d.append(d)
- self.assert_('...' in repr(d))
+ self.assertTrue('...' in repr(d))
def test_print(self):
d = deque(range(200))
@@ -461,7 +461,7 @@ class TestBasic(unittest.TestCase):
obj.x = iter(container)
del obj, container
gc.collect()
- self.assert_(ref() is None, "Cycle was not collected")
+ self.assertTrue(ref() is None, "Cycle was not collected")
class TestVariousIteratorArgs(unittest.TestCase):
diff --git a/Lib/test/test_descr.py b/Lib/test/test_descr.py
index ac5ab6832b..e447d5a0f9 100644
--- a/Lib/test/test_descr.py
+++ b/Lib/test/test_descr.py
@@ -387,12 +387,12 @@ class ClassPropertiesAndMethods(unittest.TestCase):
def test_python_dicts(self):
# Testing Python subclass of dict...
- self.assert_(issubclass(dict, dict))
- self.assert_(isinstance({}, dict))
+ self.assertTrue(issubclass(dict, dict))
+ self.assertTrue(isinstance({}, dict))
d = dict()
self.assertEqual(d, {})
- self.assert_(d.__class__ is dict)
- self.assert_(isinstance(d, dict))
+ self.assertTrue(d.__class__ is dict)
+ self.assertTrue(isinstance(d, dict))
class C(dict):
state = -1
def __init__(self_local, *a, **kw):
@@ -405,13 +405,13 @@ class ClassPropertiesAndMethods(unittest.TestCase):
def __getitem__(self, key):
return self.get(key, 0)
def __setitem__(self_local, key, value):
- self.assert_(isinstance(key, type(0)))
+ self.assertTrue(isinstance(key, type(0)))
dict.__setitem__(self_local, key, value)
def setstate(self, state):
self.state = state
def getstate(self):
return self.state
- self.assert_(issubclass(C, dict))
+ self.assertTrue(issubclass(C, dict))
a1 = C(12)
self.assertEqual(a1.state, 12)
a2 = C(foo=1, bar=2)
@@ -504,7 +504,7 @@ class ClassPropertiesAndMethods(unittest.TestCase):
return 42
self.assertEqual(C.name, 'C')
self.assertEqual(C.bases, ())
- self.assert_('spam' in C.dict)
+ self.assertTrue('spam' in C.dict)
c = C()
self.assertEqual(c.spam(), 42)
@@ -569,7 +569,7 @@ class ClassPropertiesAndMethods(unittest.TestCase):
def _set_x(self, x):
self.__x = -x
a = A()
- self.assert_(not hasattr(a, "x"))
+ self.assertTrue(not hasattr(a, "x"))
a.x = 12
self.assertEqual(a.x, 12)
self.assertEqual(a._A__x, -12)
@@ -960,7 +960,7 @@ order (MRO) for bases """
x = C()
x.foo = 5
self.assertEqual(x.foo, 5)
- self.assert_(type(slots[0]) is str)
+ self.assertTrue(type(slots[0]) is str)
# this used to leak references
try:
class C(object):
@@ -1049,7 +1049,7 @@ order (MRO) for bases """
class D(object):
__slots__ = ["__dict__"]
a = D()
- self.assert_(hasattr(a, "__dict__"))
+ self.assertTrue(hasattr(a, "__dict__"))
self.assertFalse(hasattr(a, "__weakref__"))
a.foo = 42
self.assertEqual(a.__dict__, {"foo": 42})
@@ -1057,7 +1057,7 @@ order (MRO) for bases """
class W(object):
__slots__ = ["__weakref__"]
a = W()
- self.assert_(hasattr(a, "__weakref__"))
+ self.assertTrue(hasattr(a, "__weakref__"))
self.assertFalse(hasattr(a, "__dict__"))
try:
a.foo = 42
@@ -1069,16 +1069,16 @@ order (MRO) for bases """
class C1(W, D):
__slots__ = []
a = C1()
- self.assert_(hasattr(a, "__dict__"))
- self.assert_(hasattr(a, "__weakref__"))
+ self.assertTrue(hasattr(a, "__dict__"))
+ self.assertTrue(hasattr(a, "__weakref__"))
a.foo = 42
self.assertEqual(a.__dict__, {"foo": 42})
class C2(D, W):
__slots__ = []
a = C2()
- self.assert_(hasattr(a, "__dict__"))
- self.assert_(hasattr(a, "__weakref__"))
+ self.assertTrue(hasattr(a, "__dict__"))
+ self.assertTrue(hasattr(a, "__weakref__"))
a.foo = 42
self.assertEqual(a.__dict__, {"foo": 42})
@@ -1094,7 +1094,7 @@ order (MRO) for bases """
MyABC.register(Unrelated)
u = Unrelated()
- self.assert_(isinstance(u, MyABC))
+ self.assertTrue(isinstance(u, MyABC))
# This used to crash
self.assertRaises(TypeError, MyABC.a.__set__, u, 3)
@@ -1350,7 +1350,7 @@ order (MRO) for bases """
class E: # *not* subclassing from C
foo = C.foo
self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
- self.assert_(repr(C.foo.__get__(C())).startswith("<bound method "))
+ self.assertTrue(repr(C.foo.__get__(C())).startswith("<bound method "))
def test_compattr(self):
# Testing computed attributes...
@@ -1537,7 +1537,7 @@ order (MRO) for bases """
class E(object):
foo = C.foo
self.assertEqual(E().foo.__func__, C.foo) # i.e., unbound
- self.assert_(repr(C.foo.__get__(C(1))).startswith("<bound method "))
+ self.assertTrue(repr(C.foo.__get__(C(1))).startswith("<bound method "))
def test_special_method_lookup(self):
# The lookup of special methods bypasses __getattr__ and
@@ -1648,21 +1648,21 @@ order (MRO) for bases """
raise IndexError
c1 = C()
c2 = C()
- self.assert_(not not c1) # What?
+ self.assertTrue(not not c1) # What?
self.assertNotEqual(id(c1), id(c2))
hash(c1)
hash(c2)
self.assertEqual(c1, c1)
- self.assert_(c1 != c2)
- self.assert_(not c1 != c1)
- self.assert_(not c1 == c2)
+ self.assertTrue(c1 != c2)
+ self.assertTrue(not c1 != c1)
+ self.assertTrue(not c1 == c2)
# Note that the module name appears in str/repr, and that varies
# depending on whether this test is run standalone or from a framework.
- self.assert_(str(c1).find('C object at ') >= 0)
+ self.assertTrue(str(c1).find('C object at ') >= 0)
self.assertEqual(str(c1), repr(c1))
- self.assert_(-1 not in c1)
+ self.assertTrue(-1 not in c1)
for i in range(10):
- self.assert_(i in c1)
+ self.assertTrue(i in c1)
self.assertFalse(10 in c1)
# Test the default behavior for dynamic classes
class D(object):
@@ -1671,21 +1671,21 @@ order (MRO) for bases """
raise IndexError
d1 = D()
d2 = D()
- self.assert_(not not d1)
+ self.assertTrue(not not d1)
self.assertNotEqual(id(d1), id(d2))
hash(d1)
hash(d2)
self.assertEqual(d1, d1)
self.assertNotEqual(d1, d2)
- self.assert_(not d1 != d1)
- self.assert_(not d1 == d2)
+ self.assertTrue(not d1 != d1)
+ self.assertTrue(not d1 == d2)
# Note that the module name appears in str/repr, and that varies
# depending on whether this test is run standalone or from a framework.
- self.assert_(str(d1).find('D object at ') >= 0)
+ self.assertTrue(str(d1).find('D object at ') >= 0)
self.assertEqual(str(d1), repr(d1))
- self.assert_(-1 not in d1)
+ self.assertTrue(-1 not in d1)
for i in range(10):
- self.assert_(i in d1)
+ self.assertTrue(i in d1)
self.assertFalse(10 in d1)
# Test overridden behavior
class Proxy(object):
@@ -1717,22 +1717,22 @@ order (MRO) for bases """
p1 = Proxy(1)
p_1 = Proxy(-1)
self.assertFalse(p0)
- self.assert_(not not p1)
+ self.assertTrue(not not p1)
self.assertEqual(hash(p0), hash(0))
self.assertEqual(p0, p0)
self.assertNotEqual(p0, p1)
- self.assert_(not p0 != p0)
+ self.assertTrue(not p0 != p0)
self.assertEqual(not p0, p1)
- self.assert_(p0 < p1)
- self.assert_(p0 <= p1)
- self.assert_(p1 > p0)
- self.assert_(p1 >= p0)
+ self.assertTrue(p0 < p1)
+ self.assertTrue(p0 <= p1)
+ self.assertTrue(p1 > p0)
+ self.assertTrue(p1 >= p0)
self.assertEqual(str(p0), "Proxy:0")
self.assertEqual(repr(p0), "Proxy(0)")
p10 = Proxy(range(10))
self.assertFalse(-1 in p10)
for i in range(10):
- self.assert_(i in p10)
+ self.assertTrue(i in p10)
self.assertFalse(10 in p10)
def test_weakrefs(self):
@@ -1753,7 +1753,7 @@ order (MRO) for bases """
try:
weakref.ref(no)
except TypeError as msg:
- self.assert_(str(msg).find("weak reference") >= 0)
+ self.assertTrue(str(msg).find("weak reference") >= 0)
else:
self.fail("weakref.ref(no) should be illegal")
class Weak(object):
@@ -1790,18 +1790,18 @@ order (MRO) for bases """
self.assertFalse(hasattr(a, "x"))
raw = C.__dict__['x']
- self.assert_(isinstance(raw, property))
+ self.assertTrue(isinstance(raw, property))
attrs = dir(raw)
- self.assert_("__doc__" in attrs)
- self.assert_("fget" in attrs)
- self.assert_("fset" in attrs)
- self.assert_("fdel" in attrs)
+ self.assertTrue("__doc__" in attrs)
+ self.assertTrue("fget" in attrs)
+ self.assertTrue("fset" in attrs)
+ self.assertTrue("fdel" in attrs)
self.assertEqual(raw.__doc__, "I'm the x property.")
- self.assert_(raw.fget is C.__dict__['getx'])
- self.assert_(raw.fset is C.__dict__['setx'])
- self.assert_(raw.fdel is C.__dict__['delx'])
+ self.assertTrue(raw.fget is C.__dict__['getx'])
+ self.assertTrue(raw.fset is C.__dict__['setx'])
+ self.assertTrue(raw.fdel is C.__dict__['delx'])
for attr in "__doc__", "fget", "fset", "fdel":
try:
@@ -1863,7 +1863,7 @@ order (MRO) for bases """
self.assertEqual(C.foo.__doc__, "hello")
self.assertFalse(hasattr(c, "foo"))
c.foo = -42
- self.assert_(hasattr(c, '_foo'))
+ self.assertTrue(hasattr(c, '_foo'))
self.assertEqual(c._foo, 42)
self.assertEqual(c.foo, 42)
del c.foo
@@ -2021,12 +2021,12 @@ order (MRO) for bases """
c = C()
self.assertEqual(interesting(dir(c)), cstuff)
- ## self.assert_('__self__' in dir(C.Cmethod))
+ ## self.assertTrue('__self__' in dir(C.Cmethod))
c.cdata = 2
c.cmethod = lambda self: 0
self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
- ## self.assert_('__self__' in dir(c.Cmethod))
+ ## self.assertTrue('__self__' in dir(c.Cmethod))
class A(C):
Adata = 1
@@ -2034,13 +2034,13 @@ order (MRO) for bases """
astuff = ['Adata', 'Amethod'] + cstuff
self.assertEqual(interesting(dir(A)), astuff)
- ## self.assert_('__self__' in dir(A.Amethod))
+ ## self.assertTrue('__self__' in dir(A.Amethod))
a = A()
self.assertEqual(interesting(dir(a)), astuff)
a.adata = 42
a.amethod = lambda self: 3
self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
- ## self.assert_('__self__' in dir(a.Amethod))
+ ## self.assertTrue('__self__' in dir(a.Amethod))
# Try a module subclass.
import sys
@@ -2224,13 +2224,13 @@ order (MRO) for bases """
a = hexint(12345)
self.assertEqual(a, 12345)
self.assertEqual(int(a), 12345)
- self.assert_(int(a).__class__ is int)
+ self.assertTrue(int(a).__class__ is int)
self.assertEqual(hash(a), hash(12345))
- self.assert_((+a).__class__ is int)
- self.assert_((a >> 0).__class__ is int)
- self.assert_((a << 0).__class__ is int)
- self.assert_((hexint(0) << 12).__class__ is int)
- self.assert_((hexint(0) >> 12).__class__ is int)
+ self.assertTrue((+a).__class__ is int)
+ self.assertTrue((a >> 0).__class__ is int)
+ self.assertTrue((a << 0).__class__ is int)
+ self.assertTrue((hexint(0) << 12).__class__ is int)
+ self.assertTrue((hexint(0) >> 12).__class__ is int)
class octlong(int):
__slots__ = []
@@ -2250,36 +2250,36 @@ order (MRO) for bases """
self.assertEqual(a, 12345)
self.assertEqual(int(a), 12345)
self.assertEqual(hash(a), hash(12345))
- self.assert_(int(a).__class__ is int)
- self.assert_((+a).__class__ is int)
- self.assert_((-a).__class__ is int)
- self.assert_((-octlong(0)).__class__ is int)
- self.assert_((a >> 0).__class__ is int)
- self.assert_((a << 0).__class__ is int)
- self.assert_((a - 0).__class__ is int)
- self.assert_((a * 1).__class__ is int)
- self.assert_((a ** 1).__class__ is int)
- self.assert_((a // 1).__class__ is int)
- self.assert_((1 * a).__class__ is int)
- self.assert_((a | 0).__class__ is int)
- self.assert_((a ^ 0).__class__ is int)
- self.assert_((a & -1).__class__ is int)
- self.assert_((octlong(0) << 12).__class__ is int)
- self.assert_((octlong(0) >> 12).__class__ is int)
- self.assert_(abs(octlong(0)).__class__ is int)
+ self.assertTrue(int(a).__class__ is int)
+ self.assertTrue((+a).__class__ is int)
+ self.assertTrue((-a).__class__ is int)
+ self.assertTrue((-octlong(0)).__class__ is int)
+ self.assertTrue((a >> 0).__class__ is int)
+ self.assertTrue((a << 0).__class__ is int)
+ self.assertTrue((a - 0).__class__ is int)
+ self.assertTrue((a * 1).__class__ is int)
+ self.assertTrue((a ** 1).__class__ is int)
+ self.assertTrue((a // 1).__class__ is int)
+ self.assertTrue((1 * a).__class__ is int)
+ self.assertTrue((a | 0).__class__ is int)
+ self.assertTrue((a ^ 0).__class__ is int)
+ self.assertTrue((a & -1).__class__ is int)
+ self.assertTrue((octlong(0) << 12).__class__ is int)
+ self.assertTrue((octlong(0) >> 12).__class__ is int)
+ self.assertTrue(abs(octlong(0)).__class__ is int)
# Because octlong overrides __add__, we can't check the absence of +0
# optimizations using octlong.
class longclone(int):
pass
a = longclone(1)
- self.assert_((a + 0).__class__ is int)
- self.assert_((0 + a).__class__ is int)
+ self.assertTrue((a + 0).__class__ is int)
+ self.assertTrue((0 + a).__class__ is int)
# Check that negative clones don't segfault
a = longclone(-1)
self.assertEqual(a.__dict__, {})
- self.assertEqual(int(a), -1) # self.assert_ PyNumber_Long() copies the sign bit
+ self.assertEqual(int(a), -1) # self.assertTrue PyNumber_Long() copies the sign bit
class precfloat(float):
__slots__ = ['prec']
@@ -2291,9 +2291,9 @@ order (MRO) for bases """
a = precfloat(12345)
self.assertEqual(a, 12345.0)
self.assertEqual(float(a), 12345.0)
- self.assert_(float(a).__class__ is float)
+ self.assertTrue(float(a).__class__ is float)
self.assertEqual(hash(a), hash(12345.0))
- self.assert_((+a).__class__ is float)
+ self.assertTrue((+a).__class__ is float)
class madcomplex(complex):
def __repr__(self):
@@ -2341,20 +2341,20 @@ order (MRO) for bases """
self.assertEqual(v, t)
a = madtuple((1,2,3,4,5))
self.assertEqual(tuple(a), (1,2,3,4,5))
- self.assert_(tuple(a).__class__ is tuple)
+ self.assertTrue(tuple(a).__class__ is tuple)
self.assertEqual(hash(a), hash((1,2,3,4,5)))
- self.assert_(a[:].__class__ is tuple)
- self.assert_((a * 1).__class__ is tuple)
- self.assert_((a * 0).__class__ is tuple)
- self.assert_((a + ()).__class__ is tuple)
+ self.assertTrue(a[:].__class__ is tuple)
+ self.assertTrue((a * 1).__class__ is tuple)
+ self.assertTrue((a * 0).__class__ is tuple)
+ self.assertTrue((a + ()).__class__ is tuple)
a = madtuple(())
self.assertEqual(tuple(a), ())
- self.assert_(tuple(a).__class__ is tuple)
- self.assert_((a + a).__class__ is tuple)
- self.assert_((a * 0).__class__ is tuple)
- self.assert_((a * 1).__class__ is tuple)
- self.assert_((a * 2).__class__ is tuple)
- self.assert_(a[:].__class__ is tuple)
+ self.assertTrue(tuple(a).__class__ is tuple)
+ self.assertTrue((a + a).__class__ is tuple)
+ self.assertTrue((a * 0).__class__ is tuple)
+ self.assertTrue((a * 1).__class__ is tuple)
+ self.assertTrue((a * 2).__class__ is tuple)
+ self.assertTrue(a[:].__class__ is tuple)
class madstring(str):
_rev = None
@@ -2376,48 +2376,48 @@ order (MRO) for bases """
self.assertEqual(u, s)
s = madstring("12345")
self.assertEqual(str(s), "12345")
- self.assert_(str(s).__class__ is str)
+ self.assertTrue(str(s).__class__ is str)
base = "\x00" * 5
s = madstring(base)
self.assertEqual(s, base)
self.assertEqual(str(s), base)
- self.assert_(str(s).__class__ is str)
+ self.assertTrue(str(s).__class__ is str)
self.assertEqual(hash(s), hash(base))
self.assertEqual({s: 1}[base], 1)
self.assertEqual({base: 1}[s], 1)
- self.assert_((s + "").__class__ is str)
+ self.assertTrue((s + "").__class__ is str)
self.assertEqual(s + "", base)
- self.assert_(("" + s).__class__ is str)
+ self.assertTrue(("" + s).__class__ is str)
self.assertEqual("" + s, base)
- self.assert_((s * 0).__class__ is str)
+ self.assertTrue((s * 0).__class__ is str)
self.assertEqual(s * 0, "")
- self.assert_((s * 1).__class__ is str)
+ self.assertTrue((s * 1).__class__ is str)
self.assertEqual(s * 1, base)
- self.assert_((s * 2).__class__ is str)
+ self.assertTrue((s * 2).__class__ is str)
self.assertEqual(s * 2, base + base)
- self.assert_(s[:].__class__ is str)
+ self.assertTrue(s[:].__class__ is str)
self.assertEqual(s[:], base)
- self.assert_(s[0:0].__class__ is str)
+ self.assertTrue(s[0:0].__class__ is str)
self.assertEqual(s[0:0], "")
- self.assert_(s.strip().__class__ is str)
+ self.assertTrue(s.strip().__class__ is str)
self.assertEqual(s.strip(), base)
- self.assert_(s.lstrip().__class__ is str)
+ self.assertTrue(s.lstrip().__class__ is str)
self.assertEqual(s.lstrip(), base)
- self.assert_(s.rstrip().__class__ is str)
+ self.assertTrue(s.rstrip().__class__ is str)
self.assertEqual(s.rstrip(), base)
identitytab = {}
- self.assert_(s.translate(identitytab).__class__ is str)
+ self.assertTrue(s.translate(identitytab).__class__ is str)
self.assertEqual(s.translate(identitytab), base)
- self.assert_(s.replace("x", "x").__class__ is str)
+ self.assertTrue(s.replace("x", "x").__class__ is str)
self.assertEqual(s.replace("x", "x"), base)
- self.assert_(s.ljust(len(s)).__class__ is str)
+ self.assertTrue(s.ljust(len(s)).__class__ is str)
self.assertEqual(s.ljust(len(s)), base)
- self.assert_(s.rjust(len(s)).__class__ is str)
+ self.assertTrue(s.rjust(len(s)).__class__ is str)
self.assertEqual(s.rjust(len(s)), base)
- self.assert_(s.center(len(s)).__class__ is str)
+ self.assertTrue(s.center(len(s)).__class__ is str)
self.assertEqual(s.center(len(s)), base)
- self.assert_(s.lower().__class__ is str)
+ self.assertTrue(s.lower().__class__ is str)
self.assertEqual(s.lower(), base)
class madunicode(str):
@@ -2436,47 +2436,47 @@ order (MRO) for bases """
base = "12345"
u = madunicode(base)
self.assertEqual(str(u), base)
- self.assert_(str(u).__class__ is str)
+ self.assertTrue(str(u).__class__ is str)
self.assertEqual(hash(u), hash(base))
self.assertEqual({u: 1}[base], 1)
self.assertEqual({base: 1}[u], 1)
- self.assert_(u.strip().__class__ is str)
+ self.assertTrue(u.strip().__class__ is str)
self.assertEqual(u.strip(), base)
- self.assert_(u.lstrip().__class__ is str)
+ self.assertTrue(u.lstrip().__class__ is str)
self.assertEqual(u.lstrip(), base)
- self.assert_(u.rstrip().__class__ is str)
+ self.assertTrue(u.rstrip().__class__ is str)
self.assertEqual(u.rstrip(), base)
- self.assert_(u.replace("x", "x").__class__ is str)
+ self.assertTrue(u.replace("x", "x").__class__ is str)
self.assertEqual(u.replace("x", "x"), base)
- self.assert_(u.replace("xy", "xy").__class__ is str)
+ self.assertTrue(u.replace("xy", "xy").__class__ is str)
self.assertEqual(u.replace("xy", "xy"), base)
- self.assert_(u.center(len(u)).__class__ is str)
+ self.assertTrue(u.center(len(u)).__class__ is str)
self.assertEqual(u.center(len(u)), base)
- self.assert_(u.ljust(len(u)).__class__ is str)
+ self.assertTrue(u.ljust(len(u)).__class__ is str)
self.assertEqual(u.ljust(len(u)), base)
- self.assert_(u.rjust(len(u)).__class__ is str)
+ self.assertTrue(u.rjust(len(u)).__class__ is str)
self.assertEqual(u.rjust(len(u)), base)
- self.assert_(u.lower().__class__ is str)
+ self.assertTrue(u.lower().__class__ is str)
self.assertEqual(u.lower(), base)
- self.assert_(u.upper().__class__ is str)
+ self.assertTrue(u.upper().__class__ is str)
self.assertEqual(u.upper(), base)
- self.assert_(u.capitalize().__class__ is str)
+ self.assertTrue(u.capitalize().__class__ is str)
self.assertEqual(u.capitalize(), base)
- self.assert_(u.title().__class__ is str)
+ self.assertTrue(u.title().__class__ is str)
self.assertEqual(u.title(), base)
- self.assert_((u + "").__class__ is str)
+ self.assertTrue((u + "").__class__ is str)
self.assertEqual(u + "", base)
- self.assert_(("" + u).__class__ is str)
+ self.assertTrue(("" + u).__class__ is str)
self.assertEqual("" + u, base)
- self.assert_((u * 0).__class__ is str)
+ self.assertTrue((u * 0).__class__ is str)
self.assertEqual(u * 0, "")
- self.assert_((u * 1).__class__ is str)
+ self.assertTrue((u * 1).__class__ is str)
self.assertEqual(u * 1, base)
- self.assert_((u * 2).__class__ is str)
+ self.assertTrue((u * 2).__class__ is str)
self.assertEqual(u * 2, base + base)
- self.assert_(u[:].__class__ is str)
+ self.assertTrue(u[:].__class__ is str)
self.assertEqual(u[:], base)
- self.assert_(u[0:0].__class__ is str)
+ self.assertTrue(u[0:0].__class__ is str)
self.assertEqual(u[0:0], "")
class sublist(list):
@@ -2595,7 +2595,7 @@ order (MRO) for bases """
self.assertEqual(d[cistr('one')], 1)
self.assertEqual(d[cistr('tWo')], 2)
self.assertEqual(d[cistr('THrEE')], 3)
- self.assert_(cistr('ONe') in d)
+ self.assertTrue(cistr('ONe') in d)
self.assertEqual(d.get(cistr('thrEE')), 3)
def test_classic_comparisons(self):
@@ -2652,13 +2652,13 @@ order (MRO) for bases """
for x in 1, 2, 3:
for y in 1, 2, 3:
for op in "<", "<=", "==", "!=", ">", ">=":
- self.assert_(eval("c[x] %s c[y]" % op) ==
+ self.assertTrue(eval("c[x] %s c[y]" % op) ==
eval("x %s y" % op),
"x=%d, y=%d" % (x, y))
- self.assert_(eval("c[x] %s y" % op) ==
+ self.assertTrue(eval("c[x] %s y" % op) ==
eval("x %s y" % op),
"x=%d, y=%d" % (x, y))
- self.assert_(eval("x %s c[y]" % op) ==
+ self.assertTrue(eval("x %s c[y]" % op) ==
eval("x %s y" % op),
"x=%d, y=%d" % (x, y))
@@ -2731,11 +2731,11 @@ order (MRO) for bases """
for x in 1, 2, 3:
for y in 1, 2, 3:
for op in "<", "<=", "==", "!=", ">", ">=":
- self.assert_(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
+ self.assertTrue(eval("c[x] %s c[y]" % op) == eval("x %s y" % op),
"x=%d, y=%d" % (x, y))
- self.assert_(eval("c[x] %s y" % op) == eval("x %s y" % op),
+ self.assertTrue(eval("c[x] %s y" % op) == eval("x %s y" % op),
"x=%d, y=%d" % (x, y))
- self.assert_(eval("x %s c[y]" % op) == eval("x %s y" % op),
+ self.assertTrue(eval("x %s c[y]" % op) == eval("x %s y" % op),
"x=%d, y=%d" % (x, y))
def test_descrdoc(self):
@@ -2775,9 +2775,9 @@ order (MRO) for bases """
for cls2 in C, D, E, F:
x = cls()
x.__class__ = cls2
- self.assert_(x.__class__ is cls2)
+ self.assertTrue(x.__class__ is cls2)
x.__class__ = cls
- self.assert_(x.__class__ is cls)
+ self.assertTrue(x.__class__ is cls)
def cant(x, C):
try:
x.__class__ = C
@@ -2833,11 +2833,11 @@ order (MRO) for bases """
x = cls()
x.a = 1
x.__class__ = cls2
- self.assert_(x.__class__ is cls2,
+ self.assertTrue(x.__class__ is cls2,
"assigning %r as __class__ for %r silently failed" % (cls2, x))
self.assertEqual(x.a, 1)
x.__class__ = cls
- self.assert_(x.__class__ is cls,
+ self.assertTrue(x.__class__ is cls,
"assigning %r as __class__ for %r silently failed" % (cls, x))
self.assertEqual(x.a, 1)
for cls in G, J, K, L, M, N, P, R, list, Int:
@@ -3006,7 +3006,7 @@ order (MRO) for bases """
for cls in C, C1, C2:
s = pickle.dumps(cls, bin)
cls2 = pickle.loads(s)
- self.assert_(cls2 is cls)
+ self.assertTrue(cls2 is cls)
a = C1(1, 2); a.append(42); a.append(24)
b = C2("hello", "world", 42)
@@ -3036,7 +3036,7 @@ order (MRO) for bases """
import copy
for cls in C, C1, C2:
cls2 = copy.deepcopy(cls)
- self.assert_(cls2 is cls)
+ self.assertTrue(cls2 is cls)
a = C1(1, 2); a.append(42); a.append(24)
b = C2("hello", "world", 42)
@@ -3579,8 +3579,8 @@ order (MRO) for bases """
__slots__=()
if support.check_impl_detail():
self.assertEqual(C.__basicsize__, B.__basicsize__)
- self.assert_(hasattr(C, '__dict__'))
- self.assert_(hasattr(C, '__weakref__'))
+ self.assertTrue(hasattr(C, '__dict__'))
+ self.assertTrue(hasattr(C, '__weakref__'))
C().x = 2
def test_rmul(self):
@@ -3914,29 +3914,29 @@ order (MRO) for bases """
pass
a = C()
pa = Proxy(a)
- self.assert_(isinstance(a, C)) # Baseline
- self.assert_(isinstance(pa, C)) # Test
+ self.assertTrue(isinstance(a, C)) # Baseline
+ self.assertTrue(isinstance(pa, C)) # Test
# Test with a classic subclass
class D(C):
pass
a = D()
pa = Proxy(a)
- self.assert_(isinstance(a, C)) # Baseline
- self.assert_(isinstance(pa, C)) # Test
+ self.assertTrue(isinstance(a, C)) # Baseline
+ self.assertTrue(isinstance(pa, C)) # Test
# Test with a new-style class
class C(object):
pass
a = C()
pa = Proxy(a)
- self.assert_(isinstance(a, C)) # Baseline
- self.assert_(isinstance(pa, C)) # Test
+ self.assertTrue(isinstance(a, C)) # Baseline
+ self.assertTrue(isinstance(pa, C)) # Test
# Test with a new-style subclass
class D(C):
pass
a = D()
pa = Proxy(a)
- self.assert_(isinstance(a, C)) # Baseline
- self.assert_(isinstance(pa, C)) # Test
+ self.assertTrue(isinstance(a, C)) # Baseline
+ self.assertTrue(isinstance(pa, C)) # Test
def test_proxy_super(self):
# Testing super() for a proxy object...
@@ -4065,17 +4065,17 @@ order (MRO) for bases """
l = []
self.assertEqual(l.__add__, l.__add__)
self.assertEqual(l.__add__, [].__add__)
- self.assert_(l.__add__ != [5].__add__)
- self.assert_(l.__add__ != l.__mul__)
- self.assert_(l.__add__.__name__ == '__add__')
+ self.assertTrue(l.__add__ != [5].__add__)
+ self.assertTrue(l.__add__ != l.__mul__)
+ self.assertTrue(l.__add__.__name__ == '__add__')
if hasattr(l.__add__, '__self__'):
# CPython
- self.assert_(l.__add__.__self__ is l)
- self.assert_(l.__add__.__objclass__ is list)
+ self.assertTrue(l.__add__.__self__ is l)
+ self.assertTrue(l.__add__.__objclass__ is list)
else:
# Python implementations where [].__add__ is a normal bound method
- self.assert_(l.__add__.im_self is l)
- self.assert_(l.__add__.im_class is list)
+ self.assertTrue(l.__add__.im_self is l)
+ self.assertTrue(l.__add__.im_class is list)
self.assertEqual(l.__add__.__doc__, list.__add__.__doc__)
try:
hash(l.__add__)
diff --git a/Lib/test/test_dict.py b/Lib/test/test_dict.py
index 1c9bca8acf..1519689ed6 100644
--- a/Lib/test/test_dict.py
+++ b/Lib/test/test_dict.py
@@ -10,7 +10,7 @@ class DictTest(unittest.TestCase):
def test_constructor(self):
# calling built-in types without argument must return empty
self.assertEqual(dict(), {})
- self.assert_(dict() is not {})
+ self.assertTrue(dict() is not {})
def test_literal_constructor(self):
# check literal constructor for different sized dicts (to exercise the BUILD_MAP oparg
@@ -24,18 +24,18 @@ class DictTest(unittest.TestCase):
self.assertEqual(eval(dictliteral), dict(items))
def test_bool(self):
- self.assert_(not {})
- self.assert_({1: 2})
- self.assert_(bool({}) is False)
- self.assert_(bool({1: 2}) is True)
+ self.assertTrue(not {})
+ self.assertTrue({1: 2})
+ self.assertTrue(bool({}) is False)
+ self.assertTrue(bool({1: 2}) is True)
def test_keys(self):
d = {}
self.assertEqual(set(d.keys()), set())
d = {'a': 1, 'b': 2}
k = d.keys()
- self.assert_('a' in d)
- self.assert_('b' in d)
+ self.assertTrue('a' in d)
+ self.assertTrue('b' in d)
self.assertRaises(TypeError, d.keys, None)
self.assertEqual(repr(dict(a=1).keys()), "dict_keys(['a'])")
@@ -58,12 +58,12 @@ class DictTest(unittest.TestCase):
def test_contains(self):
d = {}
- self.assert_(not ('a' in d))
- self.assert_('a' not in d)
+ self.assertTrue(not ('a' in d))
+ self.assertTrue('a' not in d)
d = {'a': 1, 'b': 2}
- self.assert_('a' in d)
- self.assert_('b' in d)
- self.assert_('c' not in d)
+ self.assertTrue('a' in d)
+ self.assertTrue('b' in d)
+ self.assertTrue('c' not in d)
self.assertRaises(TypeError, d.__contains__)
@@ -197,7 +197,7 @@ class DictTest(unittest.TestCase):
def test_fromkeys(self):
self.assertEqual(dict.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
d = {}
- self.assert_(not(d.fromkeys('abc') is d))
+ self.assertTrue(not(d.fromkeys('abc') is d))
self.assertEqual(d.fromkeys('abc'), {'a':None, 'b':None, 'c':None})
self.assertEqual(d.fromkeys((4,5),0), {4:0, 5:0})
self.assertEqual(d.fromkeys([]), {})
@@ -208,14 +208,14 @@ class DictTest(unittest.TestCase):
class dictlike(dict): pass
self.assertEqual(dictlike.fromkeys('a'), {'a':None})
self.assertEqual(dictlike().fromkeys('a'), {'a':None})
- self.assert_(type(dictlike.fromkeys('a')) is dictlike)
- self.assert_(type(dictlike().fromkeys('a')) is dictlike)
+ self.assertTrue(type(dictlike.fromkeys('a')) is dictlike)
+ self.assertTrue(type(dictlike().fromkeys('a')) is dictlike)
class mydict(dict):
def __new__(cls):
return collections.UserDict()
ud = mydict.fromkeys('ab')
self.assertEqual(ud, {'a':None, 'b':None})
- self.assert_(isinstance(ud, collections.UserDict))
+ self.assertTrue(isinstance(ud, collections.UserDict))
self.assertRaises(TypeError, dict.fromkeys)
class Exc(Exception): pass
@@ -252,10 +252,10 @@ class DictTest(unittest.TestCase):
def test_get(self):
d = {}
- self.assert_(d.get('c') is None)
+ self.assertTrue(d.get('c') is None)
self.assertEqual(d.get('c', 3), 3)
d = {'a' : 1, 'b' : 2}
- self.assert_(d.get('c') is None)
+ self.assertTrue(d.get('c') is None)
self.assertEqual(d.get('c', 3), 3)
self.assertEqual(d.get('a'), 1)
self.assertEqual(d.get('a', 3), 1)
@@ -265,9 +265,9 @@ class DictTest(unittest.TestCase):
def test_setdefault(self):
# dict.setdefault()
d = {}
- self.assert_(d.setdefault('key0') is None)
+ self.assertTrue(d.setdefault('key0') is None)
d.setdefault('key0', [])
- self.assert_(d.setdefault('key0') is None)
+ self.assertTrue(d.setdefault('key0') is None)
d.setdefault('key', []).append(3)
self.assertEqual(d['key'][0], 3)
d.setdefault('key', []).append(4)
@@ -309,9 +309,9 @@ class DictTest(unittest.TestCase):
self.assertEqual(va, int(ka))
kb, vb = tb = b.popitem()
self.assertEqual(vb, int(kb))
- self.assert_(not(copymode < 0 and ta != tb))
- self.assert_(not a)
- self.assert_(not b)
+ self.assertTrue(not(copymode < 0 and ta != tb))
+ self.assertTrue(not a)
+ self.assertTrue(not b)
d = {}
self.assertRaises(KeyError, d.popitem)
@@ -525,8 +525,8 @@ class DictTest(unittest.TestCase):
d = D({1: 2, 3: 4})
self.assertEqual(d[1], 2)
self.assertEqual(d[3], 4)
- self.assert_(2 not in d)
- self.assert_(2 not in d.keys())
+ self.assertTrue(2 not in d)
+ self.assertTrue(2 not in d.keys())
self.assertEqual(d[2], 42)
class E(dict):
def __missing__(self, key):
@@ -663,7 +663,7 @@ class DictTest(unittest.TestCase):
obj.x = iter(obj.v)
del obj, container
gc.collect()
- self.assert_(ref() is None, "Cycle was not collected")
+ self.assertTrue(ref() is None, "Cycle was not collected")
def _not_tracked(self, t):
# Nested containers can take several collections to untrack
diff --git a/Lib/test/test_dictviews.py b/Lib/test/test_dictviews.py
index 34883d21c0..4fee755da4 100644
--- a/Lib/test/test_dictviews.py
+++ b/Lib/test/test_dictviews.py
@@ -24,10 +24,10 @@ class DictSetTest(unittest.TestCase):
self.assertNotEqual(keys, {1, "b"})
self.assertNotEqual(keys, {1})
self.assertNotEqual(keys, 42)
- self.assert_(1 in keys)
- self.assert_("a" in keys)
- self.assert_(10 not in keys)
- self.assert_("Z" not in keys)
+ self.assertTrue(1 in keys)
+ self.assertTrue("a" in keys)
+ self.assertTrue(10 not in keys)
+ self.assertTrue("Z" not in keys)
self.assertEqual(d.keys(), d.keys())
e = {1: 11, "a": "def"}
self.assertEqual(d.keys(), e.keys())
@@ -44,13 +44,13 @@ class DictSetTest(unittest.TestCase):
self.assertNotEqual(items, {(1, 10), ("a", "def")})
self.assertNotEqual(items, {(1, 10)})
self.assertNotEqual(items, 42)
- self.assert_((1, 10) in items)
- self.assert_(("a", "ABC") in items)
- self.assert_((1, 11) not in items)
- self.assert_(1 not in items)
- self.assert_(() not in items)
- self.assert_((1,) not in items)
- self.assert_((1, 2, 3) not in items)
+ self.assertTrue((1, 10) in items)
+ self.assertTrue(("a", "ABC") in items)
+ self.assertTrue((1, 11) not in items)
+ self.assertTrue(1 not in items)
+ self.assertTrue(() not in items)
+ self.assertTrue((1,) not in items)
+ self.assertTrue((1, 2, 3) not in items)
self.assertEqual(d.items(), d.items())
e = d.copy()
self.assertEqual(d.items(), e.items())
diff --git a/Lib/test/test_docxmlrpc.py b/Lib/test/test_docxmlrpc.py
index bd96e2378c..7bffa48388 100644
--- a/Lib/test/test_docxmlrpc.py
+++ b/Lib/test/test_docxmlrpc.py
@@ -104,7 +104,7 @@ class DocXMLRPCHTTPGETServer(unittest.TestCase):
self.client.request("GET", "/")
response = self.client.getresponse()
- self.assert_(
+ self.assertTrue(
b"""<dl><dt><a name="-&lt;lambda&gt;"><strong>&lt;lambda&gt;</strong></a>(x, y)</dt></dl>"""
in response.read())
@@ -118,7 +118,7 @@ b"""<dl><dt><a name="-&lt;lambda&gt;"><strong>&lt;lambda&gt;</strong></a>(x, y)<
self.client.request("GET", "/")
response = self.client.getresponse().read()
- self.assert_( # This is ugly ... how can it be made better?
+ self.assertTrue( # This is ugly ... how can it be made better?
b"""<dl><dt><a name="-add"><strong>add</strong></a>(x, y)</dt><dd><tt>Add&nbsp;two&nbsp;instances&nbsp;together.&nbsp;This&nbsp;follows&nbsp;<a href="http://www.python.org/dev/peps/pep-0008/">PEP008</a>,&nbsp;but&nbsp;has&nbsp;nothing<br>\nto&nbsp;do&nbsp;with&nbsp;<a href="http://www.rfc-editor.org/rfc/rfc1952.txt">RFC1952</a>.&nbsp;Case&nbsp;should&nbsp;matter:&nbsp;pEp008&nbsp;and&nbsp;rFC1952.&nbsp;&nbsp;Things<br>\nthat&nbsp;start&nbsp;with&nbsp;http&nbsp;and&nbsp;ftp&nbsp;should&nbsp;be&nbsp;auto-linked,&nbsp;too:<br>\n<a href="http://google.com">http://google.com</a>.</tt></dd></dl>"""
in response, response)
@@ -131,7 +131,7 @@ b"""<dl><dt><a name="-add"><strong>add</strong></a>(x, y)</dt><dd><tt>Add&nbsp;t
self.client.request("GET", "/")
response = self.client.getresponse().read()
- self.assert_(
+ self.assertTrue(
b"""<dl><dt><a name="-system.methodHelp"><strong>system.methodHelp</strong></a>(method_name)</dt><dd><tt><a href="#-system.methodHelp">system.methodHelp</a>(\'add\')&nbsp;=&gt;&nbsp;"Adds&nbsp;two&nbsp;integers&nbsp;together"<br>\n&nbsp;<br>\nReturns&nbsp;a&nbsp;string&nbsp;containing&nbsp;documentation&nbsp;for&nbsp;the&nbsp;specified&nbsp;method.</tt></dd></dl>\n<dl><dt><a name="-system.methodSignature"><strong>system.methodSignature</strong></a>(method_name)</dt><dd><tt><a href="#-system.methodSignature">system.methodSignature</a>(\'add\')&nbsp;=&gt;&nbsp;[double,&nbsp;int,&nbsp;int]<br>\n&nbsp;<br>\nReturns&nbsp;a&nbsp;list&nbsp;describing&nbsp;the&nbsp;signature&nbsp;of&nbsp;the&nbsp;method.&nbsp;In&nbsp;the<br>\nabove&nbsp;example,&nbsp;the&nbsp;add&nbsp;method&nbsp;takes&nbsp;two&nbsp;integers&nbsp;as&nbsp;arguments<br>\nand&nbsp;returns&nbsp;a&nbsp;double&nbsp;result.<br>\n&nbsp;<br>\nThis&nbsp;server&nbsp;does&nbsp;NOT&nbsp;support&nbsp;system.methodSignature.</tt></dd></dl>\n<dl><dt><a name="-test_method"><strong>test_method</strong></a>(arg)</dt><dd><tt>Test&nbsp;method\'s&nbsp;docs.&nbsp;This&nbsp;method&nbsp;truly&nbsp;does&nbsp;very&nbsp;little.</tt></dd></dl>""" in response)
def test_autolink_dotted_methods(self):
@@ -140,7 +140,7 @@ b"""<dl><dt><a name="-system.methodHelp"><strong>system.methodHelp</strong></a>(
self.client.request("GET", "/")
response = self.client.getresponse()
- self.assert_(b"""Try&nbsp;self.<strong>add</strong>,&nbsp;too.""" in
+ self.assertTrue(b"""Try&nbsp;self.<strong>add</strong>,&nbsp;too.""" in
response.read())
def test_main():
diff --git a/Lib/test/test_dummy_thread.py b/Lib/test/test_dummy_thread.py
index ecac3eed15..240b61ad83 100644
--- a/Lib/test/test_dummy_thread.py
+++ b/Lib/test/test_dummy_thread.py
@@ -24,43 +24,43 @@ class LockTests(unittest.TestCase):
def test_initlock(self):
#Make sure locks start locked
- self.failUnless(not self.lock.locked(),
+ self.assertTrue(not self.lock.locked(),
"Lock object is not initialized unlocked.")
def test_release(self):
# Test self.lock.release()
self.lock.acquire()
self.lock.release()
- self.failUnless(not self.lock.locked(),
+ self.assertTrue(not self.lock.locked(),
"Lock object did not release properly.")
def test_improper_release(self):
#Make sure release of an unlocked thread raises _thread.error
- self.failUnlessRaises(_thread.error, self.lock.release)
+ self.assertRaises(_thread.error, self.lock.release)
def test_cond_acquire_success(self):
#Make sure the conditional acquiring of the lock works.
- self.failUnless(self.lock.acquire(0),
+ self.assertTrue(self.lock.acquire(0),
"Conditional acquiring of the lock failed.")
def test_cond_acquire_fail(self):
#Test acquiring locked lock returns False
self.lock.acquire(0)
- self.failUnless(not self.lock.acquire(0),
+ self.assertTrue(not self.lock.acquire(0),
"Conditional acquiring of a locked lock incorrectly "
"succeeded.")
def test_uncond_acquire_success(self):
#Make sure unconditional acquiring of a lock works.
self.lock.acquire()
- self.failUnless(self.lock.locked(),
+ self.assertTrue(self.lock.locked(),
"Uncondional locking failed.")
def test_uncond_acquire_return_val(self):
#Make sure that an unconditional locking returns True.
- self.failUnless(self.lock.acquire(1) is True,
+ self.assertTrue(self.lock.acquire(1) is True,
"Unconditional locking did not return True.")
- self.failUnless(self.lock.acquire() is True)
+ self.assertTrue(self.lock.acquire() is True)
def test_uncond_acquire_blocking(self):
#Make sure that unconditional acquiring of a locked lock blocks.
@@ -80,7 +80,7 @@ class LockTests(unittest.TestCase):
end_time = int(time.time())
if support.verbose:
print("done")
- self.failUnless((end_time - start_time) >= DELAY,
+ self.assertTrue((end_time - start_time) >= DELAY,
"Blocking by unconditional acquiring failed.")
class MiscTests(unittest.TestCase):
@@ -88,18 +88,18 @@ class MiscTests(unittest.TestCase):
def test_exit(self):
#Make sure _thread.exit() raises SystemExit
- self.failUnlessRaises(SystemExit, _thread.exit)
+ self.assertRaises(SystemExit, _thread.exit)
def test_ident(self):
#Test sanity of _thread.get_ident()
- self.failUnless(isinstance(_thread.get_ident(), int),
+ self.assertTrue(isinstance(_thread.get_ident(), int),
"_thread.get_ident() returned a non-integer")
- self.failUnless(_thread.get_ident() != 0,
+ self.assertTrue(_thread.get_ident() != 0,
"_thread.get_ident() returned 0")
def test_LockType(self):
#Make sure _thread.LockType is the same type as _thread.allocate_locke()
- self.failUnless(isinstance(_thread.allocate_lock(), _thread.LockType),
+ self.assertTrue(isinstance(_thread.allocate_lock(), _thread.LockType),
"_thread.LockType is not an instance of what is "
"returned by _thread.allocate_lock()")
@@ -108,13 +108,13 @@ class MiscTests(unittest.TestCase):
# should raise KeyboardInterrupt upon completion.
def call_interrupt():
_thread.interrupt_main()
- self.failUnlessRaises(KeyboardInterrupt, _thread.start_new_thread,
+ self.assertRaises(KeyboardInterrupt, _thread.start_new_thread,
call_interrupt, tuple())
def test_interrupt_in_main(self):
# Make sure that if interrupt_main is called in main threat that
# KeyboardInterrupt is raised instantly.
- self.failUnlessRaises(KeyboardInterrupt, _thread.interrupt_main)
+ self.assertRaises(KeyboardInterrupt, _thread.interrupt_main)
class ThreadTests(unittest.TestCase):
"""Test thread creation."""
@@ -128,16 +128,16 @@ class ThreadTests(unittest.TestCase):
testing_queue = queue.Queue(1)
_thread.start_new_thread(arg_tester, (testing_queue, True, True))
result = testing_queue.get()
- self.failUnless(result[0] and result[1],
+ self.assertTrue(result[0] and result[1],
"Argument passing for thread creation using tuple failed")
_thread.start_new_thread(arg_tester, tuple(), {'queue':testing_queue,
'arg1':True, 'arg2':True})
result = testing_queue.get()
- self.failUnless(result[0] and result[1],
+ self.assertTrue(result[0] and result[1],
"Argument passing for thread creation using kwargs failed")
_thread.start_new_thread(arg_tester, (testing_queue, True), {'arg2':True})
result = testing_queue.get()
- self.failUnless(result[0] and result[1],
+ self.assertTrue(result[0] and result[1],
"Argument passing for thread creation using both tuple"
" and kwargs failed")
@@ -164,7 +164,7 @@ class ThreadTests(unittest.TestCase):
time.sleep(DELAY)
if support.verbose:
print('done')
- self.failUnless(testing_queue.qsize() == thread_count,
+ self.assertTrue(testing_queue.qsize() == thread_count,
"Not all %s threads executed properly after %s sec." %
(thread_count, DELAY))
diff --git a/Lib/test/test_epoll.py b/Lib/test/test_epoll.py
index ab6bf0bf92..847b991403 100644
--- a/Lib/test/test_epoll.py
+++ b/Lib/test/test_epoll.py
@@ -71,10 +71,10 @@ class TestEPoll(unittest.TestCase):
ep = select.epoll(16)
except OSError as e:
raise AssertionError(str(e))
- self.assert_(ep.fileno() > 0, ep.fileno())
- self.assert_(not ep.closed)
+ self.assertTrue(ep.fileno() > 0, ep.fileno())
+ self.assertTrue(not ep.closed)
ep.close()
- self.assert_(ep.closed)
+ self.assertTrue(ep.closed)
self.assertRaises(ValueError, ep.fileno)
def test_badcreate(self):
@@ -141,7 +141,7 @@ class TestEPoll(unittest.TestCase):
try:
ep2.poll(1, 4)
except IOError as e:
- self.failUnlessEqual(e.args[0], errno.EBADF, e)
+ self.assertEqual(e.args[0], errno.EBADF, e)
else:
self.fail("epoll on closed fd didn't raise EBADF")
@@ -157,7 +157,7 @@ class TestEPoll(unittest.TestCase):
now = time.time()
events = ep.poll(1, 4)
then = time.time()
- self.failIf(then - now > 0.1, then - now)
+ self.assertFalse(then - now > 0.1, then - now)
events.sort()
expected = [(client.fileno(), select.EPOLLOUT),
@@ -165,12 +165,12 @@ class TestEPoll(unittest.TestCase):
expected.sort()
self.assertEquals(events, expected)
- self.failIf(then - now > 0.01, then - now)
+ self.assertFalse(then - now > 0.01, then - now)
now = time.time()
events = ep.poll(timeout=2.1, maxevents=4)
then = time.time()
- self.failIf(events)
+ self.assertFalse(events)
client.send(b"Hello!")
server.send(b"world!!!")
@@ -178,7 +178,7 @@ class TestEPoll(unittest.TestCase):
now = time.time()
events = ep.poll(1, 4)
then = time.time()
- self.failIf(then - now > 0.01)
+ self.assertFalse(then - now > 0.01)
events.sort()
expected = [(client.fileno(), select.EPOLLIN | select.EPOLLOUT),
@@ -192,7 +192,7 @@ class TestEPoll(unittest.TestCase):
now = time.time()
events = ep.poll(1, 4)
then = time.time()
- self.failIf(then - now > 0.01)
+ self.assertFalse(then - now > 0.01)
expected = [(server.fileno(), select.EPOLLOUT)]
self.assertEquals(events, expected)
@@ -211,7 +211,7 @@ class TestEPoll(unittest.TestCase):
now = time.time()
events = ep.poll(1, 4)
then = time.time()
- self.failIf(then - now > 0.01)
+ self.assertFalse(then - now > 0.01)
server.close()
ep.unregister(fd)
diff --git a/Lib/test/test_errno.py b/Lib/test/test_errno.py
index 28425e2057..80edcc680a 100755
--- a/Lib/test/test_errno.py
+++ b/Lib/test/test_errno.py
@@ -14,13 +14,13 @@ class ErrnoAttributeTests(unittest.TestCase):
def test_for_improper_attributes(self):
# No unexpected attributes should be on the module.
for error_code in std_c_errors:
- self.assert_(hasattr(errno, error_code),
+ self.assertTrue(hasattr(errno, error_code),
"errno is missing %s" % error_code)
def test_using_errorcode(self):
# Every key value in errno.errorcode should be on the module.
for value in errno.errorcode.values():
- self.assert_(hasattr(errno, value), 'no %s attr in errno' % value)
+ self.assertTrue(hasattr(errno, value), 'no %s attr in errno' % value)
class ErrorcodeTests(unittest.TestCase):
@@ -28,7 +28,7 @@ class ErrorcodeTests(unittest.TestCase):
def test_attributes_in_errorcode(self):
for attribute in errno.__dict__.keys():
if attribute.isupper():
- self.assert_(getattr(errno, attribute) in errno.errorcode,
+ self.assertTrue(getattr(errno, attribute) in errno.errorcode,
'no %s attr in errno.errorcode' % attribute)
diff --git a/Lib/test/test_exceptions.py b/Lib/test/test_exceptions.py
index 8bb20791d7..89e6ebb27b 100644
--- a/Lib/test/test_exceptions.py
+++ b/Lib/test/test_exceptions.py
@@ -155,7 +155,7 @@ class ExceptionTests(unittest.TestCase):
exc, err, tb = sys.exc_info()
co = tb.tb_frame.f_code
self.assertEquals(co.co_name, "test_capi1")
- self.assert_(co.co_filename.endswith('test_exceptions.py'))
+ self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
else:
self.fail("Expected exception")
@@ -167,7 +167,7 @@ class ExceptionTests(unittest.TestCase):
exc, err, tb = sys.exc_info()
co = tb.tb_frame.f_code
self.assertEquals(co.co_name, "__init__")
- self.assert_(co.co_filename.endswith('test_exceptions.py'))
+ self.assertTrue(co.co_filename.endswith('test_exceptions.py'))
co2 = tb.tb_frame.f_back.f_code
self.assertEquals(co2.co_name, "test_capi2")
else:
@@ -189,12 +189,12 @@ class ExceptionTests(unittest.TestCase):
except NameError:
pass
else:
- self.failUnlessEqual(str(WindowsError(1001)),
+ self.assertEqual(str(WindowsError(1001)),
"1001")
- self.failUnlessEqual(str(WindowsError(1001, "message")),
+ self.assertEqual(str(WindowsError(1001, "message")),
"[Error 1001] message")
- self.failUnlessEqual(WindowsError(1001, "message").errno, 22)
- self.failUnlessEqual(WindowsError(1001, "message").winerror, 1001)
+ self.assertEqual(WindowsError(1001, "message").errno, 22)
+ self.assertEqual(WindowsError(1001, "message").winerror, 1001)
def testAttributes(self):
# test that exception attributes are happy
@@ -319,25 +319,25 @@ class ExceptionTests(unittest.TestCase):
tb = sys.exc_info()[2]
e = BaseException().with_traceback(tb)
- self.failUnless(isinstance(e, BaseException))
+ self.assertTrue(isinstance(e, BaseException))
self.assertEqual(e.__traceback__, tb)
e = IndexError(5).with_traceback(tb)
- self.failUnless(isinstance(e, IndexError))
+ self.assertTrue(isinstance(e, IndexError))
self.assertEqual(e.__traceback__, tb)
class MyException(Exception):
pass
e = MyException().with_traceback(tb)
- self.failUnless(isinstance(e, MyException))
+ self.assertTrue(isinstance(e, MyException))
self.assertEqual(e.__traceback__, tb)
def testInvalidTraceback(self):
try:
Exception().__traceback__ = 5
except TypeError as e:
- self.failUnless("__traceback__ must be a traceback" in str(e))
+ self.assertTrue("__traceback__ must be a traceback" in str(e))
else:
self.fail("No exception raised")
@@ -402,10 +402,10 @@ class ExceptionTests(unittest.TestCase):
def testUnicodeStrUsage(self):
# Make sure both instances and classes have a str and unicode
# representation.
- self.failUnless(str(Exception))
- self.failUnless(str(Exception))
- self.failUnless(str(Exception('a')))
- self.failUnless(str(Exception('a')))
+ self.assertTrue(str(Exception))
+ self.assertTrue(str(Exception))
+ self.assertTrue(str(Exception('a')))
+ self.assertTrue(str(Exception('a')))
def testExceptionCleanupNames(self):
# Make sure the local variable bound to the exception instance by
@@ -413,9 +413,9 @@ class ExceptionTests(unittest.TestCase):
try:
raise Exception()
except Exception as e:
- self.failUnless(e)
+ self.assertTrue(e)
del e
- self.failIf('e' in locals())
+ self.assertFalse('e' in locals())
def testExceptionCleanupState(self):
# Make sure exception state is cleaned up as soon as the except
@@ -441,7 +441,7 @@ class ExceptionTests(unittest.TestCase):
pass
obj = None
obj = wr()
- self.failUnless(obj is None, "%s" % obj)
+ self.assertTrue(obj is None, "%s" % obj)
# Qualified "except" without "as"
obj = MyObj()
@@ -452,7 +452,7 @@ class ExceptionTests(unittest.TestCase):
pass
obj = None
obj = wr()
- self.failUnless(obj is None, "%s" % obj)
+ self.assertTrue(obj is None, "%s" % obj)
# Bare "except"
obj = MyObj()
@@ -463,7 +463,7 @@ class ExceptionTests(unittest.TestCase):
pass
obj = None
obj = wr()
- self.failUnless(obj is None, "%s" % obj)
+ self.assertTrue(obj is None, "%s" % obj)
# "except" with premature block leave
obj = MyObj()
@@ -475,7 +475,7 @@ class ExceptionTests(unittest.TestCase):
break
obj = None
obj = wr()
- self.failUnless(obj is None, "%s" % obj)
+ self.assertTrue(obj is None, "%s" % obj)
# "except" block raising another exception
obj = MyObj()
@@ -493,7 +493,7 @@ class ExceptionTests(unittest.TestCase):
e.__context__ = None
obj = None
obj = wr()
- self.failUnless(obj is None, "%s" % obj)
+ self.assertTrue(obj is None, "%s" % obj)
# Some complicated construct
obj = MyObj()
@@ -510,7 +510,7 @@ class ExceptionTests(unittest.TestCase):
pass
obj = None
obj = wr()
- self.failUnless(obj is None, "%s" % obj)
+ self.assertTrue(obj is None, "%s" % obj)
# Inside an exception-silencing "with" block
class Context:
@@ -524,7 +524,7 @@ class ExceptionTests(unittest.TestCase):
inner_raising_func()
obj = None
obj = wr()
- self.failUnless(obj is None, "%s" % obj)
+ self.assertTrue(obj is None, "%s" % obj)
def test_generator_leaking(self):
# Test that generator exception state doesn't leak into the calling
@@ -598,8 +598,8 @@ class ExceptionTests(unittest.TestCase):
except RuntimeError:
return sys.exc_info()
e, v, tb = g()
- self.assert_(isinstance(v, RuntimeError), type(v))
- self.assert_("maximum recursion depth exceeded" in str(v), str(v))
+ self.assertTrue(isinstance(v, RuntimeError), type(v))
+ self.assertTrue("maximum recursion depth exceeded" in str(v), str(v))
def test_MemoryError(self):
diff --git a/Lib/test/test_file.py b/Lib/test/test_file.py
index 3360121f35..bd2d7c0493 100644
--- a/Lib/test/test_file.py
+++ b/Lib/test/test_file.py
@@ -83,13 +83,13 @@ class AutoFileTests(unittest.TestCase):
def testErrors(self):
f = self.f
self.assertEquals(f.name, TESTFN)
- self.assert_(not f.isatty())
- self.assert_(not f.closed)
+ self.assertTrue(not f.isatty())
+ self.assertTrue(not f.closed)
if hasattr(f, "readinto"):
self.assertRaises((IOError, TypeError), f.readinto, "")
f.close()
- self.assert_(f.closed)
+ self.assertTrue(f.closed)
def testMethods(self):
methods = [('fileno', ()),
@@ -111,7 +111,7 @@ class AutoFileTests(unittest.TestCase):
# __exit__ should close the file
self.f.__exit__(None, None, None)
- self.assert_(self.f.closed)
+ self.assertTrue(self.f.closed)
for methodname, args in methods:
method = getattr(self.f, methodname)
diff --git a/Lib/test/test_filecmp.py b/Lib/test/test_filecmp.py
index 22f0be7844..c71a27a5b9 100644
--- a/Lib/test/test_filecmp.py
+++ b/Lib/test/test_filecmp.py
@@ -25,19 +25,19 @@ class FileCompareTestCase(unittest.TestCase):
os.unlink(self.name_diff)
def test_matching(self):
- self.failUnless(filecmp.cmp(self.name, self.name_same),
+ self.assertTrue(filecmp.cmp(self.name, self.name_same),
"Comparing file to itself fails")
- self.failUnless(filecmp.cmp(self.name, self.name_same, shallow=False),
+ self.assertTrue(filecmp.cmp(self.name, self.name_same, shallow=False),
"Comparing file to itself fails")
- self.failUnless(filecmp.cmp(self.name, self.name, shallow=False),
+ self.assertTrue(filecmp.cmp(self.name, self.name, shallow=False),
"Comparing file to identical file fails")
- self.failUnless(filecmp.cmp(self.name, self.name),
+ self.assertTrue(filecmp.cmp(self.name, self.name),
"Comparing file to identical file fails")
def test_different(self):
- self.failIf(filecmp.cmp(self.name, self.name_diff),
+ self.assertFalse(filecmp.cmp(self.name, self.name_diff),
"Mismatched files compare as equal")
- self.failIf(filecmp.cmp(self.name, self.dir),
+ self.assertFalse(filecmp.cmp(self.name, self.dir),
"File and directory compare as equal")
class DirCompareTestCase(unittest.TestCase):
@@ -69,19 +69,19 @@ class DirCompareTestCase(unittest.TestCase):
shutil.rmtree(self.dir_diff)
def test_cmpfiles(self):
- self.failUnless(filecmp.cmpfiles(self.dir, self.dir, ['file']) ==
+ self.assertTrue(filecmp.cmpfiles(self.dir, self.dir, ['file']) ==
(['file'], [], []),
"Comparing directory to itself fails")
- self.failUnless(filecmp.cmpfiles(self.dir, self.dir_same, ['file']) ==
+ self.assertTrue(filecmp.cmpfiles(self.dir, self.dir_same, ['file']) ==
(['file'], [], []),
"Comparing directory to same fails")
# Try it with shallow=False
- self.failUnless(filecmp.cmpfiles(self.dir, self.dir, ['file'],
+ self.assertTrue(filecmp.cmpfiles(self.dir, self.dir, ['file'],
shallow=False) ==
(['file'], [], []),
"Comparing directory to itself fails")
- self.failUnless(filecmp.cmpfiles(self.dir, self.dir_same, ['file'],
+ self.assertTrue(filecmp.cmpfiles(self.dir, self.dir_same, ['file'],
shallow=False),
"Comparing directory to same fails")
@@ -90,7 +90,7 @@ class DirCompareTestCase(unittest.TestCase):
output.write('Different contents.\n')
output.close()
- self.failIf(filecmp.cmpfiles(self.dir, self.dir_same,
+ self.assertFalse(filecmp.cmpfiles(self.dir, self.dir_same,
['file', 'file2']) ==
(['file'], ['file2'], []),
"Comparing mismatched directories fails")
@@ -104,14 +104,14 @@ class DirCompareTestCase(unittest.TestCase):
else:
self.assertEqual([d.left_list, d.right_list],[['file'], ['file']])
self.assertEqual(d.common, ['file'])
- self.failUnless(d.left_only == d.right_only == [])
+ self.assertTrue(d.left_only == d.right_only == [])
self.assertEqual(d.same_files, ['file'])
self.assertEqual(d.diff_files, [])
# Check attributes for comparison of two different directories
d = filecmp.dircmp(self.dir, self.dir_diff)
self.assertEqual(d.left_list, ['file'])
- self.failUnless(d.right_list == ['file', 'file2'])
+ self.assertTrue(d.right_list == ['file', 'file2'])
self.assertEqual(d.common, ['file'])
self.assertEqual(d.left_only, [])
self.assertEqual(d.right_only, ['file2'])
diff --git a/Lib/test/test_fileinput.py b/Lib/test/test_fileinput.py
index a4d59e1240..aae16eadfe 100644
--- a/Lib/test/test_fileinput.py
+++ b/Lib/test/test_fileinput.py
@@ -68,8 +68,8 @@ class BufferSizesTests(unittest.TestCase):
self.assertEqual(fi.filename(), t2)
self.assertEqual(fi.lineno(), 21)
self.assertEqual(fi.filelineno(), 6)
- self.failIf(fi.isfirstline())
- self.failIf(fi.isstdin())
+ self.assertFalse(fi.isfirstline())
+ self.assertFalse(fi.isstdin())
if verbose:
print('%s. Nextfile (bs=%s)' % (start+2, bs))
@@ -138,7 +138,7 @@ class FileInputTests(unittest.TestCase):
self.assertEqual(fi.filename(), t3)
line = fi.readline()
- self.failIf(line)
+ self.assertFalse(line)
self.assertEqual(fi.lineno(), 1)
self.assertEqual(fi.filelineno(), 0)
self.assertEqual(fi.filename(), t4)
diff --git a/Lib/test/test_fileio.py b/Lib/test/test_fileio.py
index 657401e8ed..679ed088b3 100644
--- a/Lib/test/test_fileio.py
+++ b/Lib/test/test_fileio.py
@@ -80,17 +80,17 @@ class AutoFileTests(unittest.TestCase):
def testErrors(self):
f = self.f
- self.assert_(not f.isatty())
- self.assert_(not f.closed)
+ self.assertTrue(not f.isatty())
+ self.assertTrue(not f.closed)
#self.assertEquals(f.name, TESTFN)
self.assertRaises(ValueError, f.read, 10) # Open for reading
f.close()
- self.assert_(f.closed)
+ self.assertTrue(f.closed)
f = _FileIO(TESTFN, 'r')
self.assertRaises(TypeError, f.readinto, "")
- self.assert_(not f.closed)
+ self.assertTrue(not f.closed)
f.close()
- self.assert_(f.closed)
+ self.assertTrue(f.closed)
def testMethods(self):
methods = ['fileno', 'isatty', 'read', 'readinto',
@@ -100,7 +100,7 @@ class AutoFileTests(unittest.TestCase):
methods.remove('truncate')
self.f.close()
- self.assert_(self.f.closed)
+ self.assertTrue(self.f.closed)
for methodname in methods:
method = getattr(self.f, methodname)
diff --git a/Lib/test/test_float.py b/Lib/test/test_float.py
index e74e892203..af5e13c7ad 100644
--- a/Lib/test/test_float.py
+++ b/Lib/test/test_float.py
@@ -136,27 +136,27 @@ class GeneralFloatCases(unittest.TestCase):
def test_float_containment(self):
floats = (INF, -INF, 0.0, 1.0, NAN)
for f in floats:
- self.assert_(f in [f], "'%r' not in []" % f)
- self.assert_(f in (f,), "'%r' not in ()" % f)
- self.assert_(f in {f}, "'%r' not in set()" % f)
- self.assert_(f in {f: None}, "'%r' not in {}" % f)
+ self.assertTrue(f in [f], "'%r' not in []" % f)
+ self.assertTrue(f in (f,), "'%r' not in ()" % f)
+ self.assertTrue(f in {f}, "'%r' not in set()" % f)
+ self.assertTrue(f in {f: None}, "'%r' not in {}" % f)
self.assertEqual([f].count(f), 1, "[].count('%r') != 1" % f)
- self.assert_(f in floats, "'%r' not in container" % f)
+ self.assertTrue(f in floats, "'%r' not in container" % f)
for f in floats:
# nonidentical containers, same type, same contents
- self.assert_([f] == [f], "[%r] != [%r]" % (f, f))
- self.assert_((f,) == (f,), "(%r,) != (%r,)" % (f, f))
- self.assert_({f} == {f}, "{%r} != {%r}" % (f, f))
- self.assert_({f : None} == {f: None}, "{%r : None} != "
+ self.assertTrue([f] == [f], "[%r] != [%r]" % (f, f))
+ self.assertTrue((f,) == (f,), "(%r,) != (%r,)" % (f, f))
+ self.assertTrue({f} == {f}, "{%r} != {%r}" % (f, f))
+ self.assertTrue({f : None} == {f: None}, "{%r : None} != "
"{%r : None}" % (f, f))
# identical containers
l, t, s, d = [f], (f,), {f}, {f: None}
- self.assert_(l == l, "[%r] not equal to itself" % f)
- self.assert_(t == t, "(%r,) not equal to itself" % f)
- self.assert_(s == s, "{%r} not equal to itself" % f)
- self.assert_(d == d, "{%r : None} not equal to itself" % f)
+ self.assertTrue(l == l, "[%r] not equal to itself" % f)
+ self.assertTrue(t == t, "(%r,) not equal to itself" % f)
+ self.assertTrue(s == s, "{%r} not equal to itself" % f)
+ self.assertTrue(d == d, "{%r : None} not equal to itself" % f)
@@ -171,9 +171,9 @@ class FormatFunctionsTestCase(unittest.TestCase):
float.__setformat__('float', self.save_formats['float'])
def test_getformat(self):
- self.assert_(float.__getformat__('double') in
+ self.assertTrue(float.__getformat__('double') in
['unknown', 'IEEE, big-endian', 'IEEE, little-endian'])
- self.assert_(float.__getformat__('float') in
+ self.assertTrue(float.__getformat__('float') in
['unknown', 'IEEE, big-endian', 'IEEE, little-endian'])
self.assertRaises(ValueError, float.__getformat__, 'chicken')
self.assertRaises(TypeError, float.__getformat__, 1)
@@ -493,12 +493,12 @@ class RoundTestCase(unittest.TestCase):
# ways to create and represent inf and nan
class InfNanTest(unittest.TestCase):
def test_inf_from_str(self):
- self.assert_(isinf(float("inf")))
- self.assert_(isinf(float("+inf")))
- self.assert_(isinf(float("-inf")))
- self.assert_(isinf(float("infinity")))
- self.assert_(isinf(float("+infinity")))
- self.assert_(isinf(float("-infinity")))
+ self.assertTrue(isinf(float("inf")))
+ self.assertTrue(isinf(float("+inf")))
+ self.assertTrue(isinf(float("-inf")))
+ self.assertTrue(isinf(float("infinity")))
+ self.assertTrue(isinf(float("+infinity")))
+ self.assertTrue(isinf(float("-infinity")))
self.assertEqual(repr(float("inf")), "inf")
self.assertEqual(repr(float("+inf")), "inf")
@@ -545,9 +545,9 @@ class InfNanTest(unittest.TestCase):
self.assertEqual(str(-1e300 * 1e300), "-inf")
def test_nan_from_str(self):
- self.assert_(isnan(float("nan")))
- self.assert_(isnan(float("+nan")))
- self.assert_(isnan(float("-nan")))
+ self.assertTrue(isnan(float("nan")))
+ self.assertTrue(isnan(float("+nan")))
+ self.assertTrue(isnan(float("-nan")))
self.assertEqual(repr(float("nan")), "nan")
self.assertEqual(repr(float("+nan")), "nan")
@@ -581,14 +581,14 @@ class InfNanTest(unittest.TestCase):
self.assertEqual(str(-1e300 * 1e300 * 0), "nan")
def notest_float_nan(self):
- self.assert_(NAN.is_nan())
- self.failIf(INF.is_nan())
- self.failIf((0.).is_nan())
+ self.assertTrue(NAN.is_nan())
+ self.assertFalse(INF.is_nan())
+ self.assertFalse((0.).is_nan())
def notest_float_inf(self):
- self.assert_(INF.is_inf())
- self.failIf(NAN.is_inf())
- self.failIf((0.).is_inf())
+ self.assertTrue(INF.is_inf())
+ self.assertFalse(NAN.is_inf())
+ self.assertFalse((0.).is_inf())
fromHex = float.fromhex
toHex = float.hex
diff --git a/Lib/test/test_fnmatch.py b/Lib/test/test_fnmatch.py
index 30ccf6920a..2f701cacca 100644
--- a/Lib/test/test_fnmatch.py
+++ b/Lib/test/test_fnmatch.py
@@ -9,11 +9,11 @@ from fnmatch import fnmatch, fnmatchcase
class FnmatchTestCase(unittest.TestCase):
def check_match(self, filename, pattern, should_match=1):
if should_match:
- self.assert_(fnmatch(filename, pattern),
+ self.assertTrue(fnmatch(filename, pattern),
"expected %r to match pattern %r"
% (filename, pattern))
else:
- self.assert_(not fnmatch(filename, pattern),
+ self.assertTrue(not fnmatch(filename, pattern),
"expected %r not to match pattern %r"
% (filename, pattern))
diff --git a/Lib/test/test_ftplib.py b/Lib/test/test_ftplib.py
index afc8fda0b9..b83cba0d20 100644
--- a/Lib/test/test_ftplib.py
+++ b/Lib/test/test_ftplib.py
@@ -444,7 +444,7 @@ class TestTimeouts(TestCase):
def testTimeoutDefault(self):
# default -- use global socket timeout
- self.assert_(socket.getdefaulttimeout() is None)
+ self.assertTrue(socket.getdefaulttimeout() is None)
socket.setdefaulttimeout(30)
try:
ftp = ftplib.FTP("localhost")
@@ -456,7 +456,7 @@ class TestTimeouts(TestCase):
def testTimeoutNone(self):
# no timeout -- do not use global socket timeout
- self.assert_(socket.getdefaulttimeout() is None)
+ self.assertTrue(socket.getdefaulttimeout() is None)
socket.setdefaulttimeout(30)
try:
ftp = ftplib.FTP("localhost", timeout=None)
diff --git a/Lib/test/test_funcattrs.py b/Lib/test/test_funcattrs.py
index b42f6cc4be..5765b4e154 100644
--- a/Lib/test/test_funcattrs.py
+++ b/Lib/test/test_funcattrs.py
@@ -35,11 +35,11 @@ class FunctionPropertiesTest(FuncAttrsTest):
def test_dir_includes_correct_attrs(self):
self.b.known_attr = 7
- self.assert_('known_attr' in dir(self.b),
+ self.assertTrue('known_attr' in dir(self.b),
"set attributes not in dir listing of method")
# Test on underlying function object of method
self.F.a.known_attr = 7
- self.assert_('known_attr' in dir(self.fi.a), "set attribute on function "
+ self.assertTrue('known_attr' in dir(self.fi.a), "set attribute on function "
"implementations, should show up in next dir")
def test_duplicate_function_equality(self):
@@ -248,11 +248,11 @@ class CellTest(unittest.TestCase):
# their presence should not be interpreted as providing any
# guarantees about the semantics (or even existence) of cell
# comparisons in future versions of CPython.
- self.assert_(cell(2) < cell(3))
- self.assert_(empty_cell() < cell('saturday'))
- self.assert_(empty_cell() == empty_cell())
- self.assert_(cell(-36) == cell(-36.0))
- self.assert_(cell(True) > empty_cell())
+ self.assertTrue(cell(2) < cell(3))
+ self.assertTrue(empty_cell() < cell('saturday'))
+ self.assertTrue(empty_cell() == empty_cell())
+ self.assertTrue(cell(-36) == cell(-36.0))
+ self.assertTrue(cell(True) > empty_cell())
class StaticMethodAttrsTest(unittest.TestCase):
def test_func_attribute(self):
@@ -260,10 +260,10 @@ class StaticMethodAttrsTest(unittest.TestCase):
pass
c = classmethod(f)
- self.assert_(c.__func__ is f)
+ self.assertTrue(c.__func__ is f)
s = staticmethod(f)
- self.assert_(s.__func__ is f)
+ self.assertTrue(s.__func__ is f)
def test_main():
diff --git a/Lib/test/test_functools.py b/Lib/test/test_functools.py
index dedfb1ebe2..eff31e0420 100644
--- a/Lib/test/test_functools.py
+++ b/Lib/test/test_functools.py
@@ -96,7 +96,7 @@ class TestPartial(unittest.TestCase):
p = self.thetype(capture, *args)
expected = args + ('x',)
got, empty = p('x')
- self.failUnless(expected == got and empty == {})
+ self.assertTrue(expected == got and empty == {})
def test_keyword(self):
# make sure keyword arguments are captured correctly
@@ -104,15 +104,15 @@ class TestPartial(unittest.TestCase):
p = self.thetype(capture, a=a)
expected = {'a':a,'x':None}
empty, got = p(x=None)
- self.failUnless(expected == got and empty == ())
+ self.assertTrue(expected == got and empty == ())
def test_no_side_effects(self):
# make sure there are no side effects that affect subsequent calls
p = self.thetype(capture, 0, a=1)
args1, kw1 = p(1, b=2)
- self.failUnless(args1 == (0,1) and kw1 == {'a':1,'b':2})
+ self.assertTrue(args1 == (0,1) and kw1 == {'a':1,'b':2})
args2, kw2 = p()
- self.failUnless(args2 == (0,) and kw2 == {'a':1})
+ self.assertTrue(args2 == (0,) and kw2 == {'a':1})
def test_error_propagation(self):
def f(x, y):
@@ -172,13 +172,13 @@ class TestUpdateWrapper(unittest.TestCase):
updated=functools.WRAPPER_UPDATES):
# Check attributes were assigned
for name in assigned:
- self.failUnless(getattr(wrapper, name) is getattr(wrapped, name))
+ self.assertTrue(getattr(wrapper, name) is getattr(wrapped, name))
# Check attributes were updated
for name in updated:
wrapper_attr = getattr(wrapper, name)
wrapped_attr = getattr(wrapped, name)
for key in wrapped_attr:
- self.failUnless(wrapped_attr[key] is wrapper_attr[key])
+ self.assertTrue(wrapped_attr[key] is wrapper_attr[key])
def test_default_update(self):
def f():
@@ -204,7 +204,7 @@ class TestUpdateWrapper(unittest.TestCase):
self.check_wrapper(wrapper, f, (), ())
self.assertEqual(wrapper.__name__, 'wrapper')
self.assertEqual(wrapper.__doc__, None)
- self.failIf(hasattr(wrapper, 'attr'))
+ self.assertFalse(hasattr(wrapper, 'attr'))
def test_selective_update(self):
def f():
@@ -229,7 +229,7 @@ class TestUpdateWrapper(unittest.TestCase):
pass
functools.update_wrapper(wrapper, max)
self.assertEqual(wrapper.__name__, 'max')
- self.assert_(wrapper.__doc__.startswith('max('))
+ self.assertTrue(wrapper.__doc__.startswith('max('))
class TestWraps(TestUpdateWrapper):
@@ -257,7 +257,7 @@ class TestWraps(TestUpdateWrapper):
self.check_wrapper(wrapper, f, (), ())
self.assertEqual(wrapper.__name__, 'wrapper')
self.assertEqual(wrapper.__doc__, None)
- self.failIf(hasattr(wrapper, 'attr'))
+ self.assertFalse(hasattr(wrapper, 'attr'))
def test_selective_update(self):
def f():
diff --git a/Lib/test/test_genericpath.py b/Lib/test/test_genericpath.py
index 9d0baeb8c2..3be9c8992b 100644
--- a/Lib/test/test_genericpath.py
+++ b/Lib/test/test_genericpath.py
@@ -6,7 +6,7 @@ import genericpath
class AllCommonTest(unittest.TestCase):
def assertIs(self, a, b):
- self.assert_(a is b)
+ self.assertTrue(a is b)
def test_commonprefix(self):
self.assertEqual(
@@ -50,7 +50,7 @@ class AllCommonTest(unittest.TestCase):
f.close()
self.assertEqual(d, b"foobar")
- self.assert_(
+ self.assertTrue(
genericpath.getctime(support.TESTFN) <=
genericpath.getmtime(support.TESTFN)
)
diff --git a/Lib/test/test_getargs2.py b/Lib/test/test_getargs2.py
index 34d8ee03bc..3ffc1cce73 100644
--- a/Lib/test/test_getargs2.py
+++ b/Lib/test/test_getargs2.py
@@ -68,68 +68,68 @@ class Unsigned_TestCase(unittest.TestCase):
from _testcapi import getargs_b
# b returns 'unsigned char', and does range checking (0 ... UCHAR_MAX)
self.assertRaises(TypeError, getargs_b, 3.14)
- self.failUnlessEqual(99, getargs_b(Long()))
- self.failUnlessEqual(99, getargs_b(Int()))
+ self.assertEqual(99, getargs_b(Long()))
+ self.assertEqual(99, getargs_b(Int()))
self.assertRaises(OverflowError, getargs_b, -1)
- self.failUnlessEqual(0, getargs_b(0))
- self.failUnlessEqual(UCHAR_MAX, getargs_b(UCHAR_MAX))
+ self.assertEqual(0, getargs_b(0))
+ self.assertEqual(UCHAR_MAX, getargs_b(UCHAR_MAX))
self.assertRaises(OverflowError, getargs_b, UCHAR_MAX + 1)
- self.failUnlessEqual(42, getargs_b(42))
- self.failUnlessEqual(42, getargs_b(42))
+ self.assertEqual(42, getargs_b(42))
+ self.assertEqual(42, getargs_b(42))
self.assertRaises(OverflowError, getargs_b, VERY_LARGE)
def test_B(self):
from _testcapi import getargs_B
# B returns 'unsigned char', no range checking
self.assertRaises(TypeError, getargs_B, 3.14)
- self.failUnlessEqual(99, getargs_B(Long()))
- self.failUnlessEqual(99, getargs_B(Int()))
+ self.assertEqual(99, getargs_B(Long()))
+ self.assertEqual(99, getargs_B(Int()))
- self.failUnlessEqual(UCHAR_MAX, getargs_B(-1))
- self.failUnlessEqual(UCHAR_MAX, getargs_B(-1))
- self.failUnlessEqual(0, getargs_B(0))
- self.failUnlessEqual(UCHAR_MAX, getargs_B(UCHAR_MAX))
- self.failUnlessEqual(0, getargs_B(UCHAR_MAX+1))
+ self.assertEqual(UCHAR_MAX, getargs_B(-1))
+ self.assertEqual(UCHAR_MAX, getargs_B(-1))
+ self.assertEqual(0, getargs_B(0))
+ self.assertEqual(UCHAR_MAX, getargs_B(UCHAR_MAX))
+ self.assertEqual(0, getargs_B(UCHAR_MAX+1))
- self.failUnlessEqual(42, getargs_B(42))
- self.failUnlessEqual(42, getargs_B(42))
- self.failUnlessEqual(UCHAR_MAX & VERY_LARGE, getargs_B(VERY_LARGE))
+ self.assertEqual(42, getargs_B(42))
+ self.assertEqual(42, getargs_B(42))
+ self.assertEqual(UCHAR_MAX & VERY_LARGE, getargs_B(VERY_LARGE))
def test_H(self):
from _testcapi import getargs_H
# H returns 'unsigned short', no range checking
self.assertRaises(TypeError, getargs_H, 3.14)
- self.failUnlessEqual(99, getargs_H(Long()))
- self.failUnlessEqual(99, getargs_H(Int()))
+ self.assertEqual(99, getargs_H(Long()))
+ self.assertEqual(99, getargs_H(Int()))
- self.failUnlessEqual(USHRT_MAX, getargs_H(-1))
- self.failUnlessEqual(0, getargs_H(0))
- self.failUnlessEqual(USHRT_MAX, getargs_H(USHRT_MAX))
- self.failUnlessEqual(0, getargs_H(USHRT_MAX+1))
+ self.assertEqual(USHRT_MAX, getargs_H(-1))
+ self.assertEqual(0, getargs_H(0))
+ self.assertEqual(USHRT_MAX, getargs_H(USHRT_MAX))
+ self.assertEqual(0, getargs_H(USHRT_MAX+1))
- self.failUnlessEqual(42, getargs_H(42))
- self.failUnlessEqual(42, getargs_H(42))
+ self.assertEqual(42, getargs_H(42))
+ self.assertEqual(42, getargs_H(42))
- self.failUnlessEqual(VERY_LARGE & USHRT_MAX, getargs_H(VERY_LARGE))
+ self.assertEqual(VERY_LARGE & USHRT_MAX, getargs_H(VERY_LARGE))
def test_I(self):
from _testcapi import getargs_I
# I returns 'unsigned int', no range checking
self.assertRaises(TypeError, getargs_I, 3.14)
- self.failUnlessEqual(99, getargs_I(Long()))
- self.failUnlessEqual(99, getargs_I(Int()))
+ self.assertEqual(99, getargs_I(Long()))
+ self.assertEqual(99, getargs_I(Int()))
- self.failUnlessEqual(UINT_MAX, getargs_I(-1))
- self.failUnlessEqual(0, getargs_I(0))
- self.failUnlessEqual(UINT_MAX, getargs_I(UINT_MAX))
- self.failUnlessEqual(0, getargs_I(UINT_MAX+1))
+ self.assertEqual(UINT_MAX, getargs_I(-1))
+ self.assertEqual(0, getargs_I(0))
+ self.assertEqual(UINT_MAX, getargs_I(UINT_MAX))
+ self.assertEqual(0, getargs_I(UINT_MAX+1))
- self.failUnlessEqual(42, getargs_I(42))
- self.failUnlessEqual(42, getargs_I(42))
+ self.assertEqual(42, getargs_I(42))
+ self.assertEqual(42, getargs_I(42))
- self.failUnlessEqual(VERY_LARGE & UINT_MAX, getargs_I(VERY_LARGE))
+ self.assertEqual(VERY_LARGE & UINT_MAX, getargs_I(VERY_LARGE))
def test_k(self):
from _testcapi import getargs_k
@@ -139,47 +139,47 @@ class Unsigned_TestCase(unittest.TestCase):
self.assertRaises(TypeError, getargs_k, Long())
self.assertRaises(TypeError, getargs_k, Int())
- self.failUnlessEqual(ULONG_MAX, getargs_k(-1))
- self.failUnlessEqual(0, getargs_k(0))
- self.failUnlessEqual(ULONG_MAX, getargs_k(ULONG_MAX))
- self.failUnlessEqual(0, getargs_k(ULONG_MAX+1))
+ self.assertEqual(ULONG_MAX, getargs_k(-1))
+ self.assertEqual(0, getargs_k(0))
+ self.assertEqual(ULONG_MAX, getargs_k(ULONG_MAX))
+ self.assertEqual(0, getargs_k(ULONG_MAX+1))
- self.failUnlessEqual(42, getargs_k(42))
- self.failUnlessEqual(42, getargs_k(42))
+ self.assertEqual(42, getargs_k(42))
+ self.assertEqual(42, getargs_k(42))
- self.failUnlessEqual(VERY_LARGE & ULONG_MAX, getargs_k(VERY_LARGE))
+ self.assertEqual(VERY_LARGE & ULONG_MAX, getargs_k(VERY_LARGE))
class Signed_TestCase(unittest.TestCase):
def test_i(self):
from _testcapi import getargs_i
# i returns 'int', and does range checking (INT_MIN ... INT_MAX)
self.assertRaises(TypeError, getargs_i, 3.14)
- self.failUnlessEqual(99, getargs_i(Long()))
- self.failUnlessEqual(99, getargs_i(Int()))
+ self.assertEqual(99, getargs_i(Long()))
+ self.assertEqual(99, getargs_i(Int()))
self.assertRaises(OverflowError, getargs_i, INT_MIN-1)
- self.failUnlessEqual(INT_MIN, getargs_i(INT_MIN))
- self.failUnlessEqual(INT_MAX, getargs_i(INT_MAX))
+ self.assertEqual(INT_MIN, getargs_i(INT_MIN))
+ self.assertEqual(INT_MAX, getargs_i(INT_MAX))
self.assertRaises(OverflowError, getargs_i, INT_MAX+1)
- self.failUnlessEqual(42, getargs_i(42))
- self.failUnlessEqual(42, getargs_i(42))
+ self.assertEqual(42, getargs_i(42))
+ self.assertEqual(42, getargs_i(42))
self.assertRaises(OverflowError, getargs_i, VERY_LARGE)
def test_l(self):
from _testcapi import getargs_l
# l returns 'long', and does range checking (LONG_MIN ... LONG_MAX)
self.assertRaises(TypeError, getargs_l, 3.14)
- self.failUnlessEqual(99, getargs_l(Long()))
- self.failUnlessEqual(99, getargs_l(Int()))
+ self.assertEqual(99, getargs_l(Long()))
+ self.assertEqual(99, getargs_l(Int()))
self.assertRaises(OverflowError, getargs_l, LONG_MIN-1)
- self.failUnlessEqual(LONG_MIN, getargs_l(LONG_MIN))
- self.failUnlessEqual(LONG_MAX, getargs_l(LONG_MAX))
+ self.assertEqual(LONG_MIN, getargs_l(LONG_MIN))
+ self.assertEqual(LONG_MAX, getargs_l(LONG_MAX))
self.assertRaises(OverflowError, getargs_l, LONG_MAX+1)
- self.failUnlessEqual(42, getargs_l(42))
- self.failUnlessEqual(42, getargs_l(42))
+ self.assertEqual(42, getargs_l(42))
+ self.assertEqual(42, getargs_l(42))
self.assertRaises(OverflowError, getargs_l, VERY_LARGE)
def test_n(self):
@@ -191,12 +191,12 @@ class Signed_TestCase(unittest.TestCase):
self.assertRaises(TypeError, getargs_n, Int())
self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MIN-1)
- self.failUnlessEqual(PY_SSIZE_T_MIN, getargs_n(PY_SSIZE_T_MIN))
- self.failUnlessEqual(PY_SSIZE_T_MAX, getargs_n(PY_SSIZE_T_MAX))
+ self.assertEqual(PY_SSIZE_T_MIN, getargs_n(PY_SSIZE_T_MIN))
+ self.assertEqual(PY_SSIZE_T_MAX, getargs_n(PY_SSIZE_T_MAX))
self.assertRaises(OverflowError, getargs_n, PY_SSIZE_T_MAX+1)
- self.failUnlessEqual(42, getargs_n(42))
- self.failUnlessEqual(42, getargs_n(42))
+ self.assertEqual(42, getargs_n(42))
+ self.assertEqual(42, getargs_n(42))
self.assertRaises(OverflowError, getargs_n, VERY_LARGE)
@@ -204,18 +204,18 @@ class LongLong_TestCase(unittest.TestCase):
def test_L(self):
from _testcapi import getargs_L
# L returns 'long long', and does range checking (LLONG_MIN ... LLONG_MAX)
- self.failUnlessRaises(TypeError, getargs_L, "Hello")
- self.failUnlessEqual(3, getargs_L(3.14))
- self.failUnlessEqual(99, getargs_L(Long()))
- self.failUnlessEqual(99, getargs_L(Int()))
+ self.assertRaises(TypeError, getargs_L, "Hello")
+ self.assertEqual(3, getargs_L(3.14))
+ self.assertEqual(99, getargs_L(Long()))
+ self.assertEqual(99, getargs_L(Int()))
self.assertRaises(OverflowError, getargs_L, LLONG_MIN-1)
- self.failUnlessEqual(LLONG_MIN, getargs_L(LLONG_MIN))
- self.failUnlessEqual(LLONG_MAX, getargs_L(LLONG_MAX))
+ self.assertEqual(LLONG_MIN, getargs_L(LLONG_MIN))
+ self.assertEqual(LLONG_MAX, getargs_L(LLONG_MAX))
self.assertRaises(OverflowError, getargs_L, LLONG_MAX+1)
- self.failUnlessEqual(42, getargs_L(42))
- self.failUnlessEqual(42, getargs_L(42))
+ self.assertEqual(42, getargs_L(42))
+ self.assertEqual(42, getargs_L(42))
self.assertRaises(OverflowError, getargs_L, VERY_LARGE)
def test_K(self):
@@ -224,14 +224,14 @@ class LongLong_TestCase(unittest.TestCase):
self.assertRaises(TypeError, getargs_K, 3.14)
self.assertRaises(TypeError, getargs_K, Long())
self.assertRaises(TypeError, getargs_K, Int())
- self.failUnlessEqual(ULLONG_MAX, getargs_K(ULLONG_MAX))
- self.failUnlessEqual(0, getargs_K(0))
- self.failUnlessEqual(0, getargs_K(ULLONG_MAX+1))
+ self.assertEqual(ULLONG_MAX, getargs_K(ULLONG_MAX))
+ self.assertEqual(0, getargs_K(0))
+ self.assertEqual(0, getargs_K(ULLONG_MAX+1))
- self.failUnlessEqual(42, getargs_K(42))
- self.failUnlessEqual(42, getargs_K(42))
+ self.assertEqual(42, getargs_K(42))
+ self.assertEqual(42, getargs_K(42))
- self.failUnlessEqual(VERY_LARGE & ULLONG_MAX, getargs_K(VERY_LARGE))
+ self.assertEqual(VERY_LARGE & ULLONG_MAX, getargs_K(VERY_LARGE))
class Tuple_TestCase(unittest.TestCase):
diff --git a/Lib/test/test_getopt.py b/Lib/test/test_getopt.py
index b7a6309a07..20b569038b 100644
--- a/Lib/test/test_getopt.py
+++ b/Lib/test/test_getopt.py
@@ -23,21 +23,21 @@ class GetoptTests(unittest.TestCase):
self.assertRaises(getopt.GetoptError, *args, **kwargs)
def test_short_has_arg(self):
- self.failUnless(getopt.short_has_arg('a', 'a:'))
- self.failIf(getopt.short_has_arg('a', 'a'))
+ self.assertTrue(getopt.short_has_arg('a', 'a:'))
+ self.assertFalse(getopt.short_has_arg('a', 'a'))
self.assertError(getopt.short_has_arg, 'a', 'b')
def test_long_has_args(self):
has_arg, option = getopt.long_has_args('abc', ['abc='])
- self.failUnless(has_arg)
+ self.assertTrue(has_arg)
self.assertEqual(option, 'abc')
has_arg, option = getopt.long_has_args('abc', ['abc'])
- self.failIf(has_arg)
+ self.assertFalse(has_arg)
self.assertEqual(option, 'abc')
has_arg, option = getopt.long_has_args('abc', ['abcd'])
- self.failIf(has_arg)
+ self.assertFalse(has_arg)
self.assertEqual(option, 'abcd')
self.assertError(getopt.long_has_args, 'abc', ['def'])
diff --git a/Lib/test/test_gettext.py b/Lib/test/test_gettext.py
index 0023941dd5..d667819ec2 100644
--- a/Lib/test/test_gettext.py
+++ b/Lib/test/test_gettext.py
@@ -306,7 +306,7 @@ class UnicodeTranslationsTest(GettextBaseTest):
self._ = self.t.gettext
def test_unicode_msgid(self):
- unless = self.failUnless
+ unless = self.assertTrue
unless(isinstance(self._(''), str))
unless(isinstance(self._(''), str))
diff --git a/Lib/test/test_grammar.py b/Lib/test/test_grammar.py
index 977f0b8b35..b8612070fc 100644
--- a/Lib/test/test_grammar.py
+++ b/Lib/test/test_grammar.py
@@ -38,9 +38,9 @@ class TokenTests(unittest.TestCase):
if maxsize == 2147483647:
self.assertEquals(-2147483647-1, -0o20000000000)
# XXX -2147483648
- self.assert_(0o37777777777 > 0)
- self.assert_(0xffffffff > 0)
- self.assert_(0b1111111111111111111111111111111 > 0)
+ self.assertTrue(0o37777777777 > 0)
+ self.assertTrue(0xffffffff > 0)
+ self.assertTrue(0b1111111111111111111111111111111 > 0)
for s in ('2147483648', '0o40000000000', '0x100000000',
'0b10000000000000000000000000000000'):
try:
@@ -49,9 +49,9 @@ class TokenTests(unittest.TestCase):
self.fail("OverflowError on huge integer literal %r" % s)
elif maxsize == 9223372036854775807:
self.assertEquals(-9223372036854775807-1, -0o1000000000000000000000)
- self.assert_(0o1777777777777777777777 > 0)
- self.assert_(0xffffffffffffffff > 0)
- self.assert_(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
+ self.assertTrue(0o1777777777777777777777 > 0)
+ self.assertTrue(0xffffffffffffffff > 0)
+ self.assertTrue(0b11111111111111111111111111111111111111111111111111111111111111 > 0)
for s in '9223372036854775808', '0o2000000000000000000000', \
'0x10000000000000000', \
'0b100000000000000000000000000000000000000000000000000000000000000':
@@ -87,15 +87,15 @@ class TokenTests(unittest.TestCase):
x = 3.1e4
def testStringLiterals(self):
- x = ''; y = ""; self.assert_(len(x) == 0 and x == y)
- x = '\''; y = "'"; self.assert_(len(x) == 1 and x == y and ord(x) == 39)
- x = '"'; y = "\""; self.assert_(len(x) == 1 and x == y and ord(x) == 34)
+ x = ''; y = ""; self.assertTrue(len(x) == 0 and x == y)
+ x = '\''; y = "'"; self.assertTrue(len(x) == 1 and x == y and ord(x) == 39)
+ x = '"'; y = "\""; self.assertTrue(len(x) == 1 and x == y and ord(x) == 34)
x = "doesn't \"shrink\" does it"
y = 'doesn\'t "shrink" does it'
- self.assert_(len(x) == 24 and x == y)
+ self.assertTrue(len(x) == 24 and x == y)
x = "does \"shrink\" doesn't it"
y = 'does "shrink" doesn\'t it'
- self.assert_(len(x) == 24 and x == y)
+ self.assertTrue(len(x) == 24 and x == y)
x = """
The "quick"
brown fox
@@ -128,7 +128,7 @@ the \'lazy\' dog.\n\
def testEllipsis(self):
x = ...
- self.assert_(x is Ellipsis)
+ self.assertTrue(x is Ellipsis)
self.assertRaises(SyntaxError, eval, ".. .")
class GrammarTests(unittest.TestCase):
@@ -494,7 +494,7 @@ class GrammarTests(unittest.TestCase):
nonlocal x, y
def testAssert(self):
- # assert_stmt: 'assert' test [',' test]
+ # assertTruestmt: 'assert' test [',' test]
assert 1
assert 1, 1
assert lambda x:x
diff --git a/Lib/test/test_grp.py b/Lib/test/test_grp.py
index 1c1f75f776..765b4b68f5 100755
--- a/Lib/test/test_grp.py
+++ b/Lib/test/test_grp.py
@@ -12,13 +12,13 @@ class GroupDatabaseTestCase(unittest.TestCase):
# attributes promised by the docs
self.assertEqual(len(value), 4)
self.assertEqual(value[0], value.gr_name)
- self.assert_(isinstance(value.gr_name, str))
+ self.assertTrue(isinstance(value.gr_name, str))
self.assertEqual(value[1], value.gr_passwd)
- self.assert_(isinstance(value.gr_passwd, str))
+ self.assertTrue(isinstance(value.gr_passwd, str))
self.assertEqual(value[2], value.gr_gid)
- self.assert_(isinstance(value.gr_gid, int))
+ self.assertTrue(isinstance(value.gr_gid, int))
self.assertEqual(value[3], value.gr_mem)
- self.assert_(isinstance(value.gr_mem, list))
+ self.assertTrue(isinstance(value.gr_mem, list))
def test_values(self):
entries = grp.getgrall()
diff --git a/Lib/test/test_gzip.py b/Lib/test/test_gzip.py
index baf3a21f87..d92863532f 100644
--- a/Lib/test/test_gzip.py
+++ b/Lib/test/test_gzip.py
@@ -91,7 +91,7 @@ class TestGzip(unittest.TestCase):
while 1:
L = f.readline(line_length)
if not L and line_length != 0: break
- self.assert_(len(L) <= line_length)
+ self.assertTrue(len(L) <= line_length)
line_length = (line_length + 1) % 50
f.close()
@@ -157,7 +157,7 @@ class TestGzip(unittest.TestCase):
def test_1647484(self):
for mode in ('wb', 'rb'):
f = gzip.GzipFile(self.filename, mode)
- self.assert_(hasattr(f, "name"))
+ self.assertTrue(hasattr(f, "name"))
self.assertEqual(f.name, self.filename)
f.close()
@@ -169,7 +169,7 @@ class TestGzip(unittest.TestCase):
fRead = gzip.GzipFile(self.filename)
dataRead = fRead.read()
self.assertEqual(dataRead, data1)
- self.assert_(hasattr(fRead, 'mtime'))
+ self.assertTrue(hasattr(fRead, 'mtime'))
self.assertEqual(fRead.mtime, mtime)
fRead.close()
diff --git a/Lib/test/test_hash.py b/Lib/test/test_hash.py
index 5babc5a9a4..569e5e054c 100644
--- a/Lib/test/test_hash.py
+++ b/Lib/test/test_hash.py
@@ -91,7 +91,7 @@ class HashInheritanceTestCase(unittest.TestCase):
objects = (self.default_expected +
self.fixed_expected)
for obj in objects:
- self.assert_(isinstance(obj, Hashable), repr(obj))
+ self.assertTrue(isinstance(obj, Hashable), repr(obj))
def test_not_hashable(self):
for obj in self.error_expected:
diff --git a/Lib/test/test_hashlib.py b/Lib/test/test_hashlib.py
index 5bfea6b9d2..d0ad07d82e 100644
--- a/Lib/test/test_hashlib.py
+++ b/Lib/test/test_hashlib.py
@@ -36,7 +36,7 @@ class HashLibTestCase(unittest.TestCase):
except ValueError:
pass
else:
- self.assert_(0 == "hashlib didn't reject bogus hash name")
+ self.assertTrue(0 == "hashlib didn't reject bogus hash name")
def test_hexdigest(self):
for name in self.supported_hash_names:
diff --git a/Lib/test/test_heapq.py b/Lib/test/test_heapq.py
index 94c3992291..5e3b0ee981 100644
--- a/Lib/test/test_heapq.py
+++ b/Lib/test/test_heapq.py
@@ -46,7 +46,7 @@ class TestHeap(unittest.TestCase):
for pos, item in enumerate(heap):
if pos: # pos 0 has no parent
parentpos = (pos-1) >> 1
- self.assert_(heap[parentpos] <= item)
+ self.assertTrue(heap[parentpos] <= item)
def test_heapify(self):
for size in range(30):
diff --git a/Lib/test/test_hmac.py b/Lib/test/test_hmac.py
index 8dcbe7e89c..fb78eba552 100644
--- a/Lib/test/test_hmac.py
+++ b/Lib/test/test_hmac.py
@@ -280,7 +280,7 @@ class CopyTestCase(unittest.TestCase):
# Testing if attributes are of same type.
h1 = hmac.HMAC(b"key")
h2 = h1.copy()
- self.failUnless(h1.digest_cons == h2.digest_cons,
+ self.assertTrue(h1.digest_cons == h2.digest_cons,
"digest constructors don't match.")
self.assertEqual(type(h1.inner), type(h2.inner),
"Types of inner don't match.")
@@ -292,10 +292,10 @@ class CopyTestCase(unittest.TestCase):
h1 = hmac.HMAC(b"key")
h2 = h1.copy()
# Using id() in case somebody has overridden __eq__/__ne__.
- self.failUnless(id(h1) != id(h2), "No real copy of the HMAC instance.")
- self.failUnless(id(h1.inner) != id(h2.inner),
+ self.assertTrue(id(h1) != id(h2), "No real copy of the HMAC instance.")
+ self.assertTrue(id(h1.inner) != id(h2.inner),
"No real copy of the attribute 'inner'.")
- self.failUnless(id(h1.outer) != id(h2.outer),
+ self.assertTrue(id(h1.outer) != id(h2.outer),
"No real copy of the attribute 'outer'.")
def test_equality(self):
diff --git a/Lib/test/test_http_cookiejar.py b/Lib/test/test_http_cookiejar.py
index 5ec0c25132..e5f7143200 100644
--- a/Lib/test/test_http_cookiejar.py
+++ b/Lib/test/test_http_cookiejar.py
@@ -25,7 +25,7 @@ class DateTimeTests(TestCase):
az = time2isoz()
bz = time2isoz(500000)
for text in (az, bz):
- self.assert_(re.search(r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\dZ$", text),
+ self.assertTrue(re.search(r"^\d{4}-\d\d-\d\d \d\d:\d\d:\d\dZ$", text),
"bad time2isoz format: %s %s" % (az, bz))
def test_http2time(self):
@@ -74,7 +74,7 @@ class DateTimeTests(TestCase):
t2 = http2time(s.lower())
t3 = http2time(s.upper())
- self.assert_(t == t2 == t3 == test_t,
+ self.assertTrue(t == t2 == t3 == test_t,
"'%s' => %s, %s, %s (%s)" % (s, t, t2, t3, test_t))
def test_http2time_garbage(self):
@@ -90,7 +90,7 @@ class DateTimeTests(TestCase):
'01-01-1980 00:61:00',
'01-01-1980 00:00:62',
]:
- self.assert_(http2time(test) is None,
+ self.assertTrue(http2time(test) is None,
"http2time(%s) is not None\n"
"http2time(test) %s" % (test, http2time(test))
)
@@ -332,8 +332,8 @@ class CookieTests(TestCase):
]:
request = urllib.request.Request(url)
r = pol.domain_return_ok(domain, request)
- if ok: self.assert_(r)
- else: self.assert_(not r)
+ if ok: self.assertTrue(r)
+ else: self.assertTrue(not r)
def test_missing_value(self):
# missing = sign in Cookie: header is regarded by Mozilla as a missing
@@ -343,10 +343,10 @@ class CookieTests(TestCase):
interact_netscape(c, "http://www.acme.com/", 'eggs')
interact_netscape(c, "http://www.acme.com/", '"spam"; path=/foo/')
cookie = c._cookies["www.acme.com"]["/"]["eggs"]
- self.assert_(cookie.value is None)
+ self.assertTrue(cookie.value is None)
self.assertEquals(cookie.name, "eggs")
cookie = c._cookies["www.acme.com"]['/foo/']['"spam"']
- self.assert_(cookie.value is None)
+ self.assertTrue(cookie.value is None)
self.assertEquals(cookie.name, '"spam"')
self.assertEquals(lwp_cookie_str(cookie), (
r'"spam"; path="/foo/"; domain="www.acme.com"; '
@@ -388,7 +388,7 @@ class CookieTests(TestCase):
try:
cookie = c._cookies["www.example.com"]["/"]["ni"]
except KeyError:
- self.assert_(version is None) # didn't expect a stored cookie
+ self.assertTrue(version is None) # didn't expect a stored cookie
else:
self.assertEqual(cookie.version, version)
# 2965 cookies are unaffected
@@ -410,28 +410,28 @@ class CookieTests(TestCase):
cookie = c._cookies[".acme.com"]["/"]["spam"]
self.assertEquals(cookie.domain, ".acme.com")
- self.assert_(cookie.domain_specified)
+ self.assertTrue(cookie.domain_specified)
self.assertEquals(cookie.port, DEFAULT_HTTP_PORT)
- self.assert_(not cookie.port_specified)
+ self.assertTrue(not cookie.port_specified)
# case is preserved
- self.assert_(cookie.has_nonstandard_attr("blArgh") and
+ self.assertTrue(cookie.has_nonstandard_attr("blArgh") and
not cookie.has_nonstandard_attr("blargh"))
cookie = c._cookies["www.acme.com"]["/"]["ni"]
self.assertEquals(cookie.domain, "www.acme.com")
- self.assert_(not cookie.domain_specified)
+ self.assertTrue(not cookie.domain_specified)
self.assertEquals(cookie.port, "80,8080")
- self.assert_(cookie.port_specified)
+ self.assertTrue(cookie.port_specified)
cookie = c._cookies["www.acme.com"]["/"]["nini"]
- self.assert_(cookie.port is None)
- self.assert_(not cookie.port_specified)
+ self.assertTrue(cookie.port is None)
+ self.assertTrue(not cookie.port_specified)
# invalid expires should not cause cookie to be dropped
foo = c._cookies["www.acme.com"]["/"]["foo"]
spam = c._cookies["www.acme.com"]["/"]["foo"]
- self.assert_(foo.expires is None)
- self.assert_(spam.expires is None)
+ self.assertTrue(foo.expires is None)
+ self.assertTrue(spam.expires is None)
def test_ns_parser_special_names(self):
# names such as 'expires' are not special in first name=value pair
@@ -441,8 +441,8 @@ class CookieTests(TestCase):
interact_netscape(c, "http://www.acme.com/", 'version=eggs; spam=eggs')
cookies = c._cookies["www.acme.com"]["/"]
- self.assert_('expires' in cookies)
- self.assert_('version' in cookies)
+ self.assertTrue('expires' in cookies)
+ self.assertTrue('version' in cookies)
def test_expires(self):
# if expires is in future, keep cookie...
@@ -457,7 +457,7 @@ class CookieTests(TestCase):
now)
h = interact_netscape(c, "http://www.acme.com/")
self.assertEquals(len(c), 1)
- self.assert_('spam="bar"' in h and "foo" not in h)
+ self.assertTrue('spam="bar"' in h and "foo" not in h)
# max-age takes precedence over expires, and zero max-age is request to
# delete both new cookie and any old matching cookie
@@ -478,7 +478,7 @@ class CookieTests(TestCase):
self.assertEquals(len(c), 2)
c.clear_session_cookies()
self.assertEquals(len(c), 1)
- self.assert_('spam="bar"' in h)
+ self.assertTrue('spam="bar"' in h)
# XXX RFC 2965 expiry rules (some apply to V0 too)
@@ -488,39 +488,39 @@ class CookieTests(TestCase):
c = CookieJar(pol)
interact_2965(c, "http://www.acme.com/", 'spam="bar"; Version="1"')
- self.assert_("/" in c._cookies["www.acme.com"])
+ self.assertTrue("/" in c._cookies["www.acme.com"])
c = CookieJar(pol)
interact_2965(c, "http://www.acme.com/blah", 'eggs="bar"; Version="1"')
- self.assert_("/" in c._cookies["www.acme.com"])
+ self.assertTrue("/" in c._cookies["www.acme.com"])
c = CookieJar(pol)
interact_2965(c, "http://www.acme.com/blah/rhubarb",
'eggs="bar"; Version="1"')
- self.assert_("/blah/" in c._cookies["www.acme.com"])
+ self.assertTrue("/blah/" in c._cookies["www.acme.com"])
c = CookieJar(pol)
interact_2965(c, "http://www.acme.com/blah/rhubarb/",
'eggs="bar"; Version="1"')
- self.assert_("/blah/rhubarb/" in c._cookies["www.acme.com"])
+ self.assertTrue("/blah/rhubarb/" in c._cookies["www.acme.com"])
# Netscape
c = CookieJar()
interact_netscape(c, "http://www.acme.com/", 'spam="bar"')
- self.assert_("/" in c._cookies["www.acme.com"])
+ self.assertTrue("/" in c._cookies["www.acme.com"])
c = CookieJar()
interact_netscape(c, "http://www.acme.com/blah", 'eggs="bar"')
- self.assert_("/" in c._cookies["www.acme.com"])
+ self.assertTrue("/" in c._cookies["www.acme.com"])
c = CookieJar()
interact_netscape(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"')
- self.assert_("/blah" in c._cookies["www.acme.com"])
+ self.assertTrue("/blah" in c._cookies["www.acme.com"])
c = CookieJar()
interact_netscape(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"')
- self.assert_("/blah/rhubarb" in c._cookies["www.acme.com"])
+ self.assertTrue("/blah/rhubarb" in c._cookies["www.acme.com"])
def test_escape_path(self):
cases = [
@@ -589,14 +589,14 @@ class CookieTests(TestCase):
self.assertEquals(request_host(req), "www.acme.com")
def test_is_HDN(self):
- self.assert_(is_HDN("foo.bar.com"))
- self.assert_(is_HDN("1foo2.3bar4.5com"))
- self.assert_(not is_HDN("192.168.1.1"))
- self.assert_(not is_HDN(""))
- self.assert_(not is_HDN("."))
- self.assert_(not is_HDN(".foo.bar.com"))
- self.assert_(not is_HDN("..foo"))
- self.assert_(not is_HDN("foo."))
+ self.assertTrue(is_HDN("foo.bar.com"))
+ self.assertTrue(is_HDN("1foo2.3bar4.5com"))
+ self.assertTrue(not is_HDN("192.168.1.1"))
+ self.assertTrue(not is_HDN(""))
+ self.assertTrue(not is_HDN("."))
+ self.assertTrue(not is_HDN(".foo.bar.com"))
+ self.assertTrue(not is_HDN("..foo"))
+ self.assertTrue(not is_HDN("foo."))
def test_reach(self):
self.assertEquals(reach("www.acme.com"), ".acme.com")
@@ -609,40 +609,40 @@ class CookieTests(TestCase):
self.assertEquals(reach("192.168.0.1"), "192.168.0.1")
def test_domain_match(self):
- self.assert_(domain_match("192.168.1.1", "192.168.1.1"))
- self.assert_(not domain_match("192.168.1.1", ".168.1.1"))
- self.assert_(domain_match("x.y.com", "x.Y.com"))
- self.assert_(domain_match("x.y.com", ".Y.com"))
- self.assert_(not domain_match("x.y.com", "Y.com"))
- self.assert_(domain_match("a.b.c.com", ".c.com"))
- self.assert_(not domain_match(".c.com", "a.b.c.com"))
- self.assert_(domain_match("example.local", ".local"))
- self.assert_(not domain_match("blah.blah", ""))
- self.assert_(not domain_match("", ".rhubarb.rhubarb"))
- self.assert_(domain_match("", ""))
-
- self.assert_(user_domain_match("acme.com", "acme.com"))
- self.assert_(not user_domain_match("acme.com", ".acme.com"))
- self.assert_(user_domain_match("rhubarb.acme.com", ".acme.com"))
- self.assert_(user_domain_match("www.rhubarb.acme.com", ".acme.com"))
- self.assert_(user_domain_match("x.y.com", "x.Y.com"))
- self.assert_(user_domain_match("x.y.com", ".Y.com"))
- self.assert_(not user_domain_match("x.y.com", "Y.com"))
- self.assert_(user_domain_match("y.com", "Y.com"))
- self.assert_(not user_domain_match(".y.com", "Y.com"))
- self.assert_(user_domain_match(".y.com", ".Y.com"))
- self.assert_(user_domain_match("x.y.com", ".com"))
- self.assert_(not user_domain_match("x.y.com", "com"))
- self.assert_(not user_domain_match("x.y.com", "m"))
- self.assert_(not user_domain_match("x.y.com", ".m"))
- self.assert_(not user_domain_match("x.y.com", ""))
- self.assert_(not user_domain_match("x.y.com", "."))
- self.assert_(user_domain_match("192.168.1.1", "192.168.1.1"))
+ self.assertTrue(domain_match("192.168.1.1", "192.168.1.1"))
+ self.assertTrue(not domain_match("192.168.1.1", ".168.1.1"))
+ self.assertTrue(domain_match("x.y.com", "x.Y.com"))
+ self.assertTrue(domain_match("x.y.com", ".Y.com"))
+ self.assertTrue(not domain_match("x.y.com", "Y.com"))
+ self.assertTrue(domain_match("a.b.c.com", ".c.com"))
+ self.assertTrue(not domain_match(".c.com", "a.b.c.com"))
+ self.assertTrue(domain_match("example.local", ".local"))
+ self.assertTrue(not domain_match("blah.blah", ""))
+ self.assertTrue(not domain_match("", ".rhubarb.rhubarb"))
+ self.assertTrue(domain_match("", ""))
+
+ self.assertTrue(user_domain_match("acme.com", "acme.com"))
+ self.assertTrue(not user_domain_match("acme.com", ".acme.com"))
+ self.assertTrue(user_domain_match("rhubarb.acme.com", ".acme.com"))
+ self.assertTrue(user_domain_match("www.rhubarb.acme.com", ".acme.com"))
+ self.assertTrue(user_domain_match("x.y.com", "x.Y.com"))
+ self.assertTrue(user_domain_match("x.y.com", ".Y.com"))
+ self.assertTrue(not user_domain_match("x.y.com", "Y.com"))
+ self.assertTrue(user_domain_match("y.com", "Y.com"))
+ self.assertTrue(not user_domain_match(".y.com", "Y.com"))
+ self.assertTrue(user_domain_match(".y.com", ".Y.com"))
+ self.assertTrue(user_domain_match("x.y.com", ".com"))
+ self.assertTrue(not user_domain_match("x.y.com", "com"))
+ self.assertTrue(not user_domain_match("x.y.com", "m"))
+ self.assertTrue(not user_domain_match("x.y.com", ".m"))
+ self.assertTrue(not user_domain_match("x.y.com", ""))
+ self.assertTrue(not user_domain_match("x.y.com", "."))
+ self.assertTrue(user_domain_match("192.168.1.1", "192.168.1.1"))
# not both HDNs, so must string-compare equal to match
- self.assert_(not user_domain_match("192.168.1.1", ".168.1.1"))
- self.assert_(not user_domain_match("192.168.1.1", "."))
+ self.assertTrue(not user_domain_match("192.168.1.1", ".168.1.1"))
+ self.assertTrue(not user_domain_match("192.168.1.1", "."))
# empty string is a special case
- self.assert_(not user_domain_match("192.168.1.1", ""))
+ self.assertTrue(not user_domain_match("192.168.1.1", ""))
def test_wrong_domain(self):
# Cookies whose effective request-host name does not domain-match the
@@ -789,7 +789,7 @@ class CookieTests(TestCase):
self.assertEquals(len(c), 2)
# ... and check is doesn't get returned
c.add_cookie_header(req)
- self.assert_(not req.has_header("Cookie"))
+ self.assertTrue(not req.has_header("Cookie"))
def test_domain_block(self):
pol = DefaultCookiePolicy(
@@ -813,7 +813,7 @@ class CookieTests(TestCase):
self.assertEquals(len(c), 1)
req = urllib.request.Request("http://www.roadrunner.net/")
c.add_cookie_header(req)
- self.assert_((req.has_header("Cookie") and
+ self.assertTrue((req.has_header("Cookie") and
req.has_header("Cookie2")))
c.clear()
@@ -829,7 +829,7 @@ class CookieTests(TestCase):
self.assertEquals(len(c), 2)
# ... and check is doesn't get returned
c.add_cookie_header(req)
- self.assert_(not req.has_header("Cookie"))
+ self.assertTrue(not req.has_header("Cookie"))
def test_secure(self):
for ns in True, False:
@@ -847,10 +847,10 @@ class CookieTests(TestCase):
url = "http://www.acme.com/"
int(c, url, "foo1=bar%s%s" % (vs, whitespace))
int(c, url, "foo2=bar%s; secure%s" % (vs, whitespace))
- self.assert_(
+ self.assertTrue(
not c._cookies["www.acme.com"]["/"]["foo1"].secure,
"non-secure cookie registered secure")
- self.assert_(
+ self.assertTrue(
c._cookies["www.acme.com"]["/"]["foo2"].secure,
"secure cookie registered non-secure")
@@ -868,7 +868,7 @@ class CookieTests(TestCase):
req = urllib.request.Request(url)
self.assertEquals(len(c), 1)
c.add_cookie_header(req)
- self.assert_(req.has_header("Cookie"))
+ self.assertTrue(req.has_header("Cookie"))
def test_domain_mirror(self):
pol = DefaultCookiePolicy(rfc2965=True)
@@ -877,21 +877,21 @@ class CookieTests(TestCase):
url = "http://foo.bar.com/"
interact_2965(c, url, "spam=eggs; Version=1")
h = interact_2965(c, url)
- self.assert_("Domain" not in h,
+ self.assertTrue("Domain" not in h,
"absent domain returned with domain present")
c = CookieJar(pol)
url = "http://foo.bar.com/"
interact_2965(c, url, 'spam=eggs; Version=1; Domain=.bar.com')
h = interact_2965(c, url)
- self.assert_('$Domain=".bar.com"' in h, "domain not returned")
+ self.assertTrue('$Domain=".bar.com"' in h, "domain not returned")
c = CookieJar(pol)
url = "http://foo.bar.com/"
# note missing initial dot in Domain
interact_2965(c, url, 'spam=eggs; Version=1; Domain=bar.com')
h = interact_2965(c, url)
- self.assert_('$Domain="bar.com"' in h, "domain not returned")
+ self.assertTrue('$Domain="bar.com"' in h, "domain not returned")
def test_path_mirror(self):
pol = DefaultCookiePolicy(rfc2965=True)
@@ -900,14 +900,14 @@ class CookieTests(TestCase):
url = "http://foo.bar.com/"
interact_2965(c, url, "spam=eggs; Version=1")
h = interact_2965(c, url)
- self.assert_("Path" not in h,
+ self.assertTrue("Path" not in h,
"absent path returned with path present")
c = CookieJar(pol)
url = "http://foo.bar.com/"
interact_2965(c, url, 'spam=eggs; Version=1; Path=/')
h = interact_2965(c, url)
- self.assert_('$Path="/"' in h, "path not returned")
+ self.assertTrue('$Path="/"' in h, "path not returned")
def test_port_mirror(self):
pol = DefaultCookiePolicy(rfc2965=True)
@@ -916,28 +916,28 @@ class CookieTests(TestCase):
url = "http://foo.bar.com/"
interact_2965(c, url, "spam=eggs; Version=1")
h = interact_2965(c, url)
- self.assert_("Port" not in h,
+ self.assertTrue("Port" not in h,
"absent port returned with port present")
c = CookieJar(pol)
url = "http://foo.bar.com/"
interact_2965(c, url, "spam=eggs; Version=1; Port")
h = interact_2965(c, url)
- self.assert_(re.search("\$Port([^=]|$)", h),
+ self.assertTrue(re.search("\$Port([^=]|$)", h),
"port with no value not returned with no value")
c = CookieJar(pol)
url = "http://foo.bar.com/"
interact_2965(c, url, 'spam=eggs; Version=1; Port="80"')
h = interact_2965(c, url)
- self.assert_('$Port="80"' in h,
+ self.assertTrue('$Port="80"' in h,
"port with single value not returned with single value")
c = CookieJar(pol)
url = "http://foo.bar.com/"
interact_2965(c, url, 'spam=eggs; Version=1; Port="80,8080"')
h = interact_2965(c, url)
- self.assert_('$Port="80,8080"' in h,
+ self.assertTrue('$Port="80,8080"' in h,
"port with multiple values not returned with multiple "
"values")
@@ -948,7 +948,7 @@ class CookieTests(TestCase):
'Comment="does anybody read these?"; '
'CommentURL="http://foo.bar.net/comment.html"')
h = interact_2965(c, url)
- self.assert_(
+ self.assertTrue(
"Comment" not in h,
"Comment or CommentURL cookie-attributes returned to server")
@@ -977,7 +977,7 @@ class CookieTests(TestCase):
for i in range(4):
i = 0
for c in cs:
- self.assert_(isinstance(c, Cookie))
+ self.assertTrue(isinstance(c, Cookie))
self.assertEquals(c.version, versions[i])
self.assertEquals(c.name, names[i])
self.assertEquals(c.domain, domains[i])
@@ -1030,7 +1030,7 @@ class CookieTests(TestCase):
headers = ["Set-Cookie: c=foo; expires=Foo Bar 12 33:22:11 2000"]
c = cookiejar_from_cookie_headers(headers)
cookie = c._cookies["www.example.com"]["/"]["c"]
- self.assert_(cookie.expires is None)
+ self.assertTrue(cookie.expires is None)
class LWPCookieTests(TestCase):
@@ -1104,7 +1104,7 @@ class LWPCookieTests(TestCase):
c.add_cookie_header(req)
h = req.get_header("Cookie")
- self.assert_("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and
+ self.assertTrue("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and
"CUSTOMER=WILE_E_COYOTE" in h)
headers.append('Set-Cookie: SHIPPING=FEDEX; path=/foo')
@@ -1115,7 +1115,7 @@ class LWPCookieTests(TestCase):
c.add_cookie_header(req)
h = req.get_header("Cookie")
- self.assert_("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and
+ self.assertTrue("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and
"CUSTOMER=WILE_E_COYOTE" in h and
"SHIPPING=FEDEX" not in h)
@@ -1123,7 +1123,7 @@ class LWPCookieTests(TestCase):
c.add_cookie_header(req)
h = req.get_header("Cookie")
- self.assert_(("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and
+ self.assertTrue(("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and
"CUSTOMER=WILE_E_COYOTE" in h and
h.startswith("SHIPPING=FEDEX;")))
@@ -1174,7 +1174,7 @@ class LWPCookieTests(TestCase):
req = urllib.request.Request("http://www.acme.com/ammo")
c.add_cookie_header(req)
- self.assert_(re.search(r"PART_NUMBER=RIDING_ROCKET_0023;\s*"
+ self.assertTrue(re.search(r"PART_NUMBER=RIDING_ROCKET_0023;\s*"
"PART_NUMBER=ROCKET_LAUNCHER_0001",
req.get_header("Cookie")))
@@ -1209,7 +1209,7 @@ class LWPCookieTests(TestCase):
cookie = interact_2965(
c, 'http://www.acme.com/acme/login',
'Customer="WILE_E_COYOTE"; Version="1"; Path="/acme"')
- self.assert_(not cookie)
+ self.assertTrue(not cookie)
#
# 3. User Agent -> Server
@@ -1231,7 +1231,7 @@ class LWPCookieTests(TestCase):
cookie = interact_2965(c, 'http://www.acme.com/acme/pickitem',
'Part_Number="Rocket_Launcher_0001"; '
'Version="1"; Path="/acme"');
- self.assert_(re.search(
+ self.assertTrue(re.search(
r'^\$Version="?1"?; Customer="?WILE_E_COYOTE"?; \$Path="/acme"$',
cookie))
@@ -1256,10 +1256,10 @@ class LWPCookieTests(TestCase):
cookie = interact_2965(c, "http://www.acme.com/acme/shipping",
'Shipping="FedEx"; Version="1"; Path="/acme"')
- self.assert_(re.search(r'^\$Version="?1"?;', cookie))
- self.assert_(re.search(r'Part_Number="?Rocket_Launcher_0001"?;'
+ self.assertTrue(re.search(r'^\$Version="?1"?;', cookie))
+ self.assertTrue(re.search(r'Part_Number="?Rocket_Launcher_0001"?;'
'\s*\$Path="\/acme"', cookie))
- self.assert_(re.search(r'Customer="?WILE_E_COYOTE"?;\s*\$Path="\/acme"',
+ self.assertTrue(re.search(r'Customer="?WILE_E_COYOTE"?;\s*\$Path="\/acme"',
cookie))
#
@@ -1281,7 +1281,7 @@ class LWPCookieTests(TestCase):
# Transaction is complete.
cookie = interact_2965(c, "http://www.acme.com/acme/process")
- self.assert_(
+ self.assertTrue(
re.search(r'Shipping="?FedEx"?;\s*\$Path="\/acme"', cookie) and
"WILE_E_COYOTE" in cookie)
@@ -1330,7 +1330,7 @@ class LWPCookieTests(TestCase):
# than once.
cookie = interact_2965(c, "http://www.acme.com/acme/ammo/...")
- self.assert_(
+ self.assertTrue(
re.search(r"Riding_Rocket_0023.*Rocket_Launcher_0001", cookie))
# A subsequent request by the user agent to the (same) server for a URL of
@@ -1343,7 +1343,7 @@ class LWPCookieTests(TestCase):
# the server.
cookie = interact_2965(c, "http://www.acme.com/acme/parts/")
- self.assert_("Rocket_Launcher_0001" in cookie and
+ self.assertTrue("Rocket_Launcher_0001" in cookie and
"Riding_Rocket_0023" not in cookie)
def test_rejection(self):
@@ -1357,7 +1357,7 @@ class LWPCookieTests(TestCase):
# illegal domain (no embedded dots)
cookie = interact_2965(c, "http://www.acme.com",
'foo=bar; domain=".com"; version=1')
- self.assert_(not c)
+ self.assertTrue(not c)
# legal domain
cookie = interact_2965(c, "http://www.acme.com",
@@ -1449,11 +1449,11 @@ class LWPCookieTests(TestCase):
c, "http://www.acme.com/foo%2f%25/<<%0anew\345/\346\370\345",
'bar=baz; path="/foo/"; version=1');
version_re = re.compile(r'^\$version=\"?1\"?', re.I)
- self.assert_("foo=bar" in cookie and version_re.search(cookie))
+ self.assertTrue("foo=bar" in cookie and version_re.search(cookie))
cookie = interact_2965(
c, "http://www.acme.com/foo/%25/<<%0anew\345/\346\370\345")
- self.assert_(not cookie)
+ self.assertTrue(not cookie)
# unicode URL doesn't raise exception
cookie = interact_2965(c, "http://www.acme.com/\xfc")
@@ -1493,11 +1493,11 @@ class LWPCookieTests(TestCase):
new_c = save_and_restore(c, True)
self.assertEquals(len(new_c), 6) # none discarded
- self.assert_("name='foo1', value='bar'" in repr(new_c))
+ self.assertTrue("name='foo1', value='bar'" in repr(new_c))
new_c = save_and_restore(c, False)
self.assertEquals(len(new_c), 4) # 2 of them discarded on save
- self.assert_("name='foo1', value='bar'" in repr(new_c))
+ self.assertTrue("name='foo1', value='bar'" in repr(new_c))
def test_netscape_misc(self):
# Some additional Netscape cookies tests.
@@ -1519,7 +1519,7 @@ class LWPCookieTests(TestCase):
req = urllib.request.Request("http://foo.bar.acme.com/foo")
c.add_cookie_header(req)
- self.assert_(
+ self.assertTrue(
"PART_NUMBER=3,4" in req.get_header("Cookie") and
"Customer=WILE_E_COYOTE" in req.get_header("Cookie"))
@@ -1530,11 +1530,11 @@ class LWPCookieTests(TestCase):
"foo1=bar; PORT; Discard; Version=1;")
cookie = interact_2965(c, "http://example/",
'foo2=bar; domain=".local"; Version=1')
- self.assert_("foo1=bar" in cookie)
+ self.assertTrue("foo1=bar" in cookie)
interact_2965(c, "http://example/", 'foo3=bar; Version=1')
cookie = interact_2965(c, "http://example/")
- self.assert_("foo2=bar" in cookie and len(c) == 3)
+ self.assertTrue("foo2=bar" in cookie and len(c) == 3)
def test_intranet_domains_ns(self):
c = CookieJar(DefaultCookiePolicy(rfc2965 = False))
@@ -1542,10 +1542,10 @@ class LWPCookieTests(TestCase):
cookie = interact_netscape(c, "http://example/",
'foo2=bar; domain=.local')
self.assertEquals(len(c), 2)
- self.assert_("foo1=bar" in cookie)
+ self.assertTrue("foo1=bar" in cookie)
cookie = interact_netscape(c, "http://example/")
- self.assert_("foo2=bar" in cookie)
+ self.assertTrue("foo2=bar" in cookie)
self.assertEquals(len(c), 2)
def test_empty_path(self):
@@ -1614,7 +1614,7 @@ class LWPCookieTests(TestCase):
key = "%s_after" % cookie.value
counter[key] = counter[key] + 1
- self.assert_(not (
+ self.assertTrue(not (
# a permanent cookie got lost accidently
counter["perm_after"] != counter["perm_before"] or
# a session cookie hasn't been cleared
diff --git a/Lib/test/test_httplib.py b/Lib/test/test_httplib.py
index d43c82d40f..2d76f7a79f 100644
--- a/Lib/test/test_httplib.py
+++ b/Lib/test/test_httplib.py
@@ -265,7 +265,7 @@ class TimeoutTest(TestCase):
# and into the socket.
# default -- use global socket timeout
- self.assert_(socket.getdefaulttimeout() is None)
+ self.assertTrue(socket.getdefaulttimeout() is None)
socket.setdefaulttimeout(30)
try:
httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT)
@@ -276,7 +276,7 @@ class TimeoutTest(TestCase):
httpConn.close()
# no timeout -- do not use global socket default
- self.assert_(socket.getdefaulttimeout() is None)
+ self.assertTrue(socket.getdefaulttimeout() is None)
socket.setdefaulttimeout(30)
try:
httpConn = client.HTTPConnection(HOST, TimeoutTest.PORT,
diff --git a/Lib/test/test_httpservers.py b/Lib/test/test_httpservers.py
index 837d4a6c28..13e4030fea 100644
--- a/Lib/test/test_httpservers.py
+++ b/Lib/test/test_httpservers.py
@@ -217,9 +217,9 @@ class SimpleHTTPServerTestCase(BaseTestCase):
def check_status_and_reason(self, response, status, data=None):
body = response.read()
- self.assert_(response)
+ self.assertTrue(response)
self.assertEquals(response.status, status)
- self.assert_(response.reason != None)
+ self.assertTrue(response.reason != None)
if data:
self.assertEqual(data, body)
diff --git a/Lib/test/test_imp.py b/Lib/test/test_imp.py
index cc6792ab46..70169e0698 100644
--- a/Lib/test/test_imp.py
+++ b/Lib/test/test_imp.py
@@ -12,7 +12,7 @@ class LockTests(unittest.TestCase):
"""Very basic test of import lock functions."""
def verify_lock_state(self, expected):
- self.failUnlessEqual(imp.lock_held(), expected,
+ self.assertEqual(imp.lock_held(), expected,
"expected imp.lock_held() to be %r" % expected)
def testLock(self):
LOOPS = 50
diff --git a/Lib/test/test_import.py b/Lib/test/test_import.py
index dbfadfb708..7f1e37f577 100644
--- a/Lib/test/test_import.py
+++ b/Lib/test/test_import.py
@@ -145,12 +145,12 @@ class ImportTest(unittest.TestCase):
# import x.y.z binds x in the current namespace
import test as x
import test.support
- self.assert_(x is test, x.__name__)
- self.assert_(hasattr(test.support, "__file__"))
+ self.assertTrue(x is test, x.__name__)
+ self.assertTrue(hasattr(test.support, "__file__"))
# import x.y.z as w binds z as w
import test.support as y
- self.assert_(y is test.support, y.__name__)
+ self.assertTrue(y is test.support, y.__name__)
def test_import_initless_directory_warning(self):
with warnings.catch_warnings():
@@ -168,7 +168,7 @@ class ImportTest(unittest.TestCase):
sys.path.insert(0, os.curdir)
try:
mod = __import__(TESTFN)
- self.assert_(TESTFN in sys.modules, "expected module in sys.modules")
+ self.assertTrue(TESTFN in sys.modules, "expected module in sys.modules")
self.assertEquals(mod.a, 1, "module has wrong attribute values")
self.assertEquals(mod.b, 2, "module has wrong attribute values")
@@ -185,7 +185,7 @@ class ImportTest(unittest.TestCase):
self.assertRaises(ZeroDivisionError, imp.reload, mod)
# But we still expect the module to be in sys.modules.
mod = sys.modules.get(TESTFN)
- self.failIf(mod is None, "expected module to still be in sys.modules")
+ self.assertFalse(mod is None, "expected module to still be in sys.modules")
# We should have replaced a w/ 10, but the old b value should
# stick.
@@ -207,12 +207,12 @@ class ImportTest(unittest.TestCase):
sys.path.insert(0, os.curdir)
try:
mod = __import__(TESTFN)
- self.failUnless(mod.__file__.endswith('.py'))
+ self.assertTrue(mod.__file__.endswith('.py'))
os.remove(source)
del sys.modules[TESTFN]
mod = __import__(TESTFN)
ext = mod.__file__[-4:]
- self.failUnless(ext in ('.pyc', '.pyo'), ext)
+ self.assertTrue(ext in ('.pyc', '.pyo'), ext)
finally:
sys.path.pop(0)
remove_files(TESTFN)
diff --git a/Lib/test/test_importhooks.py b/Lib/test/test_importhooks.py
index f267f79f24..bf2870dbec 100644
--- a/Lib/test/test_importhooks.py
+++ b/Lib/test/test_importhooks.py
@@ -177,7 +177,7 @@ class ImportHooksTestCase(ImportHooksBaseTestCase):
TestImporter.modules['reloadmodule'] = (False, test_co)
import reloadmodule
- self.failIf(hasattr(reloadmodule,'reloaded'))
+ self.assertFalse(hasattr(reloadmodule,'reloaded'))
import hooktestpackage.newrel
self.assertEqual(hooktestpackage.newrel.get_name(),
diff --git a/Lib/test/test_index.py b/Lib/test/test_index.py
index 31609c3107..ae905c2663 100644
--- a/Lib/test/test_index.py
+++ b/Lib/test/test_index.py
@@ -59,10 +59,10 @@ class BaseTestCase(unittest.TestCase):
def test_error(self):
self.o.ind = 'dumb'
self.n.ind = 'bad'
- self.failUnlessRaises(TypeError, operator.index, self.o)
- self.failUnlessRaises(TypeError, operator.index, self.n)
- self.failUnlessRaises(TypeError, slice(self.o).indices, 0)
- self.failUnlessRaises(TypeError, slice(self.n).indices, 0)
+ self.assertRaises(TypeError, operator.index, self.o)
+ self.assertRaises(TypeError, operator.index, self.n)
+ self.assertRaises(TypeError, slice(self.o).indices, 0)
+ self.assertRaises(TypeError, slice(self.n).indices, 0)
class SeqTestCase(unittest.TestCase):
@@ -114,11 +114,11 @@ class SeqTestCase(unittest.TestCase):
self.o.ind = 'dumb'
self.n.ind = 'bad'
indexobj = lambda x, obj: obj.seq[x]
- self.failUnlessRaises(TypeError, indexobj, self.o, self)
- self.failUnlessRaises(TypeError, indexobj, self.n, self)
+ self.assertRaises(TypeError, indexobj, self.o, self)
+ self.assertRaises(TypeError, indexobj, self.n, self)
sliceobj = lambda x, obj: obj.seq[x:]
- self.failUnlessRaises(TypeError, sliceobj, self.o, self)
- self.failUnlessRaises(TypeError, sliceobj, self.n, self)
+ self.assertRaises(TypeError, sliceobj, self.o, self)
+ self.assertRaises(TypeError, sliceobj, self.n, self)
class ListTestCase(SeqTestCase):
@@ -151,7 +151,7 @@ class ListTestCase(SeqTestCase):
lst = [5, 6, 7, 8, 9, 11]
l2 = lst.__imul__(self.n)
- self.assert_(l2 is lst)
+ self.assertTrue(l2 is lst)
self.assertEqual(lst, [5, 6, 7, 8, 9, 11] * 3)
@@ -188,8 +188,8 @@ class OverflowTestCase(unittest.TestCase):
(0, maxsize, 1))
def test_sequence_repeat(self):
- self.failUnlessRaises(OverflowError, lambda: "a" * self.pos)
- self.failUnlessRaises(OverflowError, lambda: "a" * self.neg)
+ self.assertRaises(OverflowError, lambda: "a" * self.pos)
+ self.assertRaises(OverflowError, lambda: "a" * self.neg)
def test_main():
diff --git a/Lib/test/test_inspect.py b/Lib/test/test_inspect.py
index 37be205757..c1df23e851 100644
--- a/Lib/test/test_inspect.py
+++ b/Lib/test/test_inspect.py
@@ -52,13 +52,13 @@ class IsTestBase(unittest.TestCase):
def istest(self, predicate, exp):
obj = eval(exp)
- self.failUnless(predicate(obj), '%s(%s)' % (predicate.__name__, exp))
+ self.assertTrue(predicate(obj), '%s(%s)' % (predicate.__name__, exp))
for other in self.predicates - set([predicate]):
if predicate == inspect.isgeneratorfunction and\
other == inspect.isfunction:
continue
- self.failIf(other(obj), 'not %s(%s)' % (other.__name__, exp))
+ self.assertFalse(other(obj), 'not %s(%s)' % (other.__name__, exp))
def generator_function_example(self):
for i in range(2):
@@ -91,15 +91,15 @@ class TestPredicates(IsTestBase):
self.istest(inspect.isgetsetdescriptor,
'type(tb.tb_frame).f_locals')
else:
- self.failIf(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
+ self.assertFalse(inspect.isgetsetdescriptor(type(tb.tb_frame).f_locals))
if hasattr(types, 'MemberDescriptorType'):
self.istest(inspect.ismemberdescriptor, 'datetime.timedelta.days')
else:
- self.failIf(inspect.ismemberdescriptor(datetime.timedelta.days))
+ self.assertFalse(inspect.ismemberdescriptor(datetime.timedelta.days))
def test_isroutine(self):
- self.assert_(inspect.isroutine(mod.spam))
- self.assert_(inspect.isroutine([].count))
+ self.assertTrue(inspect.isroutine(mod.spam))
+ self.assertTrue(inspect.isroutine([].count))
def test_isclass(self):
self.istest(inspect.isclass, 'mod.StupidGit')
@@ -117,8 +117,8 @@ class TestPredicates(IsTestBase):
x = C()
x.a = 42
members = dict(inspect.getmembers(x))
- self.assert_('a' in members)
- self.assert_('b' not in members)
+ self.assertTrue('a' in members)
+ self.assertTrue('b' not in members)
class TestInterpreterStack(IsTestBase):
@@ -132,7 +132,7 @@ class TestInterpreterStack(IsTestBase):
self.istest(inspect.isframe, 'mod.fr')
def test_stack(self):
- self.assert_(len(mod.st) >= 5)
+ self.assertTrue(len(mod.st) >= 5)
self.assertEqual(revise(*mod.st[0][1:]),
(modfile, 16, 'eggs', [' st = inspect.stack()\n'], 0))
self.assertEqual(revise(*mod.st[1][1:]),
@@ -449,25 +449,25 @@ class TestClassesAndFunctions(unittest.TestCase):
datablob = '1'
attrs = attrs_wo_objs(A)
- self.assert_(('s', 'static method', A) in attrs, 'missing static method')
- self.assert_(('c', 'class method', A) in attrs, 'missing class method')
- self.assert_(('p', 'property', A) in attrs, 'missing property')
- self.assert_(('m', 'method', A) in attrs,
+ self.assertTrue(('s', 'static method', A) in attrs, 'missing static method')
+ self.assertTrue(('c', 'class method', A) in attrs, 'missing class method')
+ self.assertTrue(('p', 'property', A) in attrs, 'missing property')
+ self.assertTrue(('m', 'method', A) in attrs,
'missing plain method: %r' % attrs)
- self.assert_(('m1', 'method', A) in attrs, 'missing plain method')
- self.assert_(('datablob', 'data', A) in attrs, 'missing data')
+ self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method')
+ self.assertTrue(('datablob', 'data', A) in attrs, 'missing data')
class B(A):
def m(self): pass
attrs = attrs_wo_objs(B)
- self.assert_(('s', 'static method', A) in attrs, 'missing static method')
- self.assert_(('c', 'class method', A) in attrs, 'missing class method')
- self.assert_(('p', 'property', A) in attrs, 'missing property')
- self.assert_(('m', 'method', B) in attrs, 'missing plain method')
- self.assert_(('m1', 'method', A) in attrs, 'missing plain method')
- self.assert_(('datablob', 'data', A) in attrs, 'missing data')
+ self.assertTrue(('s', 'static method', A) in attrs, 'missing static method')
+ self.assertTrue(('c', 'class method', A) in attrs, 'missing class method')
+ self.assertTrue(('p', 'property', A) in attrs, 'missing property')
+ self.assertTrue(('m', 'method', B) in attrs, 'missing plain method')
+ self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method')
+ self.assertTrue(('datablob', 'data', A) in attrs, 'missing data')
class C(A):
@@ -476,24 +476,24 @@ class TestClassesAndFunctions(unittest.TestCase):
def c(self): pass
attrs = attrs_wo_objs(C)
- self.assert_(('s', 'static method', A) in attrs, 'missing static method')
- self.assert_(('c', 'method', C) in attrs, 'missing plain method')
- self.assert_(('p', 'property', A) in attrs, 'missing property')
- self.assert_(('m', 'method', C) in attrs, 'missing plain method')
- self.assert_(('m1', 'method', A) in attrs, 'missing plain method')
- self.assert_(('datablob', 'data', A) in attrs, 'missing data')
+ self.assertTrue(('s', 'static method', A) in attrs, 'missing static method')
+ self.assertTrue(('c', 'method', C) in attrs, 'missing plain method')
+ self.assertTrue(('p', 'property', A) in attrs, 'missing property')
+ self.assertTrue(('m', 'method', C) in attrs, 'missing plain method')
+ self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method')
+ self.assertTrue(('datablob', 'data', A) in attrs, 'missing data')
class D(B, C):
def m1(self): pass
attrs = attrs_wo_objs(D)
- self.assert_(('s', 'static method', A) in attrs, 'missing static method')
- self.assert_(('c', 'method', C) in attrs, 'missing plain method')
- self.assert_(('p', 'property', A) in attrs, 'missing property')
- self.assert_(('m', 'method', B) in attrs, 'missing plain method')
- self.assert_(('m1', 'method', D) in attrs, 'missing plain method')
- self.assert_(('datablob', 'data', A) in attrs, 'missing data')
+ self.assertTrue(('s', 'static method', A) in attrs, 'missing static method')
+ self.assertTrue(('c', 'method', C) in attrs, 'missing plain method')
+ self.assertTrue(('p', 'property', A) in attrs, 'missing property')
+ self.assertTrue(('m', 'method', B) in attrs, 'missing plain method')
+ self.assertTrue(('m1', 'method', D) in attrs, 'missing plain method')
+ self.assertTrue(('datablob', 'data', A) in attrs, 'missing data')
def test_main():
run_unittest(TestDecorators, TestRetrievingSourceCode, TestOneliners,
diff --git a/Lib/test/test_int.py b/Lib/test/test_int.py
index dd40ef6fe6..d56e1f0da3 100644
--- a/Lib/test/test_int.py
+++ b/Lib/test/test_int.py
@@ -52,15 +52,15 @@ class IntTestCases(unittest.TestCase):
s = repr(-1-sys.maxsize)
x = int(s)
self.assertEqual(x+1, -sys.maxsize)
- self.assert_(isinstance(x, int))
+ self.assertTrue(isinstance(x, int))
# should return long
self.assertEqual(int(s[1:]), sys.maxsize+1)
# should return long
x = int(1e100)
- self.assert_(isinstance(x, int))
+ self.assertTrue(isinstance(x, int))
x = int(-1e100)
- self.assert_(isinstance(x, int))
+ self.assertTrue(isinstance(x, int))
# SF bug 434186: 0x80000000/2 != 0x80000000>>1.
@@ -78,7 +78,7 @@ class IntTestCases(unittest.TestCase):
self.assertRaises(ValueError, int, '123\x00 245', 20)
x = int('1' * 600)
- self.assert_(isinstance(x, int))
+ self.assertTrue(isinstance(x, int))
self.assertRaises(TypeError, int, 1, 12)
@@ -96,8 +96,8 @@ class IntTestCases(unittest.TestCase):
self.assertRaises(ValueError, int, "0b", 0)
# Bug #3236: Return small longs from PyLong_FromString
- self.assert_(int("10") is 10)
- self.assert_(int("-1") is -1)
+ self.assertTrue(int("10") is 10)
+ self.assertTrue(int("-1") is -1)
# SF bug 1334662: int(string, base) wrong answers
# Various representations of 2**32 evaluated to 0
diff --git a/Lib/test/test_io.py b/Lib/test/test_io.py
index 729c0ca7c1..1f1cba2999 100644
--- a/Lib/test/test_io.py
+++ b/Lib/test/test_io.py
@@ -391,7 +391,7 @@ class IOTest(unittest.TestCase):
with self.open(support.TESTFN, "ab") as f:
self.assertEqual(f.tell(), 3)
with self.open(support.TESTFN, "a") as f:
- self.assert_(f.tell() > 0)
+ self.assertTrue(f.tell() > 0)
def test_destructor(self):
record = []
@@ -509,7 +509,7 @@ class IOTest(unittest.TestCase):
wr = weakref.ref(f)
del f
support.gc_collect()
- self.assert_(wr() is None, wr)
+ self.assertTrue(wr() is None, wr)
with self.open(support.TESTFN, "rb") as f:
self.assertEqual(f.read(), b"abcxxx")
@@ -615,8 +615,8 @@ class CommonBufferedTests:
if s:
# The destructor *may* have printed an unraisable error, check it
self.assertEqual(len(s.splitlines()), 1)
- self.assert_(s.startswith("Exception IOError: "), s)
- self.assert_(s.endswith(" ignored"), s)
+ self.assertTrue(s.startswith("Exception IOError: "), s)
+ self.assertTrue(s.endswith(" ignored"), s)
def test_repr(self):
raw = self.MockRawIO()
@@ -713,7 +713,7 @@ class BufferedReaderTest(unittest.TestCase, CommonBufferedTests):
self.assertEquals(b"e", bufio.read(1))
self.assertEquals(b"fg", bufio.read())
self.assertEquals(b"", bufio.peek(1))
- self.assert_(None is bufio.read())
+ self.assertTrue(None is bufio.read())
self.assertEquals(b"", bufio.read())
def test_read_past_eof(self):
@@ -815,7 +815,7 @@ class CBufferedReaderTest(BufferedReaderTest):
wr = weakref.ref(f)
del f
support.gc_collect()
- self.assert_(wr() is None, wr)
+ self.assertTrue(wr() is None, wr)
class PyBufferedReaderTest(BufferedReaderTest):
tp = pyio.BufferedReader
@@ -864,7 +864,7 @@ class BufferedWriterTest(unittest.TestCase, CommonBufferedTests):
flushed = b"".join(writer._write_stack)
# At least (total - 8) bytes were implicitly flushed, perhaps more
# depending on the implementation.
- self.assert_(flushed.startswith(contents[:-8]), flushed)
+ self.assertTrue(flushed.startswith(contents[:-8]), flushed)
def check_writes(self, intermediate_func):
# Lots of writes, test the flushed output is as expected.
@@ -1075,7 +1075,7 @@ class CBufferedWriterTest(BufferedWriterTest):
wr = weakref.ref(f)
del f
support.gc_collect()
- self.assert_(wr() is None, wr)
+ self.assertTrue(wr() is None, wr)
with self.open(support.TESTFN, "rb") as f:
self.assertEqual(f.read(), b"123xxx")
@@ -1565,7 +1565,7 @@ class TextIOWrapperTest(unittest.TestCase):
t = self.TextIOWrapper(b, encoding="utf8")
self.assertEqual(t.encoding, "utf8")
t = self.TextIOWrapper(b)
- self.assert_(t.encoding is not None)
+ self.assertTrue(t.encoding is not None)
codecs.lookup(t.encoding)
def test_encoding_errors_reading(self):
@@ -1735,8 +1735,8 @@ class TextIOWrapperTest(unittest.TestCase):
if s:
# The destructor *may* have printed an unraisable error, check it
self.assertEqual(len(s.splitlines()), 1)
- self.assert_(s.startswith("Exception IOError: "), s)
- self.assert_(s.endswith(" ignored"), s)
+ self.assertTrue(s.startswith("Exception IOError: "), s)
+ self.assertTrue(s.endswith(" ignored"), s)
# Systematic tests of the text I/O API
@@ -2054,7 +2054,7 @@ class CTextIOWrapperTest(TextIOWrapperTest):
wr = weakref.ref(t)
del t
support.gc_collect()
- self.assert_(wr() is None, wr)
+ self.assertTrue(wr() is None, wr)
with self.open(support.TESTFN, "rb") as f:
self.assertEqual(f.read(), b"456def")
@@ -2278,7 +2278,7 @@ class MiscIOTest(unittest.TestCase):
wr = weakref.ref(c)
del c, b
support.gc_collect()
- self.assert_(wr() is None, wr)
+ self.assertTrue(wr() is None, wr)
def test_abcs(self):
# Test the visible base classes are ABCs.
diff --git a/Lib/test/test_ioctl.py b/Lib/test/test_ioctl.py
index dcb6695458..50597cab4e 100644
--- a/Lib/test/test_ioctl.py
+++ b/Lib/test/test_ioctl.py
@@ -24,7 +24,7 @@ class IoctlTests(unittest.TestCase):
tty = open("/dev/tty", "r")
r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ")
rpgrp = struct.unpack("i", r)[0]
- self.assert_(rpgrp in ids, "%s not in %s" % (rpgrp, ids))
+ self.assertTrue(rpgrp in ids, "%s not in %s" % (rpgrp, ids))
def test_ioctl_mutate(self):
import array
@@ -34,7 +34,7 @@ class IoctlTests(unittest.TestCase):
r = fcntl.ioctl(tty, termios.TIOCGPGRP, buf, 1)
rpgrp = buf[0]
self.assertEquals(r, 0)
- self.assert_(rpgrp in ids, "%s not in %s" % (rpgrp, ids))
+ self.assertTrue(rpgrp in ids, "%s not in %s" % (rpgrp, ids))
def test_ioctl_signed_unsigned_code_param(self):
if not pty:
diff --git a/Lib/test/test_iter.py b/Lib/test/test_iter.py
index 77885020ee..a826598215 100644
--- a/Lib/test/test_iter.py
+++ b/Lib/test/test_iter.py
@@ -75,7 +75,7 @@ class TestCase(unittest.TestCase):
seq = list(range(10))
it = iter(seq)
it2 = iter(it)
- self.assert_(it is it2)
+ self.assertTrue(it is it2)
# Test that for loops over iterators work
def test_iter_for_loop(self):
@@ -542,23 +542,23 @@ class TestCase(unittest.TestCase):
def test_in_and_not_in(self):
for sc5 in IteratingSequenceClass(5), SequenceClass(5):
for i in range(5):
- self.assert_(i in sc5)
+ self.assertTrue(i in sc5)
for i in "abc", -1, 5, 42.42, (3, 4), [], {1: 1}, 3-12j, sc5:
- self.assert_(i not in sc5)
+ self.assertTrue(i not in sc5)
self.assertRaises(TypeError, lambda: 3 in 12)
self.assertRaises(TypeError, lambda: 3 not in map)
d = {"one": 1, "two": 2, "three": 3, 1j: 2j}
for k in d:
- self.assert_(k in d)
- self.assert_(k not in d.values())
+ self.assertTrue(k in d)
+ self.assertTrue(k not in d.values())
for v in d.values():
- self.assert_(v in d.values())
- self.assert_(v not in d)
+ self.assertTrue(v in d.values())
+ self.assertTrue(v not in d)
for k, v in d.items():
- self.assert_((k, v) in d.items())
- self.assert_((v, k) not in d.items())
+ self.assertTrue((k, v) in d.items())
+ self.assertTrue((v, k) not in d.items())
f = open(TESTFN, "w")
try:
@@ -569,9 +569,9 @@ class TestCase(unittest.TestCase):
try:
for chunk in "abc":
f.seek(0, 0)
- self.assert_(chunk not in f)
+ self.assertTrue(chunk not in f)
f.seek(0, 0)
- self.assert_((chunk + "\n") in f)
+ self.assertTrue((chunk + "\n") in f)
finally:
f.close()
try:
diff --git a/Lib/test/test_itertools.py b/Lib/test/test_itertools.py
index af2efa0087..d917262fd4 100644
--- a/Lib/test/test_itertools.py
+++ b/Lib/test/test_itertools.py
@@ -131,7 +131,7 @@ class TestBasicOps(unittest.TestCase):
self.assertEqual(len(c), r) # r-length combinations
self.assertEqual(len(set(c)), r) # no duplicate elements
self.assertEqual(list(c), sorted(c)) # keep original ordering
- self.assert_(all(e in values for e in c)) # elements taken from input iterable
+ self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
self.assertEqual(list(c),
[e for e in values if e in c]) # comb is a subsequence of the input iterable
self.assertEqual(result, list(combinations1(values, r))) # matches first pure python version
@@ -195,14 +195,14 @@ class TestBasicOps(unittest.TestCase):
if n == 0 or r <= 1:
self.assertEquals(result, regular_combs) # cases that should be identical
else:
- self.assert_(set(result) >= set(regular_combs)) # rest should be supersets of regular combs
+ self.assertTrue(set(result) >= set(regular_combs)) # rest should be supersets of regular combs
for c in result:
self.assertEqual(len(c), r) # r-length combinations
noruns = [k for k,v in groupby(c)] # combo without consecutive repeats
self.assertEqual(len(noruns), len(set(noruns))) # no repeats other than consecutive
self.assertEqual(list(c), sorted(c)) # keep original ordering
- self.assert_(all(e in values for e in c)) # elements taken from input iterable
+ self.assertTrue(all(e in values for e in c)) # elements taken from input iterable
self.assertEqual(noruns,
[e for e in values if e in c]) # comb is a subsequence of the input iterable
self.assertEqual(result, list(cwr1(values, r))) # matches first pure python version
@@ -265,7 +265,7 @@ class TestBasicOps(unittest.TestCase):
for p in result:
self.assertEqual(len(p), r) # r-length permutations
self.assertEqual(len(set(p)), r) # no duplicate elements
- self.assert_(all(e in values for e in p)) # elements taken from input iterable
+ self.assertTrue(all(e in values for e in p)) # elements taken from input iterable
self.assertEqual(result, list(permutations1(values, r))) # matches first pure python version
self.assertEqual(result, list(permutations2(values, r))) # matches second pure python version
if r == n:
@@ -836,7 +836,7 @@ class TestBasicOps(unittest.TestCase):
# tee pass-through to copyable iterator
a, b = tee('abc')
c, d = tee(a)
- self.assert_(a is c)
+ self.assertTrue(a is c)
# test tee_new
t1, t2 = tee('abc')
@@ -844,7 +844,7 @@ class TestBasicOps(unittest.TestCase):
self.assertRaises(TypeError, tnew)
self.assertRaises(TypeError, tnew, 10)
t3 = tnew(t1)
- self.assert_(list(t1) == list(t2) == list(t3) == list('abc'))
+ self.assertTrue(list(t1) == list(t2) == list(t3) == list('abc'))
# test that tee objects are weak referencable
a, b = tee(range(10))
@@ -1356,7 +1356,7 @@ class SubclassWithKwargsTest(unittest.TestCase):
Subclass(newarg=1)
except TypeError as err:
# we expect type errors because of wrong argument count
- self.failIf("does not take keyword arguments" in err.args[0])
+ self.assertFalse("does not take keyword arguments" in err.args[0])
libreftest = """ Doctest for examples in the library reference: libitertools.tex
diff --git a/Lib/test/test_kqueue.py b/Lib/test/test_kqueue.py
index 42ef958060..dd1ecc8cf0 100644
--- a/Lib/test/test_kqueue.py
+++ b/Lib/test/test_kqueue.py
@@ -15,10 +15,10 @@ if not hasattr(select, "kqueue"):
class TestKQueue(unittest.TestCase):
def test_create_queue(self):
kq = select.kqueue()
- self.assert_(kq.fileno() > 0, kq.fileno())
- self.assert_(not kq.closed)
+ self.assertTrue(kq.fileno() > 0, kq.fileno())
+ self.assertTrue(not kq.closed)
kq.close()
- self.assert_(kq.closed)
+ self.assertTrue(kq.closed)
self.assertRaises(ValueError, kq.fileno)
def test_create_event(self):
@@ -34,8 +34,8 @@ class TestKQueue(unittest.TestCase):
self.assertEqual(ev.udata, 0)
self.assertEqual(ev, ev)
self.assertNotEqual(ev, other)
- self.assert_(ev < other)
- self.assert_(other >= ev)
+ self.assertTrue(ev < other)
+ self.assertTrue(other >= ev)
for op in lt, le, gt, ge:
self.assertRaises(TypeError, op, ev, None)
self.assertRaises(TypeError, op, ev, 1)
diff --git a/Lib/test/test_largefile.py b/Lib/test/test_largefile.py
index 1e868e059d..7fd3e0e652 100644
--- a/Lib/test/test_largefile.py
+++ b/Lib/test/test_largefile.py
@@ -139,7 +139,7 @@ class LargeFileTest(unittest.TestCase):
for pos in (2**31-1, 2**31, 2**31+1):
with self.open(TESTFN, 'rb') as f:
f.seek(pos)
- self.assert_(f.seekable())
+ self.assertTrue(f.seekable())
def test_main():
diff --git a/Lib/test/test_list.py b/Lib/test/test_list.py
index 279afecf92..3510bd5feb 100644
--- a/Lib/test/test_list.py
+++ b/Lib/test/test_list.py
@@ -9,7 +9,7 @@ class ListTest(list_tests.CommonTest):
l0_3 = [0, 1, 2, 3]
l0_3_bis = list(l0_3)
self.assertEqual(l0_3, l0_3_bis)
- self.assert_(l0_3 is not l0_3_bis)
+ self.assertTrue(l0_3 is not l0_3_bis)
self.assertEqual(list(()), [])
self.assertEqual(list((0, 1, 2, 3)), [0, 1, 2, 3])
self.assertEqual(list(''), [])
@@ -39,11 +39,11 @@ class ListTest(list_tests.CommonTest):
def test_truth(self):
super().test_truth()
- self.assert_(not [])
- self.assert_([42])
+ self.assertTrue(not [])
+ self.assertTrue([42])
def test_identity(self):
- self.assert_([] is not [])
+ self.assertTrue([] is not [])
def test_len(self):
super().test_len()
diff --git a/Lib/test/test_logging.py b/Lib/test/test_logging.py
index 69ec49124d..72b26bb64a 100644
--- a/Lib/test/test_logging.py
+++ b/Lib/test/test_logging.py
@@ -99,7 +99,7 @@ class BaseTest(unittest.TestCase):
finally:
logging._releaseLock()
- def assert_log_lines(self, expected_values, stream=None):
+ def assertTruelog_lines(self, expected_values, stream=None):
"""Match the collected log lines against the regular expression
self.expected_log_pat, and compare the extracted group values to
the expected_values list of tuples."""
@@ -165,7 +165,7 @@ class BuiltinLevelsTest(BaseTest):
INF.debug(m())
- self.assert_log_lines([
+ self.assertTruelog_lines([
('ERR', 'CRITICAL', '1'),
('ERR', 'ERROR', '2'),
('INF', 'CRITICAL', '3'),
@@ -197,7 +197,7 @@ class BuiltinLevelsTest(BaseTest):
INF_ERR.info(m())
INF_ERR.debug(m())
- self.assert_log_lines([
+ self.assertTruelog_lines([
('INF.ERR', 'CRITICAL', '1'),
('INF.ERR', 'ERROR', '2'),
])
@@ -228,7 +228,7 @@ class BuiltinLevelsTest(BaseTest):
INF_ERR_UNDEF.info(m())
INF_ERR_UNDEF.debug(m())
- self.assert_log_lines([
+ self.assertTruelog_lines([
('INF.UNDEF', 'CRITICAL', '1'),
('INF.UNDEF', 'ERROR', '2'),
('INF.UNDEF', 'WARNING', '3'),
@@ -256,7 +256,7 @@ class BuiltinLevelsTest(BaseTest):
GRANDCHILD.debug(m())
CHILD.debug(m())
- self.assert_log_lines([
+ self.assertTruelog_lines([
('INF.BADPARENT.UNDEF', 'CRITICAL', '1'),
('INF.BADPARENT.UNDEF', 'INFO', '2'),
('INF.BADPARENT', 'CRITICAL', '3'),
@@ -285,7 +285,7 @@ class BasicFilterTest(BaseTest):
spam_eggs_fish.info(self.next_message()) # Good.
spam_bakedbeans.info(self.next_message())
- self.assert_log_lines([
+ self.assertTruelog_lines([
('spam.eggs', 'INFO', '2'),
('spam.eggs.fish', 'INFO', '3'),
])
@@ -367,7 +367,7 @@ class CustomLevelsAndFiltersTest(BaseTest):
self.root_logger.setLevel(VERBOSE)
# Levels >= 'Verbose' are good.
self.log_at_all_levels(self.root_logger)
- self.assert_log_lines([
+ self.assertTruelog_lines([
('Verbose', '5'),
('Sociable', '6'),
('Effusive', '7'),
@@ -382,7 +382,7 @@ class CustomLevelsAndFiltersTest(BaseTest):
try:
# Levels >= 'Sociable' are good.
self.log_at_all_levels(self.root_logger)
- self.assert_log_lines([
+ self.assertTruelog_lines([
('Sociable', '6'),
('Effusive', '7'),
('Terse', '8'),
@@ -413,12 +413,12 @@ class CustomLevelsAndFiltersTest(BaseTest):
('Taciturn', '9'),
('Silent', '10'),
]
- self.assert_log_lines(first_lines)
+ self.assertTruelog_lines(first_lines)
specific_filter = VerySpecificFilter()
self.root_logger.addFilter(specific_filter)
self.log_at_all_levels(self.root_logger)
- self.assert_log_lines(first_lines + [
+ self.assertTruelog_lines(first_lines + [
# Not only 'Garrulous' is still missing, but also 'Sociable'
# and 'Taciturn'
('Boring', '11'),
@@ -458,9 +458,9 @@ class MemoryHandlerTest(BaseTest):
# The memory handler flushes to its target handler based on specific
# criteria (message count and message level).
self.mem_logger.debug(self.next_message())
- self.assert_log_lines([])
+ self.assertTruelog_lines([])
self.mem_logger.info(self.next_message())
- self.assert_log_lines([])
+ self.assertTruelog_lines([])
# This will flush because the level is >= logging.WARNING
self.mem_logger.warn(self.next_message())
lines = [
@@ -468,19 +468,19 @@ class MemoryHandlerTest(BaseTest):
('INFO', '2'),
('WARNING', '3'),
]
- self.assert_log_lines(lines)
+ self.assertTruelog_lines(lines)
for n in (4, 14):
for i in range(9):
self.mem_logger.debug(self.next_message())
- self.assert_log_lines(lines)
+ self.assertTruelog_lines(lines)
# This will flush because it's the 10th message since the last
# flush.
self.mem_logger.debug(self.next_message())
lines = lines + [('DEBUG', str(i)) for i in range(n, n + 10)]
- self.assert_log_lines(lines)
+ self.assertTruelog_lines(lines)
self.mem_logger.debug(self.next_message())
- self.assert_log_lines(lines)
+ self.assertTruelog_lines(lines)
class ExceptionFormatter(logging.Formatter):
@@ -650,11 +650,11 @@ class ConfigFileTest(BaseTest):
logger.info(self.next_message())
# Outputs a message
logger.error(self.next_message())
- self.assert_log_lines([
+ self.assertTruelog_lines([
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
- self.assert_log_lines([])
+ self.assertTruelog_lines([])
def test_config1_ok(self, config=config1):
# A config file defining a sub-parser as well.
@@ -664,12 +664,12 @@ class ConfigFileTest(BaseTest):
# Both will output a message
logger.info(self.next_message())
logger.error(self.next_message())
- self.assert_log_lines([
+ self.assertTruelog_lines([
('INFO', '1'),
('ERROR', '2'),
], stream=output)
# Original logger output is empty.
- self.assert_log_lines([])
+ self.assertTruelog_lines([])
def test_config2_failure(self):
# A simple config file which overrides the default settings.
@@ -692,7 +692,7 @@ class ConfigFileTest(BaseTest):
self.assertEquals(output.getvalue(),
"ERROR:root:just testing\nGot a [RuntimeError]\n")
# Original logger output is empty
- self.assert_log_lines([])
+ self.assertTruelog_lines([])
def test_config5_ok(self):
self.test_config1_ok(config=self.config5)
@@ -826,7 +826,7 @@ class MemoryTest(BaseTest):
key = id(obj), repr(obj)
self._survivors[key] = weakref.ref(obj)
- def _assert_survival(self):
+ def _assertTruesurvival(self):
"""Assert that all objects watched for survival have survived."""
# Trigger cycle breaking.
gc.collect()
@@ -847,16 +847,16 @@ class MemoryTest(BaseTest):
foo.setLevel(logging.DEBUG)
self.root_logger.debug(self.next_message())
foo.debug(self.next_message())
- self.assert_log_lines([
+ self.assertTruelog_lines([
('foo', 'DEBUG', '2'),
])
del foo
# foo has survived.
- self._assert_survival()
+ self._assertTruesurvival()
# foo has retained its settings.
bar = logging.getLogger("foo")
bar.debug(self.next_message())
- self.assert_log_lines([
+ self.assertTruelog_lines([
('foo', 'DEBUG', '2'),
('foo', 'DEBUG', '3'),
])
@@ -881,7 +881,7 @@ class EncodingTest(BaseTest):
# check we wrote exactly those bytes, ignoring trailing \n etc
f = open(fn, encoding="utf8")
try:
- self.failUnlessEqual(f.read().rstrip(), data)
+ self.assertEqual(f.read().rstrip(), data)
finally:
f.close()
finally:
diff --git a/Lib/test/test_long.py b/Lib/test/test_long.py
index 53d3e6b9b1..1b5e6d4c9b 100644
--- a/Lib/test/test_long.py
+++ b/Lib/test/test_long.py
@@ -65,7 +65,7 @@ class LongTest(unittest.TestCase):
# The sign of the number is also random.
def getran(self, ndigits):
- self.assert_(ndigits > 0)
+ self.assertTrue(ndigits > 0)
nbits_hi = ndigits * SHIFT
nbits_lo = nbits_hi - SHIFT + 1
answer = 0
@@ -74,13 +74,13 @@ class LongTest(unittest.TestCase):
while nbits < nbits_lo:
bits = (r >> 1) + 1
bits = min(bits, nbits_hi - nbits)
- self.assert_(1 <= bits <= SHIFT)
+ self.assertTrue(1 <= bits <= SHIFT)
nbits = nbits + bits
answer = answer << bits
if r & 1:
answer = answer | ((1 << bits) - 1)
r = int(random.random() * (SHIFT * 2))
- self.assert_(nbits_lo <= nbits <= nbits_hi)
+ self.assertTrue(nbits_lo <= nbits <= nbits_hi)
if random.random() < 0.5:
answer = -answer
return answer
@@ -106,9 +106,9 @@ class LongTest(unittest.TestCase):
eq(r, r2, Frm("divmod returns different mod than %% for %r and %r", x, y))
eq(x, q*y + r, Frm("x != q*y + r after divmod on x=%r, y=%r", x, y))
if y > 0:
- self.assert_(0 <= r < y, Frm("bad mod from divmod on %r and %r", x, y))
+ self.assertTrue(0 <= r < y, Frm("bad mod from divmod on %r and %r", x, y))
else:
- self.assert_(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y))
+ self.assertTrue(y < r <= 0, Frm("bad mod from divmod on %r and %r", x, y))
def test_division(self):
digits = list(range(1, MAXDIGITS+1)) + list(range(KARATSUBA_CUTOFF,
@@ -538,7 +538,7 @@ class LongTest(unittest.TestCase):
y = int(x)
except OverflowError:
self.fail("int(long(sys.maxsize) + 1) mustn't overflow")
- self.assert_(isinstance(y, int),
+ self.assertTrue(isinstance(y, int),
"int(long(sys.maxsize) + 1) should have returned long")
x = hugeneg_aslong - 1
@@ -546,14 +546,14 @@ class LongTest(unittest.TestCase):
y = int(x)
except OverflowError:
self.fail("int(long(-sys.maxsize-1) - 1) mustn't overflow")
- self.assert_(isinstance(y, int),
+ self.assertTrue(isinstance(y, int),
"int(long(-sys.maxsize-1) - 1) should have returned long")
class long2(int):
pass
x = long2(1<<100)
y = int(x)
- self.assert_(type(y) is int,
+ self.assertTrue(type(y) is int,
"overflowing int conversion must return long not long subtype")
# ----------------------------------- tests of auto int->long conversion
@@ -958,7 +958,7 @@ class LongTest(unittest.TestCase):
self.assertEqual(k, len(bin(x).lstrip('-0b')))
# Behaviour as specified in the docs
if x != 0:
- self.assert_(2**(k-1) <= abs(x) < 2**k)
+ self.assertTrue(2**(k-1) <= abs(x) < 2**k)
else:
self.assertEqual(k, 0)
# Alternative definition: x.bit_length() == 1 + floor(log_2(x))
@@ -995,7 +995,7 @@ class LongTest(unittest.TestCase):
got = round(k+offset, -1)
expected = v+offset
self.assertEqual(got, expected)
- self.assert_(type(got) is int)
+ self.assertTrue(type(got) is int)
# larger second argument
self.assertEqual(round(-150, -2), -200)
@@ -1034,7 +1034,7 @@ class LongTest(unittest.TestCase):
got = round(10**k + 324678, -3)
expect = 10**k + 325000
self.assertEqual(got, expect)
- self.assert_(type(got) is int)
+ self.assertTrue(type(got) is int)
# nonnegative second argument: round(x, n) should just return x
for n in range(5):
@@ -1042,7 +1042,7 @@ class LongTest(unittest.TestCase):
x = random.randrange(-10000, 10000)
got = round(x, n)
self.assertEqual(got, x)
- self.assert_(type(got) is int)
+ self.assertTrue(type(got) is int)
for huge_n in 2**31-1, 2**31, 2**63-1, 2**63, 2**100, 10**100:
self.assertEqual(round(8979323, huge_n), 8979323)
@@ -1051,7 +1051,7 @@ class LongTest(unittest.TestCase):
x = random.randrange(-10000, 10000)
got = round(x)
self.assertEqual(got, x)
- self.assert_(type(got) is int)
+ self.assertTrue(type(got) is int)
# bad second argument
bad_exponents = ('brian', 2.0, 0j, None)
diff --git a/Lib/test/test_macpath.py b/Lib/test/test_macpath.py
index 368d8f5c57..e13865d80c 100644
--- a/Lib/test/test_macpath.py
+++ b/Lib/test/test_macpath.py
@@ -10,37 +10,37 @@ class MacPathTestCase(unittest.TestCase):
def test_isabs(self):
isabs = macpath.isabs
- self.assert_(isabs("xx:yy"))
- self.assert_(isabs("xx:yy:"))
- self.assert_(isabs("xx:"))
- self.failIf(isabs("foo"))
- self.failIf(isabs(":foo"))
- self.failIf(isabs(":foo:bar"))
- self.failIf(isabs(":foo:bar:"))
-
- self.assert_(isabs(b"xx:yy"))
- self.assert_(isabs(b"xx:yy:"))
- self.assert_(isabs(b"xx:"))
- self.failIf(isabs(b"foo"))
- self.failIf(isabs(b":foo"))
- self.failIf(isabs(b":foo:bar"))
- self.failIf(isabs(b":foo:bar:"))
+ self.assertTrue(isabs("xx:yy"))
+ self.assertTrue(isabs("xx:yy:"))
+ self.assertTrue(isabs("xx:"))
+ self.assertFalse(isabs("foo"))
+ self.assertFalse(isabs(":foo"))
+ self.assertFalse(isabs(":foo:bar"))
+ self.assertFalse(isabs(":foo:bar:"))
+
+ self.assertTrue(isabs(b"xx:yy"))
+ self.assertTrue(isabs(b"xx:yy:"))
+ self.assertTrue(isabs(b"xx:"))
+ self.assertFalse(isabs(b"foo"))
+ self.assertFalse(isabs(b":foo"))
+ self.assertFalse(isabs(b":foo:bar"))
+ self.assertFalse(isabs(b":foo:bar:"))
def test_commonprefix(self):
commonprefix = macpath.commonprefix
- self.assert_(commonprefix(["home:swenson:spam", "home:swen:spam"])
+ self.assertTrue(commonprefix(["home:swenson:spam", "home:swen:spam"])
== "home:swen")
- self.assert_(commonprefix([":home:swen:spam", ":home:swen:eggs"])
+ self.assertTrue(commonprefix([":home:swen:spam", ":home:swen:eggs"])
== ":home:swen:")
- self.assert_(commonprefix([":home:swen:spam", ":home:swen:spam"])
+ self.assertTrue(commonprefix([":home:swen:spam", ":home:swen:spam"])
== ":home:swen:spam")
- self.assert_(commonprefix([b"home:swenson:spam", b"home:swen:spam"])
+ self.assertTrue(commonprefix([b"home:swenson:spam", b"home:swen:spam"])
== b"home:swen")
- self.assert_(commonprefix([b":home:swen:spam", b":home:swen:eggs"])
+ self.assertTrue(commonprefix([b":home:swen:spam", b":home:swen:eggs"])
== b":home:swen:")
- self.assert_(commonprefix([b":home:swen:spam", b":home:swen:spam"])
+ self.assertTrue(commonprefix([b":home:swen:spam", b":home:swen:spam"])
== b":home:swen:spam")
def test_split(self):
diff --git a/Lib/test/test_mailbox.py b/Lib/test/test_mailbox.py
index 655b639115..8994340131 100644
--- a/Lib/test/test_mailbox.py
+++ b/Lib/test/test_mailbox.py
@@ -21,16 +21,16 @@ class TestBase(unittest.TestCase):
def _check_sample(self, msg):
# Inspect a mailbox.Message representation of the sample message
- self.assert_(isinstance(msg, email.message.Message))
- self.assert_(isinstance(msg, mailbox.Message))
+ self.assertTrue(isinstance(msg, email.message.Message))
+ self.assertTrue(isinstance(msg, mailbox.Message))
for key, value in _sample_headers.items():
- self.assert_(value in msg.get_all(key))
- self.assert_(msg.is_multipart())
+ self.assertTrue(value in msg.get_all(key))
+ self.assertTrue(msg.is_multipart())
self.assertEqual(len(msg.get_payload()), len(_sample_payloads))
for i, payload in enumerate(_sample_payloads):
part = msg.get_payload(i)
- self.assert_(isinstance(part, email.message.Message))
- self.assert_(not isinstance(part, mailbox.Message))
+ self.assertTrue(isinstance(part, email.message.Message))
+ self.assertTrue(not isinstance(part, mailbox.Message))
self.assertEqual(part.get_payload(), payload)
def _delete_recursively(self, target):
@@ -92,7 +92,7 @@ class TestMailbox(TestBase):
self.assertEqual(len(self._box), 2)
method(key0)
l = len(self._box)
- self.assert_(l == 1, "actual l: %s" % l)
+ self.assertTrue(l == 1, "actual l: %s" % l)
self.assertRaises(KeyError, lambda: self._box[key0])
self.assertRaises(KeyError, lambda: method(key0))
self.assertEqual(self._box.get_string(key1), self._template % 1)
@@ -100,7 +100,7 @@ class TestMailbox(TestBase):
self.assertEqual(len(self._box), 2)
method(key2)
l = len(self._box)
- self.assert_(l == 1, "actual l: %s" % l)
+ self.assertTrue(l == 1, "actual l: %s" % l)
self.assertRaises(KeyError, lambda: self._box[key2])
self.assertRaises(KeyError, lambda: method(key2))
self.assertEqual(self._box.get_string(key1), self._template % 1)
@@ -127,8 +127,8 @@ class TestMailbox(TestBase):
msg = self._box.get(key0)
self.assertEqual(msg['from'], 'foo')
self.assertEqual(msg.get_payload(), '0')
- self.assert_(self._box.get('foo') is None)
- self.assert_(self._box.get('foo', False) is False)
+ self.assertTrue(self._box.get('foo') is None)
+ self.assertTrue(self._box.get('foo', False) is False)
self._box.close()
self._box = self._factory(self._path)
key1 = self._box.add(self._template % 1)
@@ -151,7 +151,7 @@ class TestMailbox(TestBase):
key0 = self._box.add(self._template % 0)
key1 = self._box.add(_sample_message)
msg0 = self._box.get_message(key0)
- self.assert_(isinstance(msg0, mailbox.Message))
+ self.assertTrue(isinstance(msg0, mailbox.Message))
self.assertEqual(msg0['from'], 'foo')
self.assertEqual(msg0.get_payload(), '0')
self._check_sample(self._box.get_message(key1))
@@ -228,29 +228,29 @@ class TestMailbox(TestBase):
count = 0
for value in returned_values:
self.assertEqual(value['from'], 'foo')
- self.assert_(int(value.get_payload()) < repetitions)
+ self.assertTrue(int(value.get_payload()) < repetitions)
count += 1
self.assertEqual(len(values), count)
def test_contains(self):
# Check existence of keys using __contains__()
method = self._box.__contains__
- self.assert_(not method('foo'))
+ self.assertTrue(not method('foo'))
key0 = self._box.add(self._template % 0)
- self.assert_(method(key0))
- self.assert_(not method('foo'))
+ self.assertTrue(method(key0))
+ self.assertTrue(not method('foo'))
key1 = self._box.add(self._template % 1)
- self.assert_(method(key1))
- self.assert_(method(key0))
- self.assert_(not method('foo'))
+ self.assertTrue(method(key1))
+ self.assertTrue(method(key0))
+ self.assertTrue(not method('foo'))
self._box.remove(key0)
- self.assert_(not method(key0))
- self.assert_(method(key1))
- self.assert_(not method('foo'))
+ self.assertTrue(not method(key0))
+ self.assertTrue(method(key1))
+ self.assertTrue(not method('foo'))
self._box.remove(key1)
- self.assert_(not method(key1))
- self.assert_(not method(key0))
- self.assert_(not method('foo'))
+ self.assertTrue(not method(key1))
+ self.assertTrue(not method(key0))
+ self.assertTrue(not method('foo'))
def test_len(self, repetitions=10):
# Get message count
@@ -297,7 +297,7 @@ class TestMailbox(TestBase):
for i in range(iterations):
self._box.add(self._template % i)
for i, key in enumerate(keys):
- self.assert_(self._box.get_string(key) == self._template % i)
+ self.assertTrue(self._box.get_string(key) == self._template % i)
self._box.clear()
self.assertEqual(len(self._box), 0)
for i, key in enumerate(keys):
@@ -306,19 +306,19 @@ class TestMailbox(TestBase):
def test_pop(self):
# Get and remove a message using pop()
key0 = self._box.add(self._template % 0)
- self.assert_(key0 in self._box)
+ self.assertTrue(key0 in self._box)
key1 = self._box.add(self._template % 1)
- self.assert_(key1 in self._box)
+ self.assertTrue(key1 in self._box)
self.assertEqual(self._box.pop(key0).get_payload(), '0')
- self.assert_(key0 not in self._box)
- self.assert_(key1 in self._box)
+ self.assertTrue(key0 not in self._box)
+ self.assertTrue(key1 in self._box)
key2 = self._box.add(self._template % 2)
- self.assert_(key2 in self._box)
+ self.assertTrue(key2 in self._box)
self.assertEqual(self._box.pop(key2).get_payload(), '2')
- self.assert_(key2 not in self._box)
- self.assert_(key1 in self._box)
+ self.assertTrue(key2 not in self._box)
+ self.assertTrue(key1 in self._box)
self.assertEqual(self._box.pop(key1).get_payload(), '1')
- self.assert_(key1 not in self._box)
+ self.assertTrue(key1 not in self._box)
self.assertEqual(len(self._box), 0)
def test_popitem(self, iterations=10):
@@ -329,8 +329,8 @@ class TestMailbox(TestBase):
seen = []
for i in range(10):
key, msg = self._box.popitem()
- self.assert_(key in keys)
- self.assert_(key not in seen)
+ self.assertTrue(key in keys)
+ self.assertTrue(key not in seen)
seen.append(key)
self.assertEqual(int(msg.get_payload()), keys.index(key))
self.assertEqual(len(self._box), 0)
@@ -377,11 +377,11 @@ class TestMailbox(TestBase):
def test_lock_unlock(self):
# Lock and unlock the mailbox
- self.assert_(not os.path.exists(self._get_lock_path()))
+ self.assertTrue(not os.path.exists(self._get_lock_path()))
self._box.lock()
- self.assert_(os.path.exists(self._get_lock_path()))
+ self.assertTrue(os.path.exists(self._get_lock_path()))
self._box.unlock()
- self.assert_(not os.path.exists(self._get_lock_path()))
+ self.assertTrue(not os.path.exists(self._get_lock_path()))
def test_close(self):
# Close mailbox and flush changes to disk
@@ -400,7 +400,7 @@ class TestMailbox(TestBase):
keys = self._box.keys()
self.assertEqual(len(keys), 3)
for key in keys:
- self.assert_(self._box.get_string(key) in contents)
+ self.assertTrue(self._box.get_string(key) in contents)
oldbox.close()
def test_dump_message(self):
@@ -469,7 +469,7 @@ class TestMaildir(TestMailbox):
msg.set_subdir('cur')
msg.set_info('foo')
key = self._box.add(msg)
- self.assert_(os.path.exists(os.path.join(self._path, 'cur', '%s%sfoo' %
+ self.assertTrue(os.path.exists(os.path.join(self._path, 'cur', '%s%sfoo' %
(key, self._box.colon))))
def test_get_MM(self):
@@ -479,7 +479,7 @@ class TestMaildir(TestMailbox):
msg.set_flags('RF')
key = self._box.add(msg)
msg_returned = self._box.get_message(key)
- self.assert_(isinstance(msg_returned, mailbox.MaildirMessage))
+ self.assertTrue(isinstance(msg_returned, mailbox.MaildirMessage))
self.assertEqual(msg_returned.get_subdir(), 'cur')
self.assertEqual(msg_returned.get_flags(), 'FR')
@@ -519,7 +519,7 @@ class TestMaildir(TestMailbox):
box = mailbox.Maildir(self._path, factory=FakeMessage)
box.colon = self._box.colon
msg2 = box.get_message(key)
- self.assert_(isinstance(msg2, FakeMessage))
+ self.assertTrue(isinstance(msg2, FakeMessage))
def test_initialize_new(self):
# Initialize a non-existent mailbox
@@ -545,7 +545,7 @@ class TestMaildir(TestMailbox):
for subdir in '', 'tmp', 'new', 'cur':
path = os.path.join(self._path, subdir)
mode = os.stat(path)[stat.ST_MODE]
- self.assert_(stat.S_ISDIR(mode), "Not a directory: '%s'" % path)
+ self.assertTrue(stat.S_ISDIR(mode), "Not a directory: '%s'" % path)
def test_list_folders(self):
# List folders
@@ -561,7 +561,7 @@ class TestMaildir(TestMailbox):
self._box.add_folder('foo.bar')
folder0 = self._box.get_folder('foo.bar')
folder0.add(self._template % 'bar')
- self.assert_(os.path.isdir(os.path.join(self._path, '.foo.bar')))
+ self.assertTrue(os.path.isdir(os.path.join(self._path, '.foo.bar')))
folder1 = self._box.get_folder('foo.bar')
self.assertEqual(folder1.get_string(folder1.keys()[0]),
self._template % 'bar')
@@ -571,7 +571,7 @@ class TestMaildir(TestMailbox):
self._box.add_folder('one')
self._box.add_folder('two')
self.assertEqual(len(self._box.list_folders()), 2)
- self.assert_(set(self._box.list_folders()) == set(('one', 'two')))
+ self.assertTrue(set(self._box.list_folders()) == set(('one', 'two')))
self._box.remove_folder('one')
self.assertEqual(len(self._box.list_folders()), 1)
self.assertEqual(set(self._box.list_folders()), set(('two',)))
@@ -596,14 +596,14 @@ class TestMaildir(TestMailbox):
f.write("@")
f.close()
self._box.clean()
- self.assert_(os.path.exists(foo_path))
- self.assert_(os.path.exists(bar_path))
+ self.assertTrue(os.path.exists(foo_path))
+ self.assertTrue(os.path.exists(bar_path))
foo_stat = os.stat(foo_path)
os.utime(foo_path, (time.time() - 129600 - 2,
foo_stat.st_mtime))
self._box.clean()
- self.assert_(not os.path.exists(foo_path))
- self.assert_(os.path.exists(bar_path))
+ self.assertTrue(not os.path.exists(foo_path))
+ self.assertTrue(os.path.exists(bar_path))
def test_create_tmp(self, repetitions=10):
# Create files in tmp directory
@@ -623,13 +623,13 @@ class TestMaildir(TestMailbox):
"tmp")),
"File in wrong location: '%s'" % head)
match = pattern.match(tail)
- self.assert_(match is not None, "Invalid file name: '%s'" % tail)
+ self.assertTrue(match is not None, "Invalid file name: '%s'" % tail)
groups = match.groups()
if previous_groups is not None:
- self.assert_(int(groups[0] >= previous_groups[0]),
+ self.assertTrue(int(groups[0] >= previous_groups[0]),
"Non-monotonic seconds: '%s' before '%s'" %
(previous_groups[0], groups[0]))
- self.assert_(int(groups[1] >= previous_groups[1]) or
+ self.assertTrue(int(groups[1] >= previous_groups[1]) or
groups[0] != groups[1],
"Non-monotonic milliseconds: '%s' before '%s'" %
(previous_groups[1], groups[1]))
@@ -691,10 +691,10 @@ class TestMaildir(TestMailbox):
return None
box = self._factory(self._path, factory=dummy_factory)
folder = box.add_folder('folder1')
- self.assert_(folder._factory is dummy_factory)
+ self.assertTrue(folder._factory is dummy_factory)
folder1_alias = box.get_folder('folder1')
- self.assert_(folder1_alias._factory is dummy_factory)
+ self.assertTrue(folder1_alias._factory is dummy_factory)
def test_directory_in_folder (self):
# Test that mailboxes still work if there's a stray extra directory
@@ -721,7 +721,7 @@ class TestMaildir(TestMailbox):
os.umask(orig_umask)
path = os.path.join(self._path, self._box._lookup(key))
mode = os.stat(path).st_mode
- self.assert_(mode & 0o111 == 0)
+ self.assertTrue(mode & 0o111 == 0)
def test_folder_file_perms(self):
# From bug #3228, we want to verify that the file created inside a Maildir
@@ -802,7 +802,7 @@ class _TestMboxMMDF(TestMailbox):
self._box = self._factory(self._path)
self.assertEqual(len(self._box), 3)
for key in self._box.keys():
- self.assert_(self._box.get_string(key) in values)
+ self.assertTrue(self._box.get_string(key) in values)
self._box.close()
self.assertEqual(mtime, os.path.getmtime(self._path))
@@ -859,7 +859,7 @@ class _TestMboxMMDF(TestMailbox):
self._box.lock()
key2 = self._box.add(msg)
self._box.flush()
- self.assert_(self._box._locked)
+ self.assertTrue(self._box._locked)
self._box.close()
@@ -913,15 +913,15 @@ class TestMH(TestMailbox):
new_folder = self._box.add_folder('foo.bar')
folder0 = self._box.get_folder('foo.bar')
folder0.add(self._template % 'bar')
- self.assert_(os.path.isdir(os.path.join(self._path, 'foo.bar')))
+ self.assertTrue(os.path.isdir(os.path.join(self._path, 'foo.bar')))
folder1 = self._box.get_folder('foo.bar')
self.assertEqual(folder1.get_string(folder1.keys()[0]),
self._template % 'bar')
# Test for bug #1569790: verify that folders returned by .get_folder()
# use the same factory function.
- self.assert_(new_folder._factory is self._box._factory)
- self.assert_(folder0._factory is self._box._factory)
+ self.assertTrue(new_folder._factory is self._box._factory)
+ self.assertTrue(folder0._factory is self._box._factory)
def test_add_and_remove_folders(self):
# Delete folders
@@ -990,7 +990,7 @@ class TestMH(TestMailbox):
{'foo':[key0,key1,key3], 'unseen':[key0], 'bar':[key3],
'replied':[key3]})
self._box.pack()
- self.assert_(self._box.keys() == [1, 2, 3])
+ self.assertTrue(self._box.keys() == [1, 2, 3])
key0 = key0
key1 = key0 + 1
key2 = key1 + 1
@@ -1082,11 +1082,11 @@ class TestMessage(TestBase):
# Initialize without arguments
msg = self._factory()
self._post_initialize_hook(msg)
- self.assert_(isinstance(msg, email.message.Message))
- self.assert_(isinstance(msg, mailbox.Message))
- self.assert_(isinstance(msg, self._factory))
+ self.assertTrue(isinstance(msg, email.message.Message))
+ self.assertTrue(isinstance(msg, mailbox.Message))
+ self.assertTrue(isinstance(msg, self._factory))
self.assertEqual(msg.keys(), [])
- self.assert_(not msg.is_multipart())
+ self.assertTrue(not msg.is_multipart())
self.assertEqual(msg.get_payload(), None)
def test_initialize_incorrectly(self):
@@ -1159,7 +1159,7 @@ class TestMaildirMessage(TestMessage):
def test_date(self):
# Use get_date() and set_date()
msg = mailbox.MaildirMessage(_sample_message)
- self.assert_(abs(msg.get_date() - time.time()) < 60)
+ self.assertTrue(abs(msg.get_date() - time.time()) < 60)
msg.set_date(0.0)
self.assertEqual(msg.get_date(), 0.0)
@@ -1234,7 +1234,7 @@ class _TestMboxMMDFMessage(TestMessage):
# Check contents of "From " line
if sender is None:
sender = "MAILER-DAEMON"
- self.assert_(re.match(sender + r" \w{3} \w{3} [\d ]\d [\d ]\d:\d{2}:"
+ self.assertTrue(re.match(sender + r" \w{3} \w{3} [\d ]\d [\d ]\d:\d{2}:"
r"\d{2} \d{4}", msg.get_from()) is not None)
@@ -1309,19 +1309,19 @@ class TestBabylMessage(TestMessage):
msg = mailbox.BabylMessage(_sample_message)
visible = msg.get_visible()
self.assertEqual(visible.keys(), [])
- self.assert_(visible.get_payload() is None)
+ self.assertTrue(visible.get_payload() is None)
visible['User-Agent'] = 'FooBar 1.0'
visible['X-Whatever'] = 'Blah'
self.assertEqual(msg.get_visible().keys(), [])
msg.set_visible(visible)
visible = msg.get_visible()
- self.assert_(visible.keys() == ['User-Agent', 'X-Whatever'])
- self.assert_(visible['User-Agent'] == 'FooBar 1.0')
+ self.assertTrue(visible.keys() == ['User-Agent', 'X-Whatever'])
+ self.assertTrue(visible['User-Agent'] == 'FooBar 1.0')
self.assertEqual(visible['X-Whatever'], 'Blah')
- self.assert_(visible.get_payload() is None)
+ self.assertTrue(visible.get_payload() is None)
msg.update_visible()
self.assertEqual(visible.keys(), ['User-Agent', 'X-Whatever'])
- self.assert_(visible.get_payload() is None)
+ self.assertTrue(visible.get_payload() is None)
visible = msg.get_visible()
self.assertEqual(visible.keys(), ['User-Agent', 'Date', 'From', 'To',
'Subject'])
@@ -1423,7 +1423,7 @@ class TestMessageConversion(TestBase):
msg_mboxMMDF.set_flags(setting)
msg = mailbox.MaildirMessage(msg_mboxMMDF)
self.assertEqual(msg.get_flags(), result)
- self.assert_(msg.get_date() == 0.0, msg.get_date())
+ self.assertTrue(msg.get_date() == 0.0, msg.get_date())
msg_mboxMMDF.set_flags('O')
self.assertEqual(mailbox.MaildirMessage(msg_mboxMMDF).get_subdir(),
'cur')
@@ -1655,7 +1655,7 @@ class TestProxyFileBase(TestBase):
proxy.seek(2, 0)
self.assertEqual(proxy.read(), b'o' + linesep + b'bar' + linesep)
proxy.seek(100)
- self.failIf(proxy.read())
+ self.assertFalse(proxy.read())
def _test_close(self, proxy):
# Close a file
@@ -1820,36 +1820,36 @@ class MaildirTestCase(unittest.TestCase):
# Test for regression on bug #117490:
# Make sure the boxes attribute actually gets set.
self.mbox = mailbox.Maildir(support.TESTFN)
- #self.assert_(hasattr(self.mbox, "boxes"))
+ #self.assertTrue(hasattr(self.mbox, "boxes"))
#self.assertEqual(len(self.mbox.boxes), 0)
- self.assert_(self.mbox.next() is None)
- self.assert_(self.mbox.next() is None)
+ self.assertTrue(self.mbox.next() is None)
+ self.assertTrue(self.mbox.next() is None)
def test_nonempty_maildir_cur(self):
self.createMessage("cur")
self.mbox = mailbox.Maildir(support.TESTFN)
#self.assertEqual(len(self.mbox.boxes), 1)
- self.assert_(self.mbox.next() is not None)
- self.assert_(self.mbox.next() is None)
- self.assert_(self.mbox.next() is None)
+ self.assertTrue(self.mbox.next() is not None)
+ self.assertTrue(self.mbox.next() is None)
+ self.assertTrue(self.mbox.next() is None)
def test_nonempty_maildir_new(self):
self.createMessage("new")
self.mbox = mailbox.Maildir(support.TESTFN)
#self.assertEqual(len(self.mbox.boxes), 1)
- self.assert_(self.mbox.next() is not None)
- self.assert_(self.mbox.next() is None)
- self.assert_(self.mbox.next() is None)
+ self.assertTrue(self.mbox.next() is not None)
+ self.assertTrue(self.mbox.next() is None)
+ self.assertTrue(self.mbox.next() is None)
def test_nonempty_maildir_both(self):
self.createMessage("cur")
self.createMessage("new")
self.mbox = mailbox.Maildir(support.TESTFN)
#self.assertEqual(len(self.mbox.boxes), 2)
- self.assert_(self.mbox.next() is not None)
- self.assert_(self.mbox.next() is not None)
- self.assert_(self.mbox.next() is None)
- self.assert_(self.mbox.next() is None)
+ self.assertTrue(self.mbox.next() is not None)
+ self.assertTrue(self.mbox.next() is not None)
+ self.assertTrue(self.mbox.next() is None)
+ self.assertTrue(self.mbox.next() is None)
## End: tests from the original module (for backward compatibility).
diff --git a/Lib/test/test_math.py b/Lib/test/test_math.py
index d74f01fb70..2321a09787 100644
--- a/Lib/test/test_math.py
+++ b/Lib/test/test_math.py
@@ -72,7 +72,7 @@ class MathTests(unittest.TestCase):
self.ftest('acos(1)', math.acos(1), 0)
self.assertRaises(ValueError, math.acos, INF)
self.assertRaises(ValueError, math.acos, NINF)
- self.assert_(math.isnan(math.acos(NAN)))
+ self.assertTrue(math.isnan(math.acos(NAN)))
def testAcosh(self):
self.assertRaises(TypeError, math.acosh)
@@ -82,7 +82,7 @@ class MathTests(unittest.TestCase):
self.assertRaises(ValueError, math.acosh, -1)
self.assertEquals(math.acosh(INF), INF)
self.assertRaises(ValueError, math.acosh, NINF)
- self.assert_(math.isnan(math.acosh(NAN)))
+ self.assertTrue(math.isnan(math.acosh(NAN)))
def testAsin(self):
self.assertRaises(TypeError, math.asin)
@@ -91,7 +91,7 @@ class MathTests(unittest.TestCase):
self.ftest('asin(1)', math.asin(1), math.pi/2)
self.assertRaises(ValueError, math.asin, INF)
self.assertRaises(ValueError, math.asin, NINF)
- self.assert_(math.isnan(math.asin(NAN)))
+ self.assertTrue(math.isnan(math.asin(NAN)))
def testAsinh(self):
self.assertRaises(TypeError, math.asinh)
@@ -100,7 +100,7 @@ class MathTests(unittest.TestCase):
self.ftest('asinh(-1)', math.asinh(-1), -0.88137358701954305)
self.assertEquals(math.asinh(INF), INF)
self.assertEquals(math.asinh(NINF), NINF)
- self.assert_(math.isnan(math.asinh(NAN)))
+ self.assertTrue(math.isnan(math.asinh(NAN)))
def testAtan(self):
self.assertRaises(TypeError, math.atan)
@@ -109,7 +109,7 @@ class MathTests(unittest.TestCase):
self.ftest('atan(1)', math.atan(1), math.pi/4)
self.ftest('atan(inf)', math.atan(INF), math.pi/2)
self.ftest('atan(-inf)', math.atan(NINF), -math.pi/2)
- self.assert_(math.isnan(math.atan(NAN)))
+ self.assertTrue(math.isnan(math.atan(NAN)))
def testAtanh(self):
self.assertRaises(TypeError, math.atan)
@@ -120,7 +120,7 @@ class MathTests(unittest.TestCase):
self.assertRaises(ValueError, math.atanh, -1)
self.assertRaises(ValueError, math.atanh, INF)
self.assertRaises(ValueError, math.atanh, NINF)
- self.assert_(math.isnan(math.atanh(NAN)))
+ self.assertTrue(math.isnan(math.atanh(NAN)))
def testAtan2(self):
self.assertRaises(TypeError, math.atan2)
@@ -137,7 +137,7 @@ class MathTests(unittest.TestCase):
self.assertEqual(math.atan2(0., 0.), 0.)
self.assertEqual(math.atan2(0., 2.3), 0.)
self.assertEqual(math.atan2(0., INF), 0.)
- self.assert_(math.isnan(math.atan2(0., NAN)))
+ self.assertTrue(math.isnan(math.atan2(0., NAN)))
# math.atan2(-0, x)
self.ftest('atan2(-0., -inf)', math.atan2(-0., NINF), -math.pi)
self.ftest('atan2(-0., -2.3)', math.atan2(-0., -2.3), -math.pi)
@@ -145,7 +145,7 @@ class MathTests(unittest.TestCase):
self.assertEqual(math.atan2(-0., 0.), -0.)
self.assertEqual(math.atan2(-0., 2.3), -0.)
self.assertEqual(math.atan2(-0., INF), -0.)
- self.assert_(math.isnan(math.atan2(-0., NAN)))
+ self.assertTrue(math.isnan(math.atan2(-0., NAN)))
# math.atan2(INF, x)
self.ftest('atan2(inf, -inf)', math.atan2(INF, NINF), math.pi*3/4)
self.ftest('atan2(inf, -2.3)', math.atan2(INF, -2.3), math.pi/2)
@@ -153,7 +153,7 @@ class MathTests(unittest.TestCase):
self.ftest('atan2(inf, 0.)', math.atan2(INF, 0.0), math.pi/2)
self.ftest('atan2(inf, 2.3)', math.atan2(INF, 2.3), math.pi/2)
self.ftest('atan2(inf, inf)', math.atan2(INF, INF), math.pi/4)
- self.assert_(math.isnan(math.atan2(INF, NAN)))
+ self.assertTrue(math.isnan(math.atan2(INF, NAN)))
# math.atan2(NINF, x)
self.ftest('atan2(-inf, -inf)', math.atan2(NINF, NINF), -math.pi*3/4)
self.ftest('atan2(-inf, -2.3)', math.atan2(NINF, -2.3), -math.pi/2)
@@ -161,27 +161,27 @@ class MathTests(unittest.TestCase):
self.ftest('atan2(-inf, 0.)', math.atan2(NINF, 0.0), -math.pi/2)
self.ftest('atan2(-inf, 2.3)', math.atan2(NINF, 2.3), -math.pi/2)
self.ftest('atan2(-inf, inf)', math.atan2(NINF, INF), -math.pi/4)
- self.assert_(math.isnan(math.atan2(NINF, NAN)))
+ self.assertTrue(math.isnan(math.atan2(NINF, NAN)))
# math.atan2(+finite, x)
self.ftest('atan2(2.3, -inf)', math.atan2(2.3, NINF), math.pi)
self.ftest('atan2(2.3, -0.)', math.atan2(2.3, -0.), math.pi/2)
self.ftest('atan2(2.3, 0.)', math.atan2(2.3, 0.), math.pi/2)
self.assertEqual(math.atan2(2.3, INF), 0.)
- self.assert_(math.isnan(math.atan2(2.3, NAN)))
+ self.assertTrue(math.isnan(math.atan2(2.3, NAN)))
# math.atan2(-finite, x)
self.ftest('atan2(-2.3, -inf)', math.atan2(-2.3, NINF), -math.pi)
self.ftest('atan2(-2.3, -0.)', math.atan2(-2.3, -0.), -math.pi/2)
self.ftest('atan2(-2.3, 0.)', math.atan2(-2.3, 0.), -math.pi/2)
self.assertEqual(math.atan2(-2.3, INF), -0.)
- self.assert_(math.isnan(math.atan2(-2.3, NAN)))
+ self.assertTrue(math.isnan(math.atan2(-2.3, NAN)))
# math.atan2(NAN, x)
- self.assert_(math.isnan(math.atan2(NAN, NINF)))
- self.assert_(math.isnan(math.atan2(NAN, -2.3)))
- self.assert_(math.isnan(math.atan2(NAN, -0.)))
- self.assert_(math.isnan(math.atan2(NAN, 0.)))
- self.assert_(math.isnan(math.atan2(NAN, 2.3)))
- self.assert_(math.isnan(math.atan2(NAN, INF)))
- self.assert_(math.isnan(math.atan2(NAN, NAN)))
+ self.assertTrue(math.isnan(math.atan2(NAN, NINF)))
+ self.assertTrue(math.isnan(math.atan2(NAN, -2.3)))
+ self.assertTrue(math.isnan(math.atan2(NAN, -0.)))
+ self.assertTrue(math.isnan(math.atan2(NAN, 0.)))
+ self.assertTrue(math.isnan(math.atan2(NAN, 2.3)))
+ self.assertTrue(math.isnan(math.atan2(NAN, INF)))
+ self.assertTrue(math.isnan(math.atan2(NAN, NAN)))
def testCeil(self):
self.assertRaises(TypeError, math.ceil)
@@ -194,7 +194,7 @@ class MathTests(unittest.TestCase):
self.ftest('ceil(-1.5)', math.ceil(-1.5), -1)
#self.assertEquals(math.ceil(INF), INF)
#self.assertEquals(math.ceil(NINF), NINF)
- #self.assert_(math.isnan(math.ceil(NAN)))
+ #self.assertTrue(math.isnan(math.ceil(NAN)))
class TestCeil:
def __ceil__(self):
@@ -226,14 +226,14 @@ class MathTests(unittest.TestCase):
self.assertEquals(copysign(INF, NINF), NINF)
self.assertEquals(copysign(NINF, INF), INF)
self.assertEquals(copysign(NINF, NINF), NINF)
- self.assert_(math.isnan(copysign(NAN, 1.)))
- self.assert_(math.isnan(copysign(NAN, INF)))
- self.assert_(math.isnan(copysign(NAN, NINF)))
- self.assert_(math.isnan(copysign(NAN, NAN)))
+ self.assertTrue(math.isnan(copysign(NAN, 1.)))
+ self.assertTrue(math.isnan(copysign(NAN, INF)))
+ self.assertTrue(math.isnan(copysign(NAN, NINF)))
+ self.assertTrue(math.isnan(copysign(NAN, NAN)))
# copysign(INF, NAN) may be INF or it may be NINF, since
# we don't know whether the sign bit of NAN is set on any
# given platform.
- self.assert_(math.isinf(copysign(INF, NAN)))
+ self.assertTrue(math.isinf(copysign(INF, NAN)))
# similarly, copysign(2., NAN) could be 2. or -2.
self.assertEquals(abs(copysign(2., NAN)), 2.)
@@ -244,12 +244,12 @@ class MathTests(unittest.TestCase):
self.ftest('cos(pi/2)', math.cos(math.pi/2), 0)
self.ftest('cos(pi)', math.cos(math.pi), -1)
try:
- self.assert_(math.isnan(math.cos(INF)))
- self.assert_(math.isnan(math.cos(NINF)))
+ self.assertTrue(math.isnan(math.cos(INF)))
+ self.assertTrue(math.isnan(math.cos(NINF)))
except ValueError:
self.assertRaises(ValueError, math.cos, INF)
self.assertRaises(ValueError, math.cos, NINF)
- self.assert_(math.isnan(math.cos(NAN)))
+ self.assertTrue(math.isnan(math.cos(NAN)))
def testCosh(self):
self.assertRaises(TypeError, math.cosh)
@@ -257,7 +257,7 @@ class MathTests(unittest.TestCase):
self.ftest('cosh(2)-2*cosh(1)**2', math.cosh(2)-2*math.cosh(1)**2, -1) # Thanks to Lambert
self.assertEquals(math.cosh(INF), INF)
self.assertEquals(math.cosh(NINF), INF)
- self.assert_(math.isnan(math.cosh(NAN)))
+ self.assertTrue(math.isnan(math.cosh(NAN)))
def testDegrees(self):
self.assertRaises(TypeError, math.degrees)
@@ -272,7 +272,7 @@ class MathTests(unittest.TestCase):
self.ftest('exp(1)', math.exp(1), math.e)
self.assertEquals(math.exp(INF), INF)
self.assertEquals(math.exp(NINF), 0.)
- self.assert_(math.isnan(math.exp(NAN)))
+ self.assertTrue(math.isnan(math.exp(NAN)))
def testFabs(self):
self.assertRaises(TypeError, math.fabs)
@@ -309,7 +309,7 @@ class MathTests(unittest.TestCase):
self.ftest('floor(-1.23e167)', math.floor(-1.23e167), -1.23e167)
#self.assertEquals(math.ceil(INF), INF)
#self.assertEquals(math.ceil(NINF), NINF)
- #self.assert_(math.isnan(math.floor(NAN)))
+ #self.assertTrue(math.isnan(math.floor(NAN)))
class TestFloor:
def __floor__(self):
@@ -332,9 +332,9 @@ class MathTests(unittest.TestCase):
self.ftest('fmod(-10,1)', math.fmod(-10,1), 0)
self.ftest('fmod(-10,0.5)', math.fmod(-10,0.5), 0)
self.ftest('fmod(-10,1.5)', math.fmod(-10,1.5), -1)
- self.assert_(math.isnan(math.fmod(NAN, 1.)))
- self.assert_(math.isnan(math.fmod(1., NAN)))
- self.assert_(math.isnan(math.fmod(NAN, NAN)))
+ self.assertTrue(math.isnan(math.fmod(NAN, 1.)))
+ self.assertTrue(math.isnan(math.fmod(1., NAN)))
+ self.assertTrue(math.isnan(math.fmod(NAN, NAN)))
self.assertRaises(ValueError, math.fmod, 1., 0.)
self.assertRaises(ValueError, math.fmod, INF, 1.)
self.assertRaises(ValueError, math.fmod, NINF, 1.)
@@ -362,7 +362,7 @@ class MathTests(unittest.TestCase):
self.assertEquals(math.frexp(INF)[0], INF)
self.assertEquals(math.frexp(NINF)[0], NINF)
- self.assert_(math.isnan(math.frexp(NAN)[0]))
+ self.assertTrue(math.isnan(math.frexp(NAN)[0]))
@unittest.skipUnless(float.__getformat__("double").startswith("IEEE"),
"test requires IEEE 754 doubles")
@@ -464,8 +464,8 @@ class MathTests(unittest.TestCase):
self.assertEqual(math.hypot(INF, NAN), INF)
self.assertEqual(math.hypot(NAN, NINF), INF)
self.assertEqual(math.hypot(NINF, NAN), INF)
- self.assert_(math.isnan(math.hypot(1.0, NAN)))
- self.assert_(math.isnan(math.hypot(NAN, -2.0)))
+ self.assertTrue(math.isnan(math.hypot(1.0, NAN)))
+ self.assertTrue(math.isnan(math.hypot(NAN, -2.0)))
def testLdexp(self):
self.assertRaises(TypeError, math.ldexp)
@@ -479,7 +479,7 @@ class MathTests(unittest.TestCase):
self.assertEquals(math.ldexp(-1., -1000000), -0.)
self.assertEquals(math.ldexp(INF, 30), INF)
self.assertEquals(math.ldexp(NINF, -213), NINF)
- self.assert_(math.isnan(math.ldexp(NAN, 0)))
+ self.assertTrue(math.isnan(math.ldexp(NAN, 0)))
# large second argument
for n in [10**5, 10**10, 10**20, 10**40]:
@@ -489,7 +489,7 @@ class MathTests(unittest.TestCase):
self.assertEquals(math.ldexp(-1., -n), -0.)
self.assertEquals(math.ldexp(0., -n), 0.)
self.assertEquals(math.ldexp(-0., -n), -0.)
- self.assert_(math.isnan(math.ldexp(NAN, -n)))
+ self.assertTrue(math.isnan(math.ldexp(NAN, -n)))
self.assertRaises(OverflowError, math.ldexp, 1., n)
self.assertRaises(OverflowError, math.ldexp, -1., n)
@@ -497,7 +497,7 @@ class MathTests(unittest.TestCase):
self.assertEquals(math.ldexp(-0., n), -0.)
self.assertEquals(math.ldexp(INF, n), INF)
self.assertEquals(math.ldexp(NINF, n), NINF)
- self.assert_(math.isnan(math.ldexp(NAN, n)))
+ self.assertTrue(math.isnan(math.ldexp(NAN, n)))
def testLog(self):
self.assertRaises(TypeError, math.log)
@@ -509,7 +509,7 @@ class MathTests(unittest.TestCase):
self.ftest('log(10**40, 10**20)', math.log(10**40, 10**20), 2)
self.assertEquals(math.log(INF), INF)
self.assertRaises(ValueError, math.log, NINF)
- self.assert_(math.isnan(math.log(NAN)))
+ self.assertTrue(math.isnan(math.log(NAN)))
def testLog1p(self):
self.assertRaises(TypeError, math.log1p)
@@ -519,7 +519,7 @@ class MathTests(unittest.TestCase):
self.ftest('log1p(1)', math.log1p(1), math.log(2))
self.assertEquals(math.log1p(INF), INF)
self.assertRaises(ValueError, math.log1p, NINF)
- self.assert_(math.isnan(math.log1p(NAN)))
+ self.assertTrue(math.isnan(math.log1p(NAN)))
n= 2**90
self.assertAlmostEquals(math.log1p(n), 62.383246250395075)
self.assertAlmostEquals(math.log1p(n), math.log1p(float(n)))
@@ -531,7 +531,7 @@ class MathTests(unittest.TestCase):
self.ftest('log10(10)', math.log10(10), 1)
self.assertEquals(math.log(INF), INF)
self.assertRaises(ValueError, math.log10, NINF)
- self.assert_(math.isnan(math.log10(NAN)))
+ self.assertTrue(math.isnan(math.log10(NAN)))
def testModf(self):
self.assertRaises(TypeError, math.modf)
@@ -549,8 +549,8 @@ class MathTests(unittest.TestCase):
self.assertEquals(math.modf(NINF), (-0.0, NINF))
modf_nan = math.modf(NAN)
- self.assert_(math.isnan(modf_nan[0]))
- self.assert_(math.isnan(modf_nan[1]))
+ self.assertTrue(math.isnan(modf_nan[0]))
+ self.assertTrue(math.isnan(modf_nan[1]))
def testPow(self):
self.assertRaises(TypeError, math.pow)
@@ -562,9 +562,9 @@ class MathTests(unittest.TestCase):
self.assertEqual(math.pow(NINF, 1), NINF)
self.assertEqual((math.pow(1, INF)), 1.)
self.assertEqual((math.pow(1, NINF)), 1.)
- self.assert_(math.isnan(math.pow(NAN, 1)))
- self.assert_(math.isnan(math.pow(2, NAN)))
- self.assert_(math.isnan(math.pow(0, NAN)))
+ self.assertTrue(math.isnan(math.pow(NAN, 1)))
+ self.assertTrue(math.isnan(math.pow(2, NAN)))
+ self.assertTrue(math.isnan(math.pow(0, NAN)))
self.assertEqual(math.pow(1, NAN), 1)
# pow(0., x)
@@ -578,7 +578,7 @@ class MathTests(unittest.TestCase):
self.assertRaises(ValueError, math.pow, 0., -2.3)
self.assertRaises(ValueError, math.pow, 0., -3.)
self.assertRaises(ValueError, math.pow, 0., NINF)
- self.assert_(math.isnan(math.pow(0., NAN)))
+ self.assertTrue(math.isnan(math.pow(0., NAN)))
# pow(INF, x)
self.assertEqual(math.pow(INF, INF), INF)
@@ -591,7 +591,7 @@ class MathTests(unittest.TestCase):
self.assertEqual(math.pow(INF, -2.3), 0.)
self.assertEqual(math.pow(INF, -3.), 0.)
self.assertEqual(math.pow(INF, NINF), 0.)
- self.assert_(math.isnan(math.pow(INF, NAN)))
+ self.assertTrue(math.isnan(math.pow(INF, NAN)))
# pow(-0., x)
self.assertEqual(math.pow(-0., INF), 0.)
@@ -604,7 +604,7 @@ class MathTests(unittest.TestCase):
self.assertRaises(ValueError, math.pow, -0., -2.3)
self.assertRaises(ValueError, math.pow, -0., -3.)
self.assertRaises(ValueError, math.pow, -0., NINF)
- self.assert_(math.isnan(math.pow(-0., NAN)))
+ self.assertTrue(math.isnan(math.pow(-0., NAN)))
# pow(NINF, x)
self.assertEqual(math.pow(NINF, INF), INF)
@@ -617,7 +617,7 @@ class MathTests(unittest.TestCase):
self.assertEqual(math.pow(NINF, -2.3), 0.)
self.assertEqual(math.pow(NINF, -3.), -0.)
self.assertEqual(math.pow(NINF, NINF), 0.)
- self.assert_(math.isnan(math.pow(NINF, NAN)))
+ self.assertTrue(math.isnan(math.pow(NINF, NAN)))
# pow(-1, x)
self.assertEqual(math.pow(-1., INF), 1.)
@@ -630,7 +630,7 @@ class MathTests(unittest.TestCase):
self.assertRaises(ValueError, math.pow, -1., -2.3)
self.assertEqual(math.pow(-1., -3.), -1.)
self.assertEqual(math.pow(-1., NINF), 1.)
- self.assert_(math.isnan(math.pow(-1., NAN)))
+ self.assertTrue(math.isnan(math.pow(-1., NAN)))
# pow(1, x)
self.assertEqual(math.pow(1., INF), 1.)
@@ -713,12 +713,12 @@ class MathTests(unittest.TestCase):
self.ftest('sin(pi/2)', math.sin(math.pi/2), 1)
self.ftest('sin(-pi/2)', math.sin(-math.pi/2), -1)
try:
- self.assert_(math.isnan(math.sin(INF)))
- self.assert_(math.isnan(math.sin(NINF)))
+ self.assertTrue(math.isnan(math.sin(INF)))
+ self.assertTrue(math.isnan(math.sin(NINF)))
except ValueError:
self.assertRaises(ValueError, math.sin, INF)
self.assertRaises(ValueError, math.sin, NINF)
- self.assert_(math.isnan(math.sin(NAN)))
+ self.assertTrue(math.isnan(math.sin(NAN)))
def testSinh(self):
self.assertRaises(TypeError, math.sinh)
@@ -727,7 +727,7 @@ class MathTests(unittest.TestCase):
self.ftest('sinh(1)+sinh(-1)', math.sinh(1)+math.sinh(-1), 0)
self.assertEquals(math.sinh(INF), INF)
self.assertEquals(math.sinh(NINF), NINF)
- self.assert_(math.isnan(math.sinh(NAN)))
+ self.assertTrue(math.isnan(math.sinh(NAN)))
def testSqrt(self):
self.assertRaises(TypeError, math.sqrt)
@@ -736,7 +736,7 @@ class MathTests(unittest.TestCase):
self.ftest('sqrt(4)', math.sqrt(4), 2)
self.assertEquals(math.sqrt(INF), INF)
self.assertRaises(ValueError, math.sqrt, NINF)
- self.assert_(math.isnan(math.sqrt(NAN)))
+ self.assertTrue(math.isnan(math.sqrt(NAN)))
def testTan(self):
self.assertRaises(TypeError, math.tan)
@@ -744,12 +744,12 @@ class MathTests(unittest.TestCase):
self.ftest('tan(pi/4)', math.tan(math.pi/4), 1)
self.ftest('tan(-pi/4)', math.tan(-math.pi/4), -1)
try:
- self.assert_(math.isnan(math.tan(INF)))
- self.assert_(math.isnan(math.tan(NINF)))
+ self.assertTrue(math.isnan(math.tan(INF)))
+ self.assertTrue(math.isnan(math.tan(NINF)))
except:
self.assertRaises(ValueError, math.tan, INF)
self.assertRaises(ValueError, math.tan, NINF)
- self.assert_(math.isnan(math.tan(NAN)))
+ self.assertTrue(math.isnan(math.tan(NAN)))
def testTanh(self):
self.assertRaises(TypeError, math.tanh)
@@ -757,7 +757,7 @@ class MathTests(unittest.TestCase):
self.ftest('tanh(1)+tanh(-1)', math.tanh(1)+math.tanh(-1), 0)
self.ftest('tanh(inf)', math.tanh(INF), 1)
self.ftest('tanh(-inf)', math.tanh(NINF), -1)
- self.assert_(math.isnan(math.tanh(NAN)))
+ self.assertTrue(math.isnan(math.tanh(NAN)))
# check that tanh(-0.) == -0. on IEEE 754 systems
if float.__getformat__("double").startswith("IEEE"):
self.assertEqual(math.tanh(-0.), -0.)
@@ -804,20 +804,20 @@ class MathTests(unittest.TestCase):
self.assertEqual(math.copysign(4., -0.), -4.0)
def testIsnan(self):
- self.assert_(math.isnan(float("nan")))
- self.assert_(math.isnan(float("inf")* 0.))
- self.failIf(math.isnan(float("inf")))
- self.failIf(math.isnan(0.))
- self.failIf(math.isnan(1.))
+ self.assertTrue(math.isnan(float("nan")))
+ self.assertTrue(math.isnan(float("inf")* 0.))
+ self.assertFalse(math.isnan(float("inf")))
+ self.assertFalse(math.isnan(0.))
+ self.assertFalse(math.isnan(1.))
def testIsinf(self):
- self.assert_(math.isinf(float("inf")))
- self.assert_(math.isinf(float("-inf")))
- self.assert_(math.isinf(1E400))
- self.assert_(math.isinf(-1E400))
- self.failIf(math.isinf(float("nan")))
- self.failIf(math.isinf(0.))
- self.failIf(math.isinf(1.))
+ self.assertTrue(math.isinf(float("inf")))
+ self.assertTrue(math.isinf(float("-inf")))
+ self.assertTrue(math.isinf(1E400))
+ self.assertTrue(math.isinf(-1E400))
+ self.assertFalse(math.isinf(float("nan")))
+ self.assertFalse(math.isinf(0.))
+ self.assertFalse(math.isinf(1.))
# RED_FLAG 16-Oct-2000 Tim
# While 2.0 is more consistent about exceptions than previous releases, it
diff --git a/Lib/test/test_memoryio.py b/Lib/test/test_memoryio.py
index 0d044e96ba..c98c30704d 100644
--- a/Lib/test/test_memoryio.py
+++ b/Lib/test/test_memoryio.py
@@ -222,8 +222,8 @@ class MemoryTestMixin:
memio = self.ioclass(buf * 10)
self.assertEqual(iter(memio), memio)
- self.failUnless(hasattr(memio, '__iter__'))
- self.failUnless(hasattr(memio, '__next__'))
+ self.assertTrue(hasattr(memio, '__iter__'))
+ self.assertTrue(hasattr(memio, '__next__'))
i = 0
for line in memio:
self.assertEqual(line, buf)
diff --git a/Lib/test/test_memoryview.py b/Lib/test/test_memoryview.py
index 31bfa62017..abda678f7d 100644
--- a/Lib/test/test_memoryview.py
+++ b/Lib/test/test_memoryview.py
@@ -28,7 +28,7 @@ class AbstractMemoryTests:
oldrefcount = sys.getrefcount(b)
m = self._view(b)
self.assertEquals(m[0], item(b"a"))
- self.assert_(isinstance(m[0], bytes), type(m[0]))
+ self.assertTrue(isinstance(m[0], bytes), type(m[0]))
self.assertEquals(m[5], item(b"f"))
self.assertEquals(m[-1], item(b"f"))
self.assertEquals(m[-6], item(b"a"))
@@ -119,7 +119,7 @@ class AbstractMemoryTests:
expected = b"".join(
self.getitem_type(bytes([c])) for c in b"abcdef")
self.assertEquals(b, expected)
- self.assert_(isinstance(b, bytes), type(b))
+ self.assertTrue(isinstance(b, bytes), type(b))
def test_tolist(self):
for tp in self._types:
@@ -214,7 +214,7 @@ class AbstractMemoryTests:
b = m = o = None
# The cycle must be broken
gc.collect()
- self.assert_(wr() is None, wr())
+ self.assertTrue(wr() is None, wr())
# Variations on source objects for the buffer: bytes-like objects, then arrays
@@ -291,8 +291,8 @@ class BytesMemoryviewTest(unittest.TestCase,
def test_constructor(self):
for tp in self._types:
ob = tp(self._source)
- self.assert_(memoryview(ob))
- self.assert_(memoryview(object=ob))
+ self.assertTrue(memoryview(ob))
+ self.assertTrue(memoryview(object=ob))
self.assertRaises(TypeError, memoryview)
self.assertRaises(TypeError, memoryview, ob, ob)
self.assertRaises(TypeError, memoryview, argument=ob)
diff --git a/Lib/test/test_mimetypes.py b/Lib/test/test_mimetypes.py
index 9651a60132..7918de6a57 100644
--- a/Lib/test/test_mimetypes.py
+++ b/Lib/test/test_mimetypes.py
@@ -47,7 +47,7 @@ class MimeTypesTestCase(unittest.TestCase):
def test_guess_all_types(self):
eq = self.assertEqual
- unless = self.failUnless
+ unless = self.assertTrue
# First try strict. Use a set here for testing the results because if
# test_urllib2 is run before test_mimetypes, global state is modified
# such that the 'all' set will have more items in it.
diff --git a/Lib/test/test_minidom.py b/Lib/test/test_minidom.py
index 76b7354ed4..0a0a663082 100644
--- a/Lib/test/test_minidom.py
+++ b/Lib/test/test_minidom.py
@@ -733,7 +733,7 @@ class MinidomTest(unittest.TestCase):
def check_clone_attribute(self, deep, testName):
doc = parseString("<doc attr='value'/>")
attr = doc.documentElement.getAttributeNode("attr")
- self.failIfEqual(attr, None)
+ self.assertNotEqual(attr, None)
clone = attr.cloneNode(deep)
self.confirm(not clone.isSameNode(attr))
self.confirm(not attr.isSameNode(clone))
diff --git a/Lib/test/test_mmap.py b/Lib/test/test_mmap.py
index dec0980317..eae4157edc 100644
--- a/Lib/test/test_mmap.py
+++ b/Lib/test/test_mmap.py
@@ -501,8 +501,8 @@ class MmapTests(unittest.TestCase):
f.close()
def test_error(self):
- self.assert_(issubclass(mmap.error, EnvironmentError))
- self.assert_("mmap.error" in str(mmap.error))
+ self.assertTrue(issubclass(mmap.error, EnvironmentError))
+ self.assertTrue("mmap.error" in str(mmap.error))
def test_io_methods(self):
data = b"0123456789"
diff --git a/Lib/test/test_module.py b/Lib/test/test_module.py
index 45556e827b..225e954fc4 100644
--- a/Lib/test/test_module.py
+++ b/Lib/test/test_module.py
@@ -10,7 +10,7 @@ class ModuleTests(unittest.TestCase):
# An uninitialized module has no __dict__ or __name__,
# and __doc__ is None
foo = ModuleType.__new__(ModuleType)
- self.failUnless(foo.__dict__ is None)
+ self.assertTrue(foo.__dict__ is None)
try:
s = foo.__name__
self.fail("__name__ = %s" % repr(s))
@@ -52,7 +52,7 @@ class ModuleTests(unittest.TestCase):
self.assertEqual(foo.bar, 42)
self.assertEqual(foo.__dict__,
{"__name__": "foo", "__doc__": "foodoc", "bar": 42})
- self.failUnless(foo.__dict__ is d)
+ self.assertTrue(foo.__dict__ is d)
def test_main():
run_unittest(ModuleTests)
diff --git a/Lib/test/test_modulefinder.py b/Lib/test/test_modulefinder.py
index bddd6c5c66..b4fa06a41b 100644
--- a/Lib/test/test_modulefinder.py
+++ b/Lib/test/test_modulefinder.py
@@ -233,12 +233,12 @@ class ModuleFinderTest(unittest.TestCase):
more = list(found - modules)
less = list(modules - found)
# check if we found what we expected, not more, not less
- self.failUnlessEqual((more, less), ([], []))
+ self.assertEqual((more, less), ([], []))
# check for missing and maybe missing modules
bad, maybe = mf.any_missing_maybe()
- self.failUnlessEqual(bad, missing)
- self.failUnlessEqual(maybe, maybe_missing)
+ self.assertEqual(bad, missing)
+ self.assertEqual(maybe, maybe_missing)
finally:
distutils.dir_util.remove_tree(TEST_DIR)
diff --git a/Lib/test/test_multibytecodec.py b/Lib/test/test_multibytecodec.py
index 1d9d9e35eb..b482b3968c 100644
--- a/Lib/test/test_multibytecodec.py
+++ b/Lib/test/test_multibytecodec.py
@@ -242,10 +242,10 @@ class Test_ISO2022(unittest.TestCase):
self.assertEqual(iso2022jp2.decode('iso2022-jp-2'), uni)
def test_iso2022_jp_g0(self):
- self.failIf(b'\x0e' in '\N{SOFT HYPHEN}'.encode('iso-2022-jp-2'))
+ self.assertFalse(b'\x0e' in '\N{SOFT HYPHEN}'.encode('iso-2022-jp-2'))
for encoding in ('iso-2022-jp-2004', 'iso-2022-jp-3'):
e = '\u3406'.encode(encoding)
- self.failIf(any(x > 0x80 for x in e))
+ self.assertFalse(any(x > 0x80 for x in e))
def test_bug1572832(self):
if sys.maxunicode >= 0x10000:
diff --git a/Lib/test/test_multibytecodec_support.py b/Lib/test/test_multibytecodec_support.py
index 3e0476e41c..5e68856b7a 100644
--- a/Lib/test/test_multibytecodec_support.py
+++ b/Lib/test/test_multibytecodec_support.py
@@ -53,9 +53,9 @@ class TestBase:
if expected:
result = func(source, scheme)[0]
if func is self.decode:
- self.assert_(type(result) is str, type(result))
+ self.assertTrue(type(result) is str, type(result))
else:
- self.assert_(type(result) is bytes, type(result))
+ self.assertTrue(type(result) is bytes, type(result))
self.assertEqual(result, expected)
else:
self.assertRaises(UnicodeError, func, source, scheme)
diff --git a/Lib/test/test_netrc.py b/Lib/test/test_netrc.py
index 938e255e41..21ff88c8e1 100644
--- a/Lib/test/test_netrc.py
+++ b/Lib/test/test_netrc.py
@@ -34,11 +34,11 @@ class NetrcTestCase(unittest.TestCase):
def test_case_1(self):
nrc = netrc.netrc(temp_filename)
- self.assert_(nrc.macros == {'macro1':['line1\n', 'line2\n'],
+ self.assertTrue(nrc.macros == {'macro1':['line1\n', 'line2\n'],
'macro2':['line3\n', 'line4\n']}
)
- self.assert_(nrc.hosts['foo'] == ('log1', 'acct1', 'pass1'))
- self.assert_(nrc.hosts['default'] == ('log2', None, 'pass2'))
+ self.assertTrue(nrc.hosts['foo'] == ('log1', 'acct1', 'pass1'))
+ self.assertTrue(nrc.hosts['default'] == ('log2', None, 'pass2'))
def test_main():
support.run_unittest(NetrcTestCase)
diff --git a/Lib/test/test_normalization.py b/Lib/test/test_normalization.py
index 9e85e0a915..f92a714486 100644
--- a/Lib/test/test_normalization.py
+++ b/Lib/test/test_normalization.py
@@ -67,14 +67,14 @@ class NormalizationTest(unittest.TestCase):
continue
# Perform tests
- self.failUnless(c2 == NFC(c1) == NFC(c2) == NFC(c3), line)
- self.failUnless(c4 == NFC(c4) == NFC(c5), line)
- self.failUnless(c3 == NFD(c1) == NFD(c2) == NFD(c3), line)
- self.failUnless(c5 == NFD(c4) == NFD(c5), line)
- self.failUnless(c4 == NFKC(c1) == NFKC(c2) == \
+ self.assertTrue(c2 == NFC(c1) == NFC(c2) == NFC(c3), line)
+ self.assertTrue(c4 == NFC(c4) == NFC(c5), line)
+ self.assertTrue(c3 == NFD(c1) == NFD(c2) == NFD(c3), line)
+ self.assertTrue(c5 == NFD(c4) == NFD(c5), line)
+ self.assertTrue(c4 == NFKC(c1) == NFKC(c2) == \
NFKC(c3) == NFKC(c4) == NFKC(c5),
line)
- self.failUnless(c5 == NFKD(c1) == NFKD(c2) == \
+ self.assertTrue(c5 == NFKD(c1) == NFKD(c2) == \
NFKD(c3) == NFKD(c4) == NFKD(c5),
line)
@@ -87,7 +87,7 @@ class NormalizationTest(unittest.TestCase):
X = chr(c)
if X in part1_data:
continue
- self.failUnless(X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X), c)
+ self.assertTrue(X == NFC(X) == NFD(X) == NFKC(X) == NFKD(X), c)
def test_bug_834676(self):
# Check for bug 834676
diff --git a/Lib/test/test_opcodes.py b/Lib/test/test_opcodes.py
index 4403a114d2..8b7fd9e7a8 100644
--- a/Lib/test/test_opcodes.py
+++ b/Lib/test/test_opcodes.py
@@ -60,7 +60,7 @@ class OpcodeTest(unittest.TestCase):
try: raise DClass(a)
except DClass as v:
- self.assert_(isinstance(v, DClass))
+ self.assertTrue(isinstance(v, DClass))
else:
self.fail("no exception")
diff --git a/Lib/test/test_operator.py b/Lib/test/test_operator.py
index bf38298a45..aa3219f499 100644
--- a/Lib/test/test_operator.py
+++ b/Lib/test/test_operator.py
@@ -34,237 +34,237 @@ class Seq2(object):
class OperatorTestCase(unittest.TestCase):
def test_lt(self):
- self.failUnlessRaises(TypeError, operator.lt)
- self.failUnlessRaises(TypeError, operator.lt, 1j, 2j)
- self.failIf(operator.lt(1, 0))
- self.failIf(operator.lt(1, 0.0))
- self.failIf(operator.lt(1, 1))
- self.failIf(operator.lt(1, 1.0))
- self.failUnless(operator.lt(1, 2))
- self.failUnless(operator.lt(1, 2.0))
+ self.assertRaises(TypeError, operator.lt)
+ self.assertRaises(TypeError, operator.lt, 1j, 2j)
+ self.assertFalse(operator.lt(1, 0))
+ self.assertFalse(operator.lt(1, 0.0))
+ self.assertFalse(operator.lt(1, 1))
+ self.assertFalse(operator.lt(1, 1.0))
+ self.assertTrue(operator.lt(1, 2))
+ self.assertTrue(operator.lt(1, 2.0))
def test_le(self):
- self.failUnlessRaises(TypeError, operator.le)
- self.failUnlessRaises(TypeError, operator.le, 1j, 2j)
- self.failIf(operator.le(1, 0))
- self.failIf(operator.le(1, 0.0))
- self.failUnless(operator.le(1, 1))
- self.failUnless(operator.le(1, 1.0))
- self.failUnless(operator.le(1, 2))
- self.failUnless(operator.le(1, 2.0))
+ self.assertRaises(TypeError, operator.le)
+ self.assertRaises(TypeError, operator.le, 1j, 2j)
+ self.assertFalse(operator.le(1, 0))
+ self.assertFalse(operator.le(1, 0.0))
+ self.assertTrue(operator.le(1, 1))
+ self.assertTrue(operator.le(1, 1.0))
+ self.assertTrue(operator.le(1, 2))
+ self.assertTrue(operator.le(1, 2.0))
def test_eq(self):
class C(object):
def __eq__(self, other):
raise SyntaxError
- self.failUnlessRaises(TypeError, operator.eq)
- self.failUnlessRaises(SyntaxError, operator.eq, C(), C())
- self.failIf(operator.eq(1, 0))
- self.failIf(operator.eq(1, 0.0))
- self.failUnless(operator.eq(1, 1))
- self.failUnless(operator.eq(1, 1.0))
- self.failIf(operator.eq(1, 2))
- self.failIf(operator.eq(1, 2.0))
+ self.assertRaises(TypeError, operator.eq)
+ self.assertRaises(SyntaxError, operator.eq, C(), C())
+ self.assertFalse(operator.eq(1, 0))
+ self.assertFalse(operator.eq(1, 0.0))
+ self.assertTrue(operator.eq(1, 1))
+ self.assertTrue(operator.eq(1, 1.0))
+ self.assertFalse(operator.eq(1, 2))
+ self.assertFalse(operator.eq(1, 2.0))
def test_ne(self):
class C(object):
def __ne__(self, other):
raise SyntaxError
- self.failUnlessRaises(TypeError, operator.ne)
- self.failUnlessRaises(SyntaxError, operator.ne, C(), C())
- self.failUnless(operator.ne(1, 0))
- self.failUnless(operator.ne(1, 0.0))
- self.failIf(operator.ne(1, 1))
- self.failIf(operator.ne(1, 1.0))
- self.failUnless(operator.ne(1, 2))
- self.failUnless(operator.ne(1, 2.0))
+ self.assertRaises(TypeError, operator.ne)
+ self.assertRaises(SyntaxError, operator.ne, C(), C())
+ self.assertTrue(operator.ne(1, 0))
+ self.assertTrue(operator.ne(1, 0.0))
+ self.assertFalse(operator.ne(1, 1))
+ self.assertFalse(operator.ne(1, 1.0))
+ self.assertTrue(operator.ne(1, 2))
+ self.assertTrue(operator.ne(1, 2.0))
def test_ge(self):
- self.failUnlessRaises(TypeError, operator.ge)
- self.failUnlessRaises(TypeError, operator.ge, 1j, 2j)
- self.failUnless(operator.ge(1, 0))
- self.failUnless(operator.ge(1, 0.0))
- self.failUnless(operator.ge(1, 1))
- self.failUnless(operator.ge(1, 1.0))
- self.failIf(operator.ge(1, 2))
- self.failIf(operator.ge(1, 2.0))
+ self.assertRaises(TypeError, operator.ge)
+ self.assertRaises(TypeError, operator.ge, 1j, 2j)
+ self.assertTrue(operator.ge(1, 0))
+ self.assertTrue(operator.ge(1, 0.0))
+ self.assertTrue(operator.ge(1, 1))
+ self.assertTrue(operator.ge(1, 1.0))
+ self.assertFalse(operator.ge(1, 2))
+ self.assertFalse(operator.ge(1, 2.0))
def test_gt(self):
- self.failUnlessRaises(TypeError, operator.gt)
- self.failUnlessRaises(TypeError, operator.gt, 1j, 2j)
- self.failUnless(operator.gt(1, 0))
- self.failUnless(operator.gt(1, 0.0))
- self.failIf(operator.gt(1, 1))
- self.failIf(operator.gt(1, 1.0))
- self.failIf(operator.gt(1, 2))
- self.failIf(operator.gt(1, 2.0))
+ self.assertRaises(TypeError, operator.gt)
+ self.assertRaises(TypeError, operator.gt, 1j, 2j)
+ self.assertTrue(operator.gt(1, 0))
+ self.assertTrue(operator.gt(1, 0.0))
+ self.assertFalse(operator.gt(1, 1))
+ self.assertFalse(operator.gt(1, 1.0))
+ self.assertFalse(operator.gt(1, 2))
+ self.assertFalse(operator.gt(1, 2.0))
def test_abs(self):
- self.failUnlessRaises(TypeError, operator.abs)
- self.failUnlessRaises(TypeError, operator.abs, None)
+ self.assertRaises(TypeError, operator.abs)
+ self.assertRaises(TypeError, operator.abs, None)
self.assertEqual(operator.abs(-1), 1)
self.assertEqual(operator.abs(1), 1)
def test_add(self):
- self.failUnlessRaises(TypeError, operator.add)
- self.failUnlessRaises(TypeError, operator.add, None, None)
- self.failUnless(operator.add(3, 4) == 7)
+ self.assertRaises(TypeError, operator.add)
+ self.assertRaises(TypeError, operator.add, None, None)
+ self.assertTrue(operator.add(3, 4) == 7)
def test_bitwise_and(self):
- self.failUnlessRaises(TypeError, operator.and_)
- self.failUnlessRaises(TypeError, operator.and_, None, None)
- self.failUnless(operator.and_(0xf, 0xa) == 0xa)
+ self.assertRaises(TypeError, operator.and_)
+ self.assertRaises(TypeError, operator.and_, None, None)
+ self.assertTrue(operator.and_(0xf, 0xa) == 0xa)
def test_concat(self):
- self.failUnlessRaises(TypeError, operator.concat)
- self.failUnlessRaises(TypeError, operator.concat, None, None)
- self.failUnless(operator.concat('py', 'thon') == 'python')
- self.failUnless(operator.concat([1, 2], [3, 4]) == [1, 2, 3, 4])
- self.failUnless(operator.concat(Seq1([5, 6]), Seq1([7])) == [5, 6, 7])
- self.failUnless(operator.concat(Seq2([5, 6]), Seq2([7])) == [5, 6, 7])
- self.failUnlessRaises(TypeError, operator.concat, 13, 29)
+ self.assertRaises(TypeError, operator.concat)
+ self.assertRaises(TypeError, operator.concat, None, None)
+ self.assertTrue(operator.concat('py', 'thon') == 'python')
+ self.assertTrue(operator.concat([1, 2], [3, 4]) == [1, 2, 3, 4])
+ self.assertTrue(operator.concat(Seq1([5, 6]), Seq1([7])) == [5, 6, 7])
+ self.assertTrue(operator.concat(Seq2([5, 6]), Seq2([7])) == [5, 6, 7])
+ self.assertRaises(TypeError, operator.concat, 13, 29)
def test_countOf(self):
- self.failUnlessRaises(TypeError, operator.countOf)
- self.failUnlessRaises(TypeError, operator.countOf, None, None)
- self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1)
- self.failUnless(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0)
+ self.assertRaises(TypeError, operator.countOf)
+ self.assertRaises(TypeError, operator.countOf, None, None)
+ self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1)
+ self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0)
def test_delitem(self):
a = [4, 3, 2, 1]
- self.failUnlessRaises(TypeError, operator.delitem, a)
- self.failUnlessRaises(TypeError, operator.delitem, a, None)
- self.failUnless(operator.delitem(a, 1) is None)
- self.assert_(a == [4, 2, 1])
+ self.assertRaises(TypeError, operator.delitem, a)
+ self.assertRaises(TypeError, operator.delitem, a, None)
+ self.assertTrue(operator.delitem(a, 1) is None)
+ self.assertTrue(a == [4, 2, 1])
def test_floordiv(self):
- self.failUnlessRaises(TypeError, operator.floordiv, 5)
- self.failUnlessRaises(TypeError, operator.floordiv, None, None)
- self.failUnless(operator.floordiv(5, 2) == 2)
+ self.assertRaises(TypeError, operator.floordiv, 5)
+ self.assertRaises(TypeError, operator.floordiv, None, None)
+ self.assertTrue(operator.floordiv(5, 2) == 2)
def test_truediv(self):
- self.failUnlessRaises(TypeError, operator.truediv, 5)
- self.failUnlessRaises(TypeError, operator.truediv, None, None)
- self.failUnless(operator.truediv(5, 2) == 2.5)
+ self.assertRaises(TypeError, operator.truediv, 5)
+ self.assertRaises(TypeError, operator.truediv, None, None)
+ self.assertTrue(operator.truediv(5, 2) == 2.5)
def test_getitem(self):
a = range(10)
- self.failUnlessRaises(TypeError, operator.getitem)
- self.failUnlessRaises(TypeError, operator.getitem, a, None)
- self.failUnless(operator.getitem(a, 2) == 2)
+ self.assertRaises(TypeError, operator.getitem)
+ self.assertRaises(TypeError, operator.getitem, a, None)
+ self.assertTrue(operator.getitem(a, 2) == 2)
def test_indexOf(self):
- self.failUnlessRaises(TypeError, operator.indexOf)
- self.failUnlessRaises(TypeError, operator.indexOf, None, None)
- self.failUnless(operator.indexOf([4, 3, 2, 1], 3) == 1)
+ self.assertRaises(TypeError, operator.indexOf)
+ self.assertRaises(TypeError, operator.indexOf, None, None)
+ self.assertTrue(operator.indexOf([4, 3, 2, 1], 3) == 1)
self.assertRaises(ValueError, operator.indexOf, [4, 3, 2, 1], 0)
def test_invert(self):
- self.failUnlessRaises(TypeError, operator.invert)
- self.failUnlessRaises(TypeError, operator.invert, None)
+ self.assertRaises(TypeError, operator.invert)
+ self.assertRaises(TypeError, operator.invert, None)
self.assertEqual(operator.inv(4), -5)
def test_lshift(self):
- self.failUnlessRaises(TypeError, operator.lshift)
- self.failUnlessRaises(TypeError, operator.lshift, None, 42)
- self.failUnless(operator.lshift(5, 1) == 10)
- self.failUnless(operator.lshift(5, 0) == 5)
+ self.assertRaises(TypeError, operator.lshift)
+ self.assertRaises(TypeError, operator.lshift, None, 42)
+ self.assertTrue(operator.lshift(5, 1) == 10)
+ self.assertTrue(operator.lshift(5, 0) == 5)
self.assertRaises(ValueError, operator.lshift, 2, -1)
def test_mod(self):
- self.failUnlessRaises(TypeError, operator.mod)
- self.failUnlessRaises(TypeError, operator.mod, None, 42)
- self.failUnless(operator.mod(5, 2) == 1)
+ self.assertRaises(TypeError, operator.mod)
+ self.assertRaises(TypeError, operator.mod, None, 42)
+ self.assertTrue(operator.mod(5, 2) == 1)
def test_mul(self):
- self.failUnlessRaises(TypeError, operator.mul)
- self.failUnlessRaises(TypeError, operator.mul, None, None)
- self.failUnless(operator.mul(5, 2) == 10)
+ self.assertRaises(TypeError, operator.mul)
+ self.assertRaises(TypeError, operator.mul, None, None)
+ self.assertTrue(operator.mul(5, 2) == 10)
def test_neg(self):
- self.failUnlessRaises(TypeError, operator.neg)
- self.failUnlessRaises(TypeError, operator.neg, None)
+ self.assertRaises(TypeError, operator.neg)
+ self.assertRaises(TypeError, operator.neg, None)
self.assertEqual(operator.neg(5), -5)
self.assertEqual(operator.neg(-5), 5)
self.assertEqual(operator.neg(0), 0)
self.assertEqual(operator.neg(-0), 0)
def test_bitwise_or(self):
- self.failUnlessRaises(TypeError, operator.or_)
- self.failUnlessRaises(TypeError, operator.or_, None, None)
- self.failUnless(operator.or_(0xa, 0x5) == 0xf)
+ self.assertRaises(TypeError, operator.or_)
+ self.assertRaises(TypeError, operator.or_, None, None)
+ self.assertTrue(operator.or_(0xa, 0x5) == 0xf)
def test_pos(self):
- self.failUnlessRaises(TypeError, operator.pos)
- self.failUnlessRaises(TypeError, operator.pos, None)
+ self.assertRaises(TypeError, operator.pos)
+ self.assertRaises(TypeError, operator.pos, None)
self.assertEqual(operator.pos(5), 5)
self.assertEqual(operator.pos(-5), -5)
self.assertEqual(operator.pos(0), 0)
self.assertEqual(operator.pos(-0), 0)
def test_pow(self):
- self.failUnlessRaises(TypeError, operator.pow)
- self.failUnlessRaises(TypeError, operator.pow, None, None)
+ self.assertRaises(TypeError, operator.pow)
+ self.assertRaises(TypeError, operator.pow, None, None)
self.assertEqual(operator.pow(3,5), 3**5)
self.assertEqual(operator.__pow__(3,5), 3**5)
self.assertRaises(TypeError, operator.pow, 1)
self.assertRaises(TypeError, operator.pow, 1, 2, 3)
def test_rshift(self):
- self.failUnlessRaises(TypeError, operator.rshift)
- self.failUnlessRaises(TypeError, operator.rshift, None, 42)
- self.failUnless(operator.rshift(5, 1) == 2)
- self.failUnless(operator.rshift(5, 0) == 5)
+ self.assertRaises(TypeError, operator.rshift)
+ self.assertRaises(TypeError, operator.rshift, None, 42)
+ self.assertTrue(operator.rshift(5, 1) == 2)
+ self.assertTrue(operator.rshift(5, 0) == 5)
self.assertRaises(ValueError, operator.rshift, 2, -1)
def test_contains(self):
- self.failUnlessRaises(TypeError, operator.contains)
- self.failUnlessRaises(TypeError, operator.contains, None, None)
- self.failUnless(operator.contains(range(4), 2))
- self.failIf(operator.contains(range(4), 5))
+ self.assertRaises(TypeError, operator.contains)
+ self.assertRaises(TypeError, operator.contains, None, None)
+ self.assertTrue(operator.contains(range(4), 2))
+ self.assertFalse(operator.contains(range(4), 5))
def test_setitem(self):
a = list(range(3))
- self.failUnlessRaises(TypeError, operator.setitem, a)
- self.failUnlessRaises(TypeError, operator.setitem, a, None, None)
- self.failUnless(operator.setitem(a, 0, 2) is None)
- self.assert_(a == [2, 1, 2])
+ self.assertRaises(TypeError, operator.setitem, a)
+ self.assertRaises(TypeError, operator.setitem, a, None, None)
+ self.assertTrue(operator.setitem(a, 0, 2) is None)
+ self.assertTrue(a == [2, 1, 2])
self.assertRaises(IndexError, operator.setitem, a, 4, 2)
def test_sub(self):
- self.failUnlessRaises(TypeError, operator.sub)
- self.failUnlessRaises(TypeError, operator.sub, None, None)
- self.failUnless(operator.sub(5, 2) == 3)
+ self.assertRaises(TypeError, operator.sub)
+ self.assertRaises(TypeError, operator.sub, None, None)
+ self.assertTrue(operator.sub(5, 2) == 3)
def test_truth(self):
class C(object):
def __bool__(self):
raise SyntaxError
- self.failUnlessRaises(TypeError, operator.truth)
- self.failUnlessRaises(SyntaxError, operator.truth, C())
- self.failUnless(operator.truth(5))
- self.failUnless(operator.truth([0]))
- self.failIf(operator.truth(0))
- self.failIf(operator.truth([]))
+ self.assertRaises(TypeError, operator.truth)
+ self.assertRaises(SyntaxError, operator.truth, C())
+ self.assertTrue(operator.truth(5))
+ self.assertTrue(operator.truth([0]))
+ self.assertFalse(operator.truth(0))
+ self.assertFalse(operator.truth([]))
def test_bitwise_xor(self):
- self.failUnlessRaises(TypeError, operator.xor)
- self.failUnlessRaises(TypeError, operator.xor, None, None)
- self.failUnless(operator.xor(0xb, 0xc) == 0x7)
+ self.assertRaises(TypeError, operator.xor)
+ self.assertRaises(TypeError, operator.xor, None, None)
+ self.assertTrue(operator.xor(0xb, 0xc) == 0x7)
def test_is(self):
a = b = 'xyzpdq'
c = a[:3] + b[3:]
- self.failUnlessRaises(TypeError, operator.is_)
- self.failUnless(operator.is_(a, b))
- self.failIf(operator.is_(a,c))
+ self.assertRaises(TypeError, operator.is_)
+ self.assertTrue(operator.is_(a, b))
+ self.assertFalse(operator.is_(a,c))
def test_is_not(self):
a = b = 'xyzpdq'
c = a[:3] + b[3:]
- self.failUnlessRaises(TypeError, operator.is_not)
- self.failIf(operator.is_not(a, b))
- self.failUnless(operator.is_not(a,c))
+ self.assertRaises(TypeError, operator.is_not)
+ self.assertFalse(operator.is_not(a, b))
+ self.assertTrue(operator.is_not(a,c))
def test_attrgetter(self):
class A:
@@ -290,7 +290,7 @@ class OperatorTestCase(unittest.TestCase):
class C(object):
def __getattr__(self, name):
raise SyntaxError
- self.failUnlessRaises(SyntaxError, operator.attrgetter('foo'), C())
+ self.assertRaises(SyntaxError, operator.attrgetter('foo'), C())
# recursive gets
a = A()
@@ -322,7 +322,7 @@ class OperatorTestCase(unittest.TestCase):
class C(object):
def __getitem__(self, name):
raise SyntaxError
- self.failUnlessRaises(SyntaxError, operator.itemgetter(42), C())
+ self.assertRaises(SyntaxError, operator.itemgetter(42), C())
f = operator.itemgetter('name')
self.assertRaises(TypeError, f, a)
diff --git a/Lib/test/test_optparse.py b/Lib/test/test_optparse.py
index 9c52f86cfd..cdbbc9d549 100644
--- a/Lib/test/test_optparse.py
+++ b/Lib/test/test_optparse.py
@@ -109,7 +109,7 @@ Args were %(args)s.""" % locals ())
except expected_exception as err:
actual_message = str(err)
if isinstance(expected_message, retype):
- self.assert_(expected_message.search(actual_message),
+ self.assertTrue(expected_message.search(actual_message),
"""\
expected exception message pattern:
/%s/
@@ -165,7 +165,7 @@ and kwargs %(kwargs)r
sys.stdout = save_stdout
except InterceptedError as err:
- self.assert_(
+ self.assertTrue(
isinstance(output, str),
"expected output to be an ordinary string, not %r"
% type(output))
@@ -338,7 +338,7 @@ class TestOptionParser(BaseTest):
def test_get_option(self):
opt1 = self.parser.get_option("-v")
- self.assert_(isinstance(opt1, Option))
+ self.assertTrue(isinstance(opt1, Option))
self.assertEqual(opt1._short_opts, ["-v", "-n"])
self.assertEqual(opt1._long_opts, ["--verbose", "--noisy"])
self.assertEqual(opt1.action, "store_true")
@@ -349,33 +349,33 @@ class TestOptionParser(BaseTest):
opt2 = self.parser.get_option("--verbose")
opt3 = self.parser.get_option("-n")
opt4 = self.parser.get_option("--noisy")
- self.assert_(opt1 is opt2 is opt3 is opt4)
+ self.assertTrue(opt1 is opt2 is opt3 is opt4)
def test_has_option(self):
- self.assert_(self.parser.has_option("-v"))
- self.assert_(self.parser.has_option("--verbose"))
+ self.assertTrue(self.parser.has_option("-v"))
+ self.assertTrue(self.parser.has_option("--verbose"))
- def assert_removed(self):
- self.assert_(self.parser.get_option("-v") is None)
- self.assert_(self.parser.get_option("--verbose") is None)
- self.assert_(self.parser.get_option("-n") is None)
- self.assert_(self.parser.get_option("--noisy") is None)
+ def assertTrueremoved(self):
+ self.assertTrue(self.parser.get_option("-v") is None)
+ self.assertTrue(self.parser.get_option("--verbose") is None)
+ self.assertTrue(self.parser.get_option("-n") is None)
+ self.assertTrue(self.parser.get_option("--noisy") is None)
- self.failIf(self.parser.has_option("-v"))
- self.failIf(self.parser.has_option("--verbose"))
- self.failIf(self.parser.has_option("-n"))
- self.failIf(self.parser.has_option("--noisy"))
+ self.assertFalse(self.parser.has_option("-v"))
+ self.assertFalse(self.parser.has_option("--verbose"))
+ self.assertFalse(self.parser.has_option("-n"))
+ self.assertFalse(self.parser.has_option("--noisy"))
- self.assert_(self.parser.has_option("-q"))
- self.assert_(self.parser.has_option("--silent"))
+ self.assertTrue(self.parser.has_option("-q"))
+ self.assertTrue(self.parser.has_option("--silent"))
def test_remove_short_opt(self):
self.parser.remove_option("-n")
- self.assert_removed()
+ self.assertTrueremoved()
def test_remove_long_opt(self):
self.parser.remove_option("--verbose")
- self.assert_removed()
+ self.assertTrueremoved()
def test_remove_nonexistent(self):
self.assertRaises(self.parser.remove_option, ('foo',), None,
@@ -779,14 +779,14 @@ class TestBool(BaseTest):
{'verbose': 0},
[])
if hasattr(__builtins__, 'False'):
- self.failUnless(options.verbose is False)
+ self.assertTrue(options.verbose is False)
def test_bool_true(self):
(options, args) = self.assertParseOK(["-v"],
{'verbose': 1},
[])
if hasattr(__builtins__, 'True'):
- self.failUnless(options.verbose is True)
+ self.assertTrue(options.verbose is True)
def test_bool_flicker_on_and_off(self):
self.assertParseOK(["-qvq", "-q", "-v"],
@@ -992,7 +992,7 @@ class TestOptionGroup(BaseTest):
description="Some more options")
group.set_title("Bacon")
group.add_option("--bacon", type="int")
- self.assert_(self.parser.get_option_group("--bacon"), group)
+ self.assertTrue(self.parser.get_option_group("--bacon"), group)
# -- Test extending and parser.parse_args() ----------------------------
@@ -1088,15 +1088,15 @@ class TestCallback(BaseTest):
if opt == "-x":
self.assertEqual(option._short_opts, ["-x"])
self.assertEqual(option._long_opts, [])
- self.assert_(parser_ is self.parser)
- self.assert_(value is None)
+ self.assertTrue(parser_ is self.parser)
+ self.assertTrue(value is None)
self.assertEqual(vars(parser_.values), {'filename': None})
parser_.values.x = 42
elif opt == "--file":
self.assertEqual(option._short_opts, ["-f"])
self.assertEqual(option._long_opts, ["--file"])
- self.assert_(parser_ is self.parser)
+ self.assertTrue(parser_ is self.parser)
self.assertEqual(value, "foo")
self.assertEqual(vars(parser_.values), {'filename': None, 'x': 42})
@@ -1134,7 +1134,7 @@ class TestCallbackExtraArgs(BaseTest):
def process_tuple(self, option, opt, value, parser_, len, type):
self.assertEqual(len, 3)
- self.assert_(type is int)
+ self.assertTrue(type is int)
if opt == "-p":
self.assertEqual(value, "1,2,3")
@@ -1225,7 +1225,7 @@ class TestCallbackVarArgs(BaseTest):
option_list=options)
def variable_args(self, option, opt, value, parser):
- self.assert_(value is None)
+ self.assertTrue(value is None)
done = 0
value = []
rargs = parser.rargs
@@ -1281,7 +1281,7 @@ class ConflictBase(BaseTest):
class TestConflict(ConflictBase):
"""Use the default conflict resolution for Optik 1.2: error."""
- def assert_conflict_error(self, func):
+ def assertTrueconflict_error(self, func):
err = self.assertRaises(
func, ("-v", "--version"), {'action' : "callback",
'callback' : self.show_version,
@@ -1293,11 +1293,11 @@ class TestConflict(ConflictBase):
self.assertEqual(err.option_id, "-v/--version")
def test_conflict_error(self):
- self.assert_conflict_error(self.parser.add_option)
+ self.assertTrueconflict_error(self.parser.add_option)
def test_conflict_error_group(self):
group = OptionGroup(self.parser, "Group 1")
- self.assert_conflict_error(group.add_option)
+ self.assertTrueconflict_error(group.add_option)
def test_no_such_conflict_handler(self):
self.assertRaises(
@@ -1317,8 +1317,8 @@ class TestConflictResolve(ConflictBase):
verbose_opt = self.parser.get_option("--verbose")
version_opt = self.parser.get_option("--version")
- self.assert_(v_opt is version_opt)
- self.assert_(v_opt is not verbose_opt)
+ self.assertTrue(v_opt is version_opt)
+ self.assertTrue(v_opt is not verbose_opt)
self.assertEqual(v_opt._long_opts, ["--version"])
self.assertEqual(version_opt._short_opts, ["-v"])
self.assertEqual(version_opt._long_opts, ["--version"])
diff --git a/Lib/test/test_os.py b/Lib/test/test_os.py
index 0600cfc0ee..63f409e958 100644
--- a/Lib/test/test_os.py
+++ b/Lib/test/test_os.py
@@ -20,7 +20,7 @@ class FileTests(unittest.TestCase):
def test_access(self):
f = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
os.close(f)
- self.assert_(os.access(support.TESTFN, os.W_OK))
+ self.assertTrue(os.access(support.TESTFN, os.W_OK))
def test_closerange(self):
first = os.open(support.TESTFN, os.O_CREAT|os.O_RDWR)
@@ -85,7 +85,7 @@ class TemporaryFileTests(unittest.TestCase):
def check_tempfile(self, name):
# make sure it doesn't already exist:
- self.failIf(os.path.exists(name),
+ self.assertFalse(os.path.exists(name),
"file already exists for temporary file")
# make sure we can create the file
open(name, "w")
@@ -102,7 +102,7 @@ class TemporaryFileTests(unittest.TestCase):
self.check_tempfile(name)
name = os.tempnam(support.TESTFN, "pfx")
- self.assert_(os.path.basename(name)[:3] == "pfx")
+ self.assertTrue(os.path.basename(name)[:3] == "pfx")
self.check_tempfile(name)
def test_tmpfile(self):
@@ -151,7 +151,7 @@ class TemporaryFileTests(unittest.TestCase):
fp.seek(0,0)
s = fp.read()
fp.close()
- self.assert_(s == "foobar")
+ self.assertTrue(s == "foobar")
def test_tmpnam(self):
import sys
@@ -176,7 +176,7 @@ class TemporaryFileTests(unittest.TestCase):
# the root of the current drive. That's a terrible place to
# put temp files, and, depending on privileges, the user
# may not even be able to open a file in the root directory.
- self.failIf(os.path.exists(name),
+ self.assertFalse(os.path.exists(name),
"file already exists for temporary file")
else:
self.check_tempfile(name)
@@ -228,7 +228,7 @@ class StatAttributeTests(unittest.TestCase):
def trunc(x): return x
self.assertEquals(trunc(getattr(result, attr)),
result[getattr(stat, name)])
- self.assert_(attr in members)
+ self.assertTrue(attr in members)
try:
result[200]
@@ -520,7 +520,7 @@ class MakedirTests(unittest.TestCase):
os.makedirs(path)
# Try paths with a '.' in them
- self.failUnlessRaises(OSError, os.makedirs, os.curdir)
+ self.assertRaises(OSError, os.makedirs, os.curdir)
path = os.path.join(base, 'dir1', 'dir2', 'dir3', 'dir4', 'dir5', os.curdir)
os.makedirs(path)
path = os.path.join(base, 'dir1', os.curdir, 'dir2', 'dir3', 'dir4',
diff --git a/Lib/test/test_ossaudiodev.py b/Lib/test/test_ossaudiodev.py
index 603aea3f25..dda6137d19 100644
--- a/Lib/test/test_ossaudiodev.py
+++ b/Lib/test/test_ossaudiodev.py
@@ -58,7 +58,7 @@ class OSSAudioDevTests(unittest.TestCase):
dsp.fileno()
# Make sure the read-only attributes work.
- self.failIf(dsp.closed)
+ self.assertFalse(dsp.closed)
self.assertEqual(dsp.name, "/dev/dsp")
self.assertEqual(dsp.mode, "w", "bad dsp.mode: %r" % dsp.mode)
@@ -84,7 +84,7 @@ class OSSAudioDevTests(unittest.TestCase):
elapsed_time = t2 - t1
percent_diff = (abs(elapsed_time - expected_time) / expected_time) * 100
- self.failUnless(percent_diff <= 10.0,
+ self.assertTrue(percent_diff <= 10.0,
"elapsed time (%s) > 10%% off of expected time (%s)" %
(elapsed_time, expected_time))
@@ -133,7 +133,7 @@ class OSSAudioDevTests(unittest.TestCase):
]:
(fmt, channels, rate) = config
result = dsp.setparameters(fmt, channels, rate, False)
- self.failIfEqual(result, config,
+ self.assertNotEqual(result, config,
"unexpectedly got requested configuration")
try:
@@ -157,7 +157,7 @@ class OSSAudioDevTests(unittest.TestCase):
#self.set_bad_parameters(dsp)
finally:
dsp.close()
- self.failUnless(dsp.closed)
+ self.assertTrue(dsp.closed)
def test_main():
diff --git a/Lib/test/test_parser.py b/Lib/test/test_parser.py
index 340ae2f63a..9e5d5c1ea4 100644
--- a/Lib/test/test_parser.py
+++ b/Lib/test/test_parser.py
@@ -546,15 +546,15 @@ class STObjectTestCase(unittest.TestCase):
bottom = min(st1, st2, st3)
top = max(st1, st2, st3)
mid = sorted([st1, st2, st3])[1]
- self.assert_(bottom < mid)
- self.assert_(bottom < top)
- self.assert_(mid < top)
- self.assert_(bottom <= mid)
- self.assert_(bottom <= top)
- self.assert_(mid <= top)
- self.assert_(bottom <= bottom)
- self.assert_(mid <= mid)
- self.assert_(top <= top)
+ self.assertTrue(bottom < mid)
+ self.assertTrue(bottom < top)
+ self.assertTrue(mid < top)
+ self.assertTrue(bottom <= mid)
+ self.assertTrue(bottom <= top)
+ self.assertTrue(mid <= top)
+ self.assertTrue(bottom <= bottom)
+ self.assertTrue(mid <= mid)
+ self.assertTrue(top <= top)
# interaction with other types
self.assertEquals(st1 == 1588.602459, False)
self.assertEquals('spanish armada' != st2, True)
diff --git a/Lib/test/test_peepholer.py b/Lib/test/test_peepholer.py
index 1543f3b9c1..569650035c 100644
--- a/Lib/test/test_peepholer.py
+++ b/Lib/test/test_peepholer.py
@@ -25,9 +25,9 @@ class TestTranforms(unittest.TestCase):
del x
asm = disassemble(unot)
for elem in ('UNARY_NOT', 'POP_JUMP_IF_FALSE'):
- self.assert_(elem not in asm)
+ self.assertTrue(elem not in asm)
for elem in ('POP_JUMP_IF_TRUE',):
- self.assert_(elem in asm)
+ self.assertTrue(elem in asm)
def test_elim_inversion_of_is_or_in(self):
for line, elem in (
@@ -37,7 +37,7 @@ class TestTranforms(unittest.TestCase):
('not a not in b', '(in)',),
):
asm = dis_single(line)
- self.assert_(elem in asm)
+ self.assertTrue(elem in asm)
def test_global_as_constant(self):
# LOAD_GLOBAL None/True/False --> LOAD_CONST None/True/False
@@ -54,14 +54,14 @@ class TestTranforms(unittest.TestCase):
for func, name in ((f, 'None'), (g, 'True'), (h, 'False')):
asm = disassemble(func)
for elem in ('LOAD_GLOBAL',):
- self.assert_(elem not in asm)
+ self.assertTrue(elem not in asm)
for elem in ('LOAD_CONST', '('+name+')'):
- self.assert_(elem in asm)
+ self.assertTrue(elem in asm)
def f():
'Adding a docstring made this test fail in Py2.5.0'
return None
- self.assert_('LOAD_CONST' in disassemble(f))
- self.assert_('LOAD_GLOBAL' not in disassemble(f))
+ self.assertTrue('LOAD_CONST' in disassemble(f))
+ self.assertTrue('LOAD_GLOBAL' not in disassemble(f))
def test_while_one(self):
# Skip over: LOAD_CONST trueconst POP_JUMP_IF_FALSE xx
@@ -71,9 +71,9 @@ class TestTranforms(unittest.TestCase):
return list
asm = disassemble(f)
for elem in ('LOAD_CONST', 'POP_JUMP_IF_FALSE'):
- self.assert_(elem not in asm)
+ self.assertTrue(elem not in asm)
for elem in ('JUMP_ABSOLUTE',):
- self.assert_(elem in asm)
+ self.assertTrue(elem in asm)
def test_pack_unpack(self):
for line, elem in (
@@ -82,9 +82,9 @@ class TestTranforms(unittest.TestCase):
('a, b, c = a, b, c', 'ROT_THREE',),
):
asm = dis_single(line)
- self.assert_(elem in asm)
- self.assert_('BUILD_TUPLE' not in asm)
- self.assert_('UNPACK_TUPLE' not in asm)
+ self.assertTrue(elem in asm)
+ self.assertTrue('BUILD_TUPLE' not in asm)
+ self.assertTrue('UNPACK_TUPLE' not in asm)
def test_folding_of_tuples_of_constants(self):
for line, elem in (
@@ -95,8 +95,8 @@ class TestTranforms(unittest.TestCase):
('((1, 2), 3, 4)', '(((1, 2), 3, 4))'),
):
asm = dis_single(line)
- self.assert_(elem in asm)
- self.assert_('BUILD_TUPLE' not in asm)
+ self.assertTrue(elem in asm)
+ self.assertTrue('BUILD_TUPLE' not in asm)
# Bug 1053819: Tuple of constants misidentified when presented with:
# . . . opcode_with_arg 100 unary_opcode BUILD_TUPLE 1 . . .
@@ -134,17 +134,17 @@ class TestTranforms(unittest.TestCase):
('a = 13 | 7', '(15)'), # binary or
):
asm = dis_single(line)
- self.assert_(elem in asm, asm)
- self.assert_('BINARY_' not in asm)
+ self.assertTrue(elem in asm, asm)
+ self.assertTrue('BINARY_' not in asm)
# Verify that unfoldables are skipped
asm = dis_single('a=2+"b"')
- self.assert_('(2)' in asm)
- self.assert_("('b')" in asm)
+ self.assertTrue('(2)' in asm)
+ self.assertTrue("('b')" in asm)
# Verify that large sequences do not result from folding
asm = dis_single('a="x"*1000')
- self.assert_('(1000)' in asm)
+ self.assertTrue('(1000)' in asm)
def test_folding_of_unaryops_on_constants(self):
for line, elem in (
@@ -152,8 +152,8 @@ class TestTranforms(unittest.TestCase):
('~-2', '(1)'), # unary invert
):
asm = dis_single(line)
- self.assert_(elem in asm, asm)
- self.assert_('UNARY_' not in asm)
+ self.assertTrue(elem in asm, asm)
+ self.assertTrue('UNARY_' not in asm)
# Verify that unfoldables are skipped
for line, elem in (
@@ -161,16 +161,16 @@ class TestTranforms(unittest.TestCase):
('~"abc"', "('abc')"), # unary invert
):
asm = dis_single(line)
- self.assert_(elem in asm, asm)
- self.assert_('UNARY_' in asm)
+ self.assertTrue(elem in asm, asm)
+ self.assertTrue('UNARY_' in asm)
def test_elim_extra_return(self):
# RETURN LOAD_CONST None RETURN --> RETURN
def f(x):
return x
asm = disassemble(f)
- self.assert_('LOAD_CONST' not in asm)
- self.assert_('(None)' not in asm)
+ self.assertTrue('LOAD_CONST' not in asm)
+ self.assertTrue('(None)' not in asm)
self.assertEqual(asm.split().count('RETURN_VALUE'), 1)
def test_elim_jump_to_return(self):
@@ -178,8 +178,8 @@ class TestTranforms(unittest.TestCase):
def f(cond, true_value, false_value):
return true_value if cond else false_value
asm = disassemble(f)
- self.assert_('JUMP_FORWARD' not in asm)
- self.assert_('JUMP_ABSOLUTE' not in asm)
+ self.assertTrue('JUMP_FORWARD' not in asm)
+ self.assertTrue('JUMP_ABSOLUTE' not in asm)
self.assertEqual(asm.split().count('RETURN_VALUE'), 2)
def test_elim_jump_after_return1(self):
@@ -194,8 +194,8 @@ class TestTranforms(unittest.TestCase):
return 5
return 6
asm = disassemble(f)
- self.assert_('JUMP_FORWARD' not in asm)
- self.assert_('JUMP_ABSOLUTE' not in asm)
+ self.assertTrue('JUMP_FORWARD' not in asm)
+ self.assertTrue('JUMP_ABSOLUTE' not in asm)
self.assertEqual(asm.split().count('RETURN_VALUE'), 6)
def test_elim_jump_after_return2(self):
@@ -204,7 +204,7 @@ class TestTranforms(unittest.TestCase):
while 1:
if cond1: return 4
asm = disassemble(f)
- self.assert_('JUMP_FORWARD' not in asm)
+ self.assertTrue('JUMP_FORWARD' not in asm)
# There should be one jump for the while loop.
self.assertEqual(asm.split().count('JUMP_ABSOLUTE'), 1)
self.assertEqual(asm.split().count('RETURN_VALUE'), 2)
@@ -215,7 +215,7 @@ class TestTranforms(unittest.TestCase):
pass
return g
asm = disassemble(f)
- self.assert_('BINARY_ADD' not in asm)
+ self.assertTrue('BINARY_ADD' not in asm)
def test_main(verbose=None):
diff --git a/Lib/test/test_pep247.py b/Lib/test/test_pep247.py
index 733109a16e..da8f81690b 100644
--- a/Lib/test/test_pep247.py
+++ b/Lib/test/test_pep247.py
@@ -11,8 +11,8 @@ from test import support
class Pep247Test(unittest.TestCase):
def check_module(self, module, key=None):
- self.assert_(hasattr(module, 'digest_size'))
- self.assert_(module.digest_size is None or module.digest_size > 0)
+ self.assertTrue(hasattr(module, 'digest_size'))
+ self.assertTrue(module.digest_size is None or module.digest_size > 0)
self.check_object(module.new, module.digest_size, key)
def check_object(self, cls, digest_size, key):
@@ -31,7 +31,7 @@ class Pep247Test(unittest.TestCase):
obj3.update(b'string')
h2 = obj3.digest()
self.assertEquals(h1, h2)
- self.assert_(hasattr(obj1, 'digest_size'))
+ self.assertTrue(hasattr(obj1, 'digest_size'))
if digest_size is not None:
self.assertEquals(obj1.digest_size, digest_size)
diff --git a/Lib/test/test_pep277.py b/Lib/test/test_pep277.py
index e18f602469..11039acc32 100644
--- a/Lib/test/test_pep277.py
+++ b/Lib/test/test_pep277.py
@@ -82,8 +82,8 @@ class UnicodeFileTests(unittest.TestCase):
sys.getfilesystemencoding()))
sf2 = set("\\".join((str(support.TESTFN), f))
for f in f2)
- self.failUnlessEqual(len(f1), len(self.files))
- self.failUnlessEqual(sf2, set(self.files))
+ self.assertEqual(len(f1), len(self.files))
+ self.assertEqual(sf2, set(self.files))
def test_rename(self):
for name in self.files:
diff --git a/Lib/test/test_pep3120.py b/Lib/test/test_pep3120.py
index 81d15bc8f4..85da048a7d 100644
--- a/Lib/test/test_pep3120.py
+++ b/Lib/test/test_pep3120.py
@@ -19,7 +19,7 @@ class PEP3120Test(unittest.TestCase):
try:
import test.badsyntax_pep3120
except SyntaxError as msg:
- self.assert_(str(msg).find("Non-UTF-8 code starting with") >= 0)
+ self.assertTrue(str(msg).find("Non-UTF-8 code starting with") >= 0)
else:
self.fail("expected exception didn't occur")
diff --git a/Lib/test/test_pep352.py b/Lib/test/test_pep352.py
index 1481244fe4..b9645d5cf9 100644
--- a/Lib/test/test_pep352.py
+++ b/Lib/test/test_pep352.py
@@ -12,7 +12,7 @@ class ExceptionClassTests(unittest.TestCase):
inheritance hierarchy)"""
def test_builtins_new_style(self):
- self.failUnless(issubclass(Exception, object))
+ self.assertTrue(issubclass(Exception, object))
def verify_instance_interface(self, ins):
for attr in ("args", "__str__", "__repr__"):
@@ -38,7 +38,7 @@ class ExceptionClassTests(unittest.TestCase):
last_exc = getattr(builtins, superclass_name)
except AttributeError:
self.fail("base class %s not a built-in" % superclass_name)
- self.failUnless(superclass_name in exc_set,
+ self.assertTrue(superclass_name in exc_set,
'%s not found' % superclass_name)
exc_set.discard(superclass_name)
superclasses = [] # Loop will insert base exception
@@ -66,20 +66,20 @@ class ExceptionClassTests(unittest.TestCase):
elif last_depth > depth:
while superclasses[-1][0] >= depth:
superclasses.pop()
- self.failUnless(issubclass(exc, superclasses[-1][1]),
+ self.assertTrue(issubclass(exc, superclasses[-1][1]),
"%s is not a subclass of %s" % (exc.__name__,
superclasses[-1][1].__name__))
try: # Some exceptions require arguments; just skip them
self.verify_instance_interface(exc())
except TypeError:
pass
- self.failUnless(exc_name in exc_set)
+ self.assertTrue(exc_name in exc_set)
exc_set.discard(exc_name)
last_exc = exc
last_depth = depth
finally:
inheritance_tree.close()
- self.failUnlessEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
+ self.assertEqual(len(exc_set), 0, "%s not accounted for" % exc_set)
interface_tests = ("length", "args", "str", "repr")
diff --git a/Lib/test/test_pkg.py b/Lib/test/test_pkg.py
index 1064617f2d..0c568bb3b5 100644
--- a/Lib/test/test_pkg.py
+++ b/Lib/test/test_pkg.py
@@ -130,7 +130,7 @@ class TestPkg(unittest.TestCase):
self.assertEqual(subsub.__name__, "t2.sub.subsub")
self.assertEqual(sub.subsub.__name__, "t2.sub.subsub")
for name in ['spam', 'sub', 'subsub', 't2']:
- self.failUnless(locals()["name"], "Failed to import %s" % name)
+ self.assertTrue(locals()["name"], "Failed to import %s" % name)
import t2.sub
import t2.sub.subsub
@@ -140,7 +140,7 @@ class TestPkg(unittest.TestCase):
s = """
from t2 import *
- self.failUnless(dir(), ['self', 'sub'])
+ self.assertTrue(dir(), ['self', 'sub'])
"""
self.run_code(s)
@@ -258,25 +258,25 @@ class TestPkg(unittest.TestCase):
self.assertEqual(fixdir(dir(tas)),
['__doc__', '__file__', '__name__',
'__package__', '__path__'])
- self.failIf(t7)
+ self.assertFalse(t7)
from t7 import sub as subpar
self.assertEqual(fixdir(dir(subpar)),
['__doc__', '__file__', '__name__',
'__package__', '__path__'])
- self.failIf(t7)
- self.failIf(sub)
+ self.assertFalse(t7)
+ self.assertFalse(sub)
from t7.sub import subsub as subsubsub
self.assertEqual(fixdir(dir(subsubsub)),
['__doc__', '__file__', '__name__',
'__package__', '__path__', 'spam'])
- self.failIf(t7)
- self.failIf(sub)
- self.failIf(subsub)
+ self.assertFalse(t7)
+ self.assertFalse(sub)
+ self.assertFalse(subsub)
from t7.sub.subsub import spam as ham
self.assertEqual(ham, 1)
- self.failIf(t7)
- self.failIf(sub)
- self.failIf(subsub)
+ self.assertFalse(t7)
+ self.assertFalse(sub)
+ self.assertFalse(subsub)
def test_main():
diff --git a/Lib/test/test_pkgimport.py b/Lib/test/test_pkgimport.py
index eff7b5a25d..60f5c3255e 100644
--- a/Lib/test/test_pkgimport.py
+++ b/Lib/test/test_pkgimport.py
@@ -52,7 +52,7 @@ class TestImport(unittest.TestCase):
try: __import__(self.module_name)
except SyntaxError: pass
else: raise RuntimeError('Failed to induce SyntaxError')
- self.assert_(self.module_name not in sys.modules and
+ self.assertTrue(self.module_name not in sys.modules and
not hasattr(sys.modules[self.package_name], 'foo'))
# ...make up a variable name that isn't bound in __builtins__
diff --git a/Lib/test/test_platform.py b/Lib/test/test_platform.py
index 9bb5bddfc6..8b1815effa 100644
--- a/Lib/test/test_platform.py
+++ b/Lib/test/test_platform.py
@@ -125,12 +125,12 @@ class PlatformTest(unittest.TestCase):
def test_uname(self):
res = platform.uname()
- self.assert_(any(res))
+ self.assertTrue(any(res))
def test_java_ver(self):
res = platform.java_ver()
if sys.platform == 'java':
- self.assert_(all(res))
+ self.assertTrue(all(res))
def test_win32_ver(self):
res = platform.win32_ver()
@@ -148,7 +148,7 @@ class PlatformTest(unittest.TestCase):
real_ver = ln.strip().split()[-1]
break
fd.close()
- self.failIf(real_ver is None)
+ self.assertFalse(real_ver is None)
self.assertEquals(res[0], real_ver)
# res[1] claims to contain
diff --git a/Lib/test/test_poplib.py b/Lib/test/test_poplib.py
index ad00802a37..7f36115d06 100644
--- a/Lib/test/test_poplib.py
+++ b/Lib/test/test_poplib.py
@@ -251,7 +251,7 @@ if hasattr(poplib, 'POP3_SSL'):
self.client = poplib.POP3_SSL(self.server.host, self.server.port)
def test__all__(self):
- self.assert_('POP3_SSL' in poplib.__all__)
+ self.assertTrue('POP3_SSL' in poplib.__all__)
class TestTimeouts(TestCase):
diff --git a/Lib/test/test_posix.py b/Lib/test/test_posix.py
index 8d1bb59453..294b302f73 100644
--- a/Lib/test/test_posix.py
+++ b/Lib/test/test_posix.py
@@ -42,13 +42,13 @@ class PosixTester(unittest.TestCase):
def test_statvfs(self):
if hasattr(posix, 'statvfs'):
- self.assert_(posix.statvfs(os.curdir))
+ self.assertTrue(posix.statvfs(os.curdir))
def test_fstatvfs(self):
if hasattr(posix, 'fstatvfs'):
fp = open(support.TESTFN)
try:
- self.assert_(posix.fstatvfs(fp.fileno()))
+ self.assertTrue(posix.fstatvfs(fp.fileno()))
finally:
fp.close()
@@ -68,7 +68,7 @@ class PosixTester(unittest.TestCase):
fp = open(support.TESTFN)
try:
fd = posix.dup(fp.fileno())
- self.assert_(isinstance(fd, int))
+ self.assertTrue(isinstance(fd, int))
os.close(fd)
finally:
fp.close()
@@ -123,13 +123,13 @@ class PosixTester(unittest.TestCase):
if hasattr(posix, 'fstat'):
fp = open(support.TESTFN)
try:
- self.assert_(posix.fstat(fp.fileno()))
+ self.assertTrue(posix.fstat(fp.fileno()))
finally:
fp.close()
def test_stat(self):
if hasattr(posix, 'stat'):
- self.assert_(posix.stat(support.TESTFN))
+ self.assertTrue(posix.stat(support.TESTFN))
if hasattr(posix, 'chown'):
def test_chown(self):
@@ -165,21 +165,21 @@ class PosixTester(unittest.TestCase):
def test_lsdir(self):
if hasattr(posix, 'lsdir'):
- self.assert_(support.TESTFN in posix.lsdir(os.curdir))
+ self.assertTrue(support.TESTFN in posix.lsdir(os.curdir))
def test_access(self):
if hasattr(posix, 'access'):
- self.assert_(posix.access(support.TESTFN, os.R_OK))
+ self.assertTrue(posix.access(support.TESTFN, os.R_OK))
def test_umask(self):
if hasattr(posix, 'umask'):
old_mask = posix.umask(0)
- self.assert_(isinstance(old_mask, int))
+ self.assertTrue(isinstance(old_mask, int))
posix.umask(old_mask)
def test_strerror(self):
if hasattr(posix, 'strerror'):
- self.assert_(posix.strerror(0))
+ self.assertTrue(posix.strerror(0))
def test_pipe(self):
if hasattr(posix, 'pipe'):
diff --git a/Lib/test/test_posixpath.py b/Lib/test/test_posixpath.py
index eb918f4976..0efe3ff656 100644
--- a/Lib/test/test_posixpath.py
+++ b/Lib/test/test_posixpath.py
@@ -26,7 +26,7 @@ class PosixPathTest(unittest.TestCase):
safe_rmdir(support.TESTFN + suffix)
def assertIs(self, a, b):
- self.assert_(a is b)
+ self.assertTrue(a is b)
def test_normcase(self):
# Check that normcase() is idempotent
@@ -200,8 +200,8 @@ class PosixPathTest(unittest.TestCase):
for s1 in testlist:
for s2 in testlist:
p = posixpath.commonprefix([s1, s2])
- self.assert_(s1.startswith(p))
- self.assert_(s2.startswith(p))
+ self.assertTrue(s1.startswith(p))
+ self.assertTrue(s2.startswith(p))
if s1 != s2:
n = len(p)
self.assertNotEqual(s1[n:n+1], s2[n:n+1])
@@ -229,7 +229,7 @@ class PosixPathTest(unittest.TestCase):
f.close()
self.assertEqual(d, b"foobar")
- self.assert_(
+ self.assertTrue(
posixpath.getctime(support.TESTFN) <=
posixpath.getmtime(support.TESTFN)
)
@@ -402,8 +402,8 @@ class PosixPathTest(unittest.TestCase):
except ImportError:
pass
else:
- self.assert_(isinstance(posixpath.expanduser("~/"), str))
- self.assert_(isinstance(posixpath.expanduser(b"~/"), bytes))
+ self.assertTrue(isinstance(posixpath.expanduser("~/"), str))
+ self.assertTrue(isinstance(posixpath.expanduser(b"~/"), bytes))
# if home directory == root directory, this test makes no sense
if posixpath.expanduser("~") != '/':
self.assertEqual(
@@ -414,10 +414,10 @@ class PosixPathTest(unittest.TestCase):
posixpath.expanduser(b"~") + b"/",
posixpath.expanduser(b"~/")
)
- self.assert_(isinstance(posixpath.expanduser("~root/"), str))
- self.assert_(isinstance(posixpath.expanduser("~foo/"), str))
- self.assert_(isinstance(posixpath.expanduser(b"~root/"), bytes))
- self.assert_(isinstance(posixpath.expanduser(b"~foo/"), bytes))
+ self.assertTrue(isinstance(posixpath.expanduser("~root/"), str))
+ self.assertTrue(isinstance(posixpath.expanduser("~foo/"), str))
+ self.assertTrue(isinstance(posixpath.expanduser(b"~root/"), bytes))
+ self.assertTrue(isinstance(posixpath.expanduser(b"~foo/"), bytes))
with support.EnvironmentVarGuard() as env:
env['HOME'] = '/'
@@ -481,14 +481,14 @@ class PosixPathTest(unittest.TestCase):
self.assertRaises(TypeError, posixpath.normpath)
def test_abspath(self):
- self.assert_("foo" in posixpath.abspath("foo"))
- self.assert_(b"foo" in posixpath.abspath(b"foo"))
+ self.assertTrue("foo" in posixpath.abspath("foo"))
+ self.assertTrue(b"foo" in posixpath.abspath(b"foo"))
self.assertRaises(TypeError, posixpath.abspath)
def test_realpath(self):
- self.assert_("foo" in realpath("foo"))
- self.assert_(b"foo" in realpath(b"foo"))
+ self.assertTrue("foo" in realpath("foo"))
+ self.assertTrue(b"foo" in realpath(b"foo"))
self.assertRaises(TypeError, posixpath.realpath)
if hasattr(os, "symlink"):
diff --git a/Lib/test/test_pprint.py b/Lib/test/test_pprint.py
index 1469ff0f7b..3d13b6064b 100644
--- a/Lib/test/test_pprint.py
+++ b/Lib/test/test_pprint.py
@@ -34,7 +34,7 @@ class QueryTestCase(unittest.TestCase):
def test_basic(self):
# Verify .isrecursive() and .isreadable() w/o recursion
- verify = self.assert_
+ verify = self.assertTrue
pp = pprint.PrettyPrinter()
for safe in (2, 2.0, 2j, "abc", [3], (2,2), {3: 3}, "yaddayadda",
self.a, self.b):
@@ -57,7 +57,7 @@ class QueryTestCase(unittest.TestCase):
self.d = {}
self.d[0] = self.d[1] = self.d[2] = self.d
- verify = self.assert_
+ verify = self.assertTrue
pp = pprint.PrettyPrinter()
for icky in self.a, self.b, self.d, (self.d, self.d):
@@ -85,7 +85,7 @@ class QueryTestCase(unittest.TestCase):
def test_unreadable(self):
# Not recursive but not readable anyway
- verify = self.assert_
+ verify = self.assertTrue
pp = pprint.PrettyPrinter()
for unreadable in type(3), pprint, pprint.isrecursive:
# module-level convenience functions
@@ -108,7 +108,7 @@ class QueryTestCase(unittest.TestCase):
# it sorted a dict display if and only if the display required
# multiple lines. For that reason, dicts with more than one element
# aren't tested here.
- verify = self.assert_
+ verify = self.assertTrue
for simple in (0, 0, 0+0j, 0.0, "", b"",
(), tuple2(), tuple3(),
[], list2(), list3(),
diff --git a/Lib/test/test_property.py b/Lib/test/test_property.py
index 4ce1da2b69..d9469d97d0 100644
--- a/Lib/test/test_property.py
+++ b/Lib/test/test_property.py
@@ -86,8 +86,8 @@ class PropertyTests(unittest.TestCase):
self.assertEqual(base.spam, 10)
self.assertEqual(base._spam, 10)
delattr(base, "spam")
- self.assert_(not hasattr(base, "spam"))
- self.assert_(not hasattr(base, "_spam"))
+ self.assertTrue(not hasattr(base, "spam"))
+ self.assertTrue(not hasattr(base, "_spam"))
base.spam = 20
self.assertEqual(base.spam, 20)
self.assertEqual(base._spam, 20)
diff --git a/Lib/test/test_pwd.py b/Lib/test/test_pwd.py
index 450306c45a..406578a70d 100644
--- a/Lib/test/test_pwd.py
+++ b/Lib/test/test_pwd.py
@@ -13,19 +13,19 @@ class PwdTest(unittest.TestCase):
for e in entries:
self.assertEqual(len(e), 7)
self.assertEqual(e[0], e.pw_name)
- self.assert_(isinstance(e.pw_name, str))
+ self.assertTrue(isinstance(e.pw_name, str))
self.assertEqual(e[1], e.pw_passwd)
- self.assert_(isinstance(e.pw_passwd, str))
+ self.assertTrue(isinstance(e.pw_passwd, str))
self.assertEqual(e[2], e.pw_uid)
- self.assert_(isinstance(e.pw_uid, int))
+ self.assertTrue(isinstance(e.pw_uid, int))
self.assertEqual(e[3], e.pw_gid)
- self.assert_(isinstance(e.pw_gid, int))
+ self.assertTrue(isinstance(e.pw_gid, int))
self.assertEqual(e[4], e.pw_gecos)
- self.assert_(isinstance(e.pw_gecos, str))
+ self.assertTrue(isinstance(e.pw_gecos, str))
self.assertEqual(e[5], e.pw_dir)
- self.assert_(isinstance(e.pw_dir, str))
+ self.assertTrue(isinstance(e.pw_dir, str))
self.assertEqual(e[6], e.pw_shell)
- self.assert_(isinstance(e.pw_shell, str))
+ self.assertTrue(isinstance(e.pw_shell, str))
# The following won't work, because of duplicate entries
# for one uid
@@ -43,8 +43,8 @@ class PwdTest(unittest.TestCase):
for e in entries:
if not e[0] or e[0] == '+':
continue # skip NIS entries etc.
- self.assert_(pwd.getpwnam(e.pw_name) in entriesbyname[e.pw_name])
- self.assert_(pwd.getpwuid(e.pw_uid) in entriesbyuid[e.pw_uid])
+ self.assertTrue(pwd.getpwnam(e.pw_name) in entriesbyname[e.pw_name])
+ self.assertTrue(pwd.getpwuid(e.pw_uid) in entriesbyuid[e.pw_uid])
def test_errors(self):
self.assertRaises(TypeError, pwd.getpwuid)
diff --git a/Lib/test/test_pyclbr.py b/Lib/test/test_pyclbr.py
index 9438c7b14c..30d8249634 100644
--- a/Lib/test/test_pyclbr.py
+++ b/Lib/test/test_pyclbr.py
@@ -31,7 +31,7 @@ class PyclbrTest(TestCase):
''' succeed iff hasattr(obj,attr) or attr in ignore. '''
if attr in ignore: return
if not hasattr(obj, attr): print("???", attr)
- self.failUnless(hasattr(obj, attr),
+ self.assertTrue(hasattr(obj, attr),
'expected hasattr(%r, %r)' % (obj, attr))
@@ -40,7 +40,7 @@ class PyclbrTest(TestCase):
if key in ignore: return
if key not in obj:
print("***",key, file=sys.stderr)
- self.failUnless(key in obj, "%r in %r" % (key, obj))
+ self.assertTrue(key in obj, "%r in %r" % (key, obj))
def assertEqualsOrIgnored(self, a, b, ignore):
''' succeed iff a == b or a in ignore or b in ignore '''
@@ -84,12 +84,12 @@ class PyclbrTest(TestCase):
self.assertHasattr(module, name, ignore)
py_item = getattr(module, name)
if isinstance(value, pyclbr.Function):
- self.assert_(isinstance(py_item, (FunctionType, BuiltinFunctionType)))
+ self.assertTrue(isinstance(py_item, (FunctionType, BuiltinFunctionType)))
if py_item.__module__ != moduleName:
continue # skip functions that came from somewhere else
self.assertEquals(py_item.__module__, value.module)
else:
- self.failUnless(isinstance(py_item, type))
+ self.assertTrue(isinstance(py_item, type))
if py_item.__module__ != moduleName:
continue # skip classes that came from somewhere else
diff --git a/Lib/test/test_pydoc.py b/Lib/test/test_pydoc.py
index 00a2ada6c5..76822afe38 100644
--- a/Lib/test/test_pydoc.py
+++ b/Lib/test/test_pydoc.py
@@ -309,7 +309,7 @@ class TestDescriptions(unittest.TestCase):
# Check that pydocfodder module can be described
from test import pydocfodder
doc = pydoc.render_doc(pydocfodder)
- self.assert_("pydocfodder" in doc)
+ self.assertTrue("pydocfodder" in doc)
def test_classic_class(self):
class C: "Classic class"
@@ -317,7 +317,7 @@ class TestDescriptions(unittest.TestCase):
self.assertEqual(pydoc.describe(C), 'class C')
self.assertEqual(pydoc.describe(c), 'C')
expected = 'C in module %s' % __name__
- self.assert_(expected in pydoc.render_doc(c))
+ self.assertTrue(expected in pydoc.render_doc(c))
def test_class(self):
class C(object): "New-style class"
@@ -326,7 +326,7 @@ class TestDescriptions(unittest.TestCase):
self.assertEqual(pydoc.describe(C), 'class C')
self.assertEqual(pydoc.describe(c), 'C')
expected = 'C in module %s object' % __name__
- self.assert_(expected in pydoc.render_doc(c))
+ self.assertTrue(expected in pydoc.render_doc(c))
def test_main():
diff --git a/Lib/test/test_queue.py b/Lib/test/test_queue.py
index 22cdcad1ef..95f80accfe 100644
--- a/Lib/test/test_queue.py
+++ b/Lib/test/test_queue.py
@@ -103,12 +103,12 @@ class BaseQueueTest(unittest.TestCase, BlockingTestMixin):
"Didn't seem to queue the correct data!")
for i in range(QUEUE_SIZE-1):
q.put(i)
- self.assert_(q.qsize(), "Queue should not be empty")
- self.assert_(not qfull(q), "Queue should not be full")
+ self.assertTrue(q.qsize(), "Queue should not be empty")
+ self.assertTrue(not qfull(q), "Queue should not be full")
last = 2 * QUEUE_SIZE
full = 3 * 2 * QUEUE_SIZE
q.put(last)
- self.assert_(qfull(q), "Queue should be full")
+ self.assertTrue(qfull(q), "Queue should be full")
try:
q.put(full, block=0)
self.fail("Didn't appear to block with a full queue")
@@ -125,7 +125,7 @@ class BaseQueueTest(unittest.TestCase, BlockingTestMixin):
# Empty it
for i in range(QUEUE_SIZE):
q.get()
- self.assert_(not q.qsize(), "Queue should be empty")
+ self.assertTrue(not q.qsize(), "Queue should be empty")
try:
q.get(block=0)
self.fail("Didn't appear to block with an empty queue")
@@ -247,7 +247,7 @@ class FailingQueueTest(unittest.TestCase, BlockingTestMixin):
except FailingQueueException:
pass
q.put("last")
- self.assert_(qfull(q), "Queue should be full")
+ self.assertTrue(qfull(q), "Queue should be full")
# Test a failing blocking put
q.fail_next_put = True
try:
@@ -269,17 +269,17 @@ class FailingQueueTest(unittest.TestCase, BlockingTestMixin):
# Check the Queue isn't damaged.
# put failed, but get succeeded - re-add
q.put("last")
- self.assert_(qfull(q), "Queue should be full")
+ self.assertTrue(qfull(q), "Queue should be full")
q.get()
- self.assert_(not qfull(q), "Queue should not be full")
+ self.assertTrue(not qfull(q), "Queue should not be full")
q.put("last")
- self.assert_(qfull(q), "Queue should be full")
+ self.assertTrue(qfull(q), "Queue should be full")
# Test a blocking put
self.do_blocking_test(q.put, ("full",), q.get, ())
# Empty it
for i in range(QUEUE_SIZE):
q.get()
- self.assert_(not q.qsize(), "Queue should be empty")
+ self.assertTrue(not q.qsize(), "Queue should be empty")
q.put("first")
q.fail_next_get = True
try:
@@ -287,16 +287,16 @@ class FailingQueueTest(unittest.TestCase, BlockingTestMixin):
self.fail("The queue didn't fail when it should have")
except FailingQueueException:
pass
- self.assert_(q.qsize(), "Queue should not be empty")
+ self.assertTrue(q.qsize(), "Queue should not be empty")
q.fail_next_get = True
try:
q.get(timeout=0.1)
self.fail("The queue didn't fail when it should have")
except FailingQueueException:
pass
- self.assert_(q.qsize(), "Queue should not be empty")
+ self.assertTrue(q.qsize(), "Queue should not be empty")
q.get()
- self.assert_(not q.qsize(), "Queue should be empty")
+ self.assertTrue(not q.qsize(), "Queue should be empty")
q.fail_next_get = True
try:
self.do_exceptional_blocking_test(q.get, (), q.put, ('empty',),
@@ -305,9 +305,9 @@ class FailingQueueTest(unittest.TestCase, BlockingTestMixin):
except FailingQueueException:
pass
# put succeeded, but get failed.
- self.assert_(q.qsize(), "Queue should not be empty")
+ self.assertTrue(q.qsize(), "Queue should not be empty")
q.get()
- self.assert_(not q.qsize(), "Queue should be empty")
+ self.assertTrue(not q.qsize(), "Queue should be empty")
def test_failing_queue(self):
# Test to make sure a queue is functioning correctly.
diff --git a/Lib/test/test_raise.py b/Lib/test/test_raise.py
index 5a63b86850..ff4800b954 100644
--- a/Lib/test/test_raise.py
+++ b/Lib/test/test_raise.py
@@ -28,7 +28,7 @@ class TestRaise(unittest.TestCase):
try:
raise
except RuntimeError as e:
- self.failUnless("No active exception" in str(e))
+ self.assertTrue("No active exception" in str(e))
else:
self.fail("No exception raised")
@@ -40,7 +40,7 @@ class TestRaise(unittest.TestCase):
exc1 = e
raise
except IndexError as exc2:
- self.failUnless(exc1 is exc2)
+ self.assertTrue(exc1 is exc2)
else:
self.fail("No exception raised")
@@ -127,7 +127,7 @@ class TestCause(unittest.TestCase):
try:
raise IndexError from 5
except TypeError as e:
- self.failUnless("exception cause" in str(e))
+ self.assertTrue("exception cause" in str(e))
else:
self.fail("No exception raised")
@@ -135,7 +135,7 @@ class TestCause(unittest.TestCase):
try:
raise IndexError from KeyError
except IndexError as e:
- self.failUnless(isinstance(e.__cause__, KeyError))
+ self.assertTrue(isinstance(e.__cause__, KeyError))
else:
self.fail("No exception raised")
@@ -144,7 +144,7 @@ class TestCause(unittest.TestCase):
try:
raise IndexError from cause
except IndexError as e:
- self.failUnless(e.__cause__ is cause)
+ self.assertTrue(e.__cause__ is cause)
else:
self.fail("No exception raised")
@@ -166,7 +166,7 @@ class TestTraceback(unittest.TestCase):
try:
raise IndexError()
except IndexError as e:
- self.failUnless(isinstance(e.__traceback__, types.TracebackType))
+ self.assertTrue(isinstance(e.__traceback__, types.TracebackType))
else:
self.fail("No exception raised")
@@ -203,7 +203,7 @@ class TestContext(unittest.TestCase):
raise OSError()
except OSError as e:
self.assertNotEqual(e.__context__, context)
- self.failUnless(isinstance(e.__context__, context))
+ self.assertTrue(isinstance(e.__context__, context))
else:
self.fail("No exception raised")
@@ -216,7 +216,7 @@ class TestContext(unittest.TestCase):
raise OSError
except OSError as e:
self.assertNotEqual(e.__context__, context)
- self.failUnless(isinstance(e.__context__, context))
+ self.assertTrue(isinstance(e.__context__, context))
else:
self.fail("No exception raised")
@@ -227,7 +227,7 @@ class TestContext(unittest.TestCase):
except:
raise OSError
except OSError as e:
- self.failUnless(isinstance(e.__context__, ZeroDivisionError))
+ self.assertTrue(isinstance(e.__context__, ZeroDivisionError))
else:
self.fail("No exception raised")
@@ -238,7 +238,7 @@ class TestContext(unittest.TestCase):
except:
xyzzy
except NameError as e:
- self.failUnless(isinstance(e.__context__, ZeroDivisionError))
+ self.assertTrue(isinstance(e.__context__, ZeroDivisionError))
else:
self.fail("No exception raised")
@@ -249,7 +249,7 @@ class TestContext(unittest.TestCase):
finally:
raise OSError
except OSError as e:
- self.failUnless(e.__context__ is None)
+ self.assertTrue(e.__context__ is None)
else:
self.fail("No exception raised")
@@ -260,7 +260,7 @@ class TestContext(unittest.TestCase):
finally:
raise OSError
except OSError as e:
- self.failUnless(isinstance(e.__context__, ZeroDivisionError))
+ self.assertTrue(isinstance(e.__context__, ZeroDivisionError))
else:
self.fail("No exception raised")
@@ -274,7 +274,7 @@ class TestContext(unittest.TestCase):
with ContextManager():
1/0
except NameError as e:
- self.failUnless(isinstance(e.__context__, ZeroDivisionError))
+ self.assertTrue(isinstance(e.__context__, ZeroDivisionError))
else:
self.fail("No exception raised")
@@ -286,7 +286,7 @@ class TestContext(unittest.TestCase):
except ZeroDivisionError as e:
raise e
except ZeroDivisionError as e:
- self.failUnless(e.__context__ is None, e.__context__)
+ self.assertTrue(e.__context__ is None, e.__context__)
def test_reraise_cycle_broken(self):
# Non-trivial context cycles (through re-raising a previous exception)
@@ -300,7 +300,7 @@ class TestContext(unittest.TestCase):
except ZeroDivisionError:
raise a
except NameError as e:
- self.failUnless(e.__context__.__context__ is None)
+ self.assertTrue(e.__context__.__context__ is None)
def test_3118(self):
# deleting the generator caused the __context__ to be cleared
@@ -320,7 +320,7 @@ class TestContext(unittest.TestCase):
del g
raise KeyError
except Exception as e:
- self.assert_(isinstance(e.__context__, ValueError))
+ self.assertTrue(isinstance(e.__context__, ValueError))
f()
@@ -344,7 +344,7 @@ class TestContext(unittest.TestCase):
raise TypeError
except Exception as e:
self.assertNotEqual(e.__context__, None)
- self.assert_(isinstance(e.__context__, AttributeError))
+ self.assertTrue(isinstance(e.__context__, AttributeError))
with support.captured_output("stderr"):
f()
diff --git a/Lib/test/test_random.py b/Lib/test/test_random.py
index f2af1969d4..df07b76c0e 100644
--- a/Lib/test/test_random.py
+++ b/Lib/test/test_random.py
@@ -52,7 +52,7 @@ class TestBasicOps(unittest.TestCase):
self.assertEqual(len(s), k)
uniq = set(s)
self.assertEqual(len(uniq), k)
- self.failUnless(uniq <= set(population))
+ self.assertTrue(uniq <= set(population))
self.assertEqual(self.gen.sample([], 0), []) # test edge case N==k==0
def test_sample_distribution(self):
@@ -161,7 +161,7 @@ class SystemRandom_TestBasicOps(TestBasicOps):
cum = 0
for i in range(100):
r = self.gen.randrange(span)
- self.assert_(0 <= r < span)
+ self.assertTrue(0 <= r < span)
cum |= r
self.assertEqual(cum, span-1)
@@ -171,7 +171,7 @@ class SystemRandom_TestBasicOps(TestBasicOps):
stop = self.gen.randrange(2 ** (i-2))
if stop <= start:
return
- self.assert_(start <= self.gen.randrange(start, stop) < stop)
+ self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
def test_rangelimits(self):
for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
@@ -181,7 +181,7 @@ class SystemRandom_TestBasicOps(TestBasicOps):
def test_genrandbits(self):
# Verify ranges
for k in range(1, 1000):
- self.assert_(0 <= self.gen.getrandbits(k) < 2**k)
+ self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
# Verify all bits active
getbits = self.gen.getrandbits
@@ -211,13 +211,13 @@ class SystemRandom_TestBasicOps(TestBasicOps):
n += n - 1 # check 1 below the next power of two
k = int(1.00001 + _log(n, 2))
- self.assert_(k in [numbits, numbits+1])
- self.assert_(2**k > n > 2**(k-2))
+ self.assertTrue(k in [numbits, numbits+1])
+ self.assertTrue(2**k > n > 2**(k-2))
n -= n >> 15 # check a little farther below the next power of two
k = int(1.00001 + _log(n, 2))
self.assertEqual(k, numbits) # note the stronger assertion
- self.assert_(2**k > n > 2**(k-1)) # note the stronger assertion
+ self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
class MersenneTwister_TestBasicOps(TestBasicOps):
@@ -313,7 +313,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps):
cum = 0
for i in range(100):
r = self.gen.randrange(span)
- self.assert_(0 <= r < span)
+ self.assertTrue(0 <= r < span)
cum |= r
self.assertEqual(cum, span-1)
@@ -323,7 +323,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps):
stop = self.gen.randrange(2 ** (i-2))
if stop <= start:
return
- self.assert_(start <= self.gen.randrange(start, stop) < stop)
+ self.assertTrue(start <= self.gen.randrange(start, stop) < stop)
def test_rangelimits(self):
for start, stop in [(-2,0), (-(2**60)-2,-(2**60)), (2**60,2**60+2)]:
@@ -337,7 +337,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps):
97904845777343510404718956115)
# Verify ranges
for k in range(1, 1000):
- self.assert_(0 <= self.gen.getrandbits(k) < 2**k)
+ self.assertTrue(0 <= self.gen.getrandbits(k) < 2**k)
# Verify all bits active
getbits = self.gen.getrandbits
@@ -367,20 +367,20 @@ class MersenneTwister_TestBasicOps(TestBasicOps):
n += n - 1 # check 1 below the next power of two
k = int(1.00001 + _log(n, 2))
- self.assert_(k in [numbits, numbits+1])
- self.assert_(2**k > n > 2**(k-2))
+ self.assertTrue(k in [numbits, numbits+1])
+ self.assertTrue(2**k > n > 2**(k-2))
n -= n >> 15 # check a little farther below the next power of two
k = int(1.00001 + _log(n, 2))
self.assertEqual(k, numbits) # note the stronger assertion
- self.assert_(2**k > n > 2**(k-1)) # note the stronger assertion
+ self.assertTrue(2**k > n > 2**(k-1)) # note the stronger assertion
def test_randrange_bug_1590891(self):
start = 1000000000000
stop = -100000000000000000000
step = -200
x = self.gen.randrange(start, stop, step)
- self.assert_(stop < x <= start)
+ self.assertTrue(stop < x <= start)
self.assertEqual((x+stop)%step, 0)
def gamma(z, sqrt2pi=(2.0*pi)**0.5):
@@ -458,7 +458,7 @@ class TestModule(unittest.TestCase):
def test__all__(self):
# tests validity but not completeness of the __all__ list
- self.failUnless(set(random.__all__) <= set(dir(random)))
+ self.assertTrue(set(random.__all__) <= set(dir(random)))
def test_random_subclass_with_kwargs(self):
# SF bug #1486663 -- this used to erroneously raise a TypeError
diff --git a/Lib/test/test_range.py b/Lib/test/test_range.py
index 7650103bd0..24836d0cf7 100644
--- a/Lib/test/test_range.py
+++ b/Lib/test/test_range.py
@@ -26,18 +26,18 @@ class RangeTest(unittest.TestCase):
self.assertEqual(list(range(a+4, a, -2)), [a+4, a+2])
seq = list(range(a, b, c))
- self.assert_(a in seq)
- self.assert_(b not in seq)
+ self.assertTrue(a in seq)
+ self.assertTrue(b not in seq)
self.assertEqual(len(seq), 2)
seq = list(range(b, a, -c))
- self.assert_(b in seq)
- self.assert_(a not in seq)
+ self.assertTrue(b in seq)
+ self.assertTrue(a not in seq)
self.assertEqual(len(seq), 2)
seq = list(range(-a, -b, -c))
- self.assert_(-a in seq)
- self.assert_(-b not in seq)
+ self.assertTrue(-a in seq)
+ self.assertTrue(-b not in seq)
self.assertEqual(len(seq), 2)
self.assertRaises(TypeError, range)
diff --git a/Lib/test/test_re.py b/Lib/test/test_re.py
index 11fff7801c..fa75fd04c1 100644
--- a/Lib/test/test_re.py
+++ b/Lib/test/test_re.py
@@ -585,7 +585,7 @@ class ReTests(unittest.TestCase):
[":", "::", ":::"])
def test_bug_926075(self):
- self.assert_(re.compile('bug_926075') is not
+ self.assertTrue(re.compile('bug_926075') is not
re.compile(b'bug_926075'))
def test_bug_931848(self):
diff --git a/Lib/test/test_reprlib.py b/Lib/test/test_reprlib.py
index 8bd0ccf911..12e207beaf 100644
--- a/Lib/test/test_reprlib.py
+++ b/Lib/test/test_reprlib.py
@@ -123,12 +123,12 @@ class ReprTests(unittest.TestCase):
eq(r(i3), ("<ClassWithFailingRepr instance at %x>"%id(i3)))
s = r(ClassWithFailingRepr)
- self.failUnless(s.startswith("<class "))
- self.failUnless(s.endswith(">"))
- self.failUnless(s.find("...") in [12, 13])
+ self.assertTrue(s.startswith("<class "))
+ self.assertTrue(s.endswith(">"))
+ self.assertTrue(s.find("...") in [12, 13])
def test_lambda(self):
- self.failUnless(repr(lambda x: x).startswith(
+ self.assertTrue(repr(lambda x: x).startswith(
"<function <lambda"))
# XXX anonymous functions? see func_repr
@@ -137,7 +137,7 @@ class ReprTests(unittest.TestCase):
# Functions
eq(repr(hash), '<built-in function hash>')
# Methods
- self.failUnless(repr(''.split).startswith(
+ self.assertTrue(repr(''.split).startswith(
'<built-in method split of str object at 0x'))
def test_range(self):
@@ -178,9 +178,9 @@ class ReprTests(unittest.TestCase):
class C:
def foo(cls): pass
x = staticmethod(C.foo)
- self.failUnless(repr(x).startswith('<staticmethod object at 0x'))
+ self.assertTrue(repr(x).startswith('<staticmethod object at 0x'))
x = classmethod(C.foo)
- self.failUnless(repr(x).startswith('<classmethod object at 0x'))
+ self.assertTrue(repr(x).startswith('<classmethod object at 0x'))
def test_unsortable(self):
# Repr.repr() used to call sorted() on sets, frozensets and dicts
@@ -267,7 +267,7 @@ class baz:
''')
from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import baz
ibaz = baz.baz()
- self.failUnless(repr(ibaz).startswith(
+ self.assertTrue(repr(ibaz).startswith(
"<%s.baz object at 0x" % baz.__name__))
def test_method(self):
@@ -278,11 +278,11 @@ class aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
''')
from areallylongpackageandmodulenametotestreprtruncation.areallylongpackageandmodulenametotestreprtruncation import qux
# Unbound methods first
- self.failUnless(repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod).startswith(
+ self.assertTrue(repr(qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod).startswith(
'<function amethod'))
# Bound method next
iqux = qux.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa()
- self.failUnless(repr(iqux.amethod).startswith(
+ self.assertTrue(repr(iqux.amethod).startswith(
'<bound method aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa.amethod of <%s.aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa object at 0x' \
% (qux.__name__,) ))
diff --git a/Lib/test/test_richcmp.py b/Lib/test/test_richcmp.py
index 72e636d87d..a788c60dc4 100644
--- a/Lib/test/test_richcmp.py
+++ b/Lib/test/test_richcmp.py
@@ -106,7 +106,7 @@ class VectorTest(unittest.TestCase):
self.assertEqual(len(realres), len(expres))
for i in range(len(realres)):
# results are bool, so we can use "is" here
- self.assert_(realres[i] is expres[i])
+ self.assertTrue(realres[i] is expres[i])
def test_mixed(self):
# check that comparisons involving Vector objects
@@ -163,7 +163,7 @@ class NumberTest(unittest.TestCase):
for op in opmap[opname]:
realres = op(ta, tb)
realres = getattr(realres, "x", realres)
- self.assert_(realres is expres)
+ self.assertTrue(realres is expres)
def test_values(self):
# check all operators and all comparison results
@@ -237,8 +237,8 @@ class MiscTest(unittest.TestCase):
b.append(17)
# Even recursive lists of different lengths are different,
# but they cannot be ordered
- self.assert_(not (a == b))
- self.assert_(a != b)
+ self.assertTrue(not (a == b))
+ self.assertTrue(a != b)
self.assertRaises(RuntimeError, operator.lt, a, b)
self.assertRaises(RuntimeError, operator.le, a, b)
self.assertRaises(RuntimeError, operator.gt, a, b)
@@ -248,9 +248,9 @@ class MiscTest(unittest.TestCase):
self.assertRaises(RuntimeError, operator.ne, a, b)
a.insert(0, 11)
b.insert(0, 12)
- self.assert_(not (a == b))
- self.assert_(a != b)
- self.assert_(a < b)
+ self.assertTrue(not (a == b))
+ self.assertTrue(a != b)
+ self.assertTrue(a < b)
class DictTest(unittest.TestCase):
@@ -272,7 +272,7 @@ class DictTest(unittest.TestCase):
self.assertEqual(imag1a, imag1a)
self.assertEqual(imag1a, imag1b)
self.assertEqual(imag2, imag2)
- self.assert_(imag1a != imag2)
+ self.assertTrue(imag1a != imag2)
for opname in ("lt", "le", "gt", "ge"):
for op in opmap[opname]:
self.assertRaises(TypeError, op, imag1a, imag2)
@@ -280,7 +280,7 @@ class DictTest(unittest.TestCase):
class ListTest(unittest.TestCase):
def assertIs(self, a, b):
- self.assert_(a is b)
+ self.assertTrue(a is b)
def test_coverage(self):
# exercise all comparisons for lists
diff --git a/Lib/test/test_robotparser.py b/Lib/test/test_robotparser.py
index 9c47e31e0d..cc8b3900e4 100644
--- a/Lib/test/test_robotparser.py
+++ b/Lib/test/test_robotparser.py
@@ -22,9 +22,9 @@ class RobotTestCase(unittest.TestCase):
url = self.url
agent = self.agent
if self.good:
- self.failUnless(self.parser.can_fetch(agent, url))
+ self.assertTrue(self.parser.can_fetch(agent, url))
else:
- self.failIf(self.parser.can_fetch(agent, url))
+ self.assertFalse(self.parser.can_fetch(agent, url))
def __str__(self):
return self.str
diff --git a/Lib/test/test_runpy.py b/Lib/test/test_runpy.py
index 43691cbbb6..43141e5817 100644
--- a/Lib/test/test_runpy.py
+++ b/Lib/test/test_runpy.py
@@ -37,14 +37,14 @@ class RunModuleCodeTest(unittest.TestCase):
def test_run_code(self):
saved_argv0 = sys.argv[0]
d = _run_code(self.test_source, {})
- self.failUnless(d["result"] == self.expected_result)
- self.failUnless(d["__name__"] is None)
- self.failUnless(d["__file__"] is None)
- self.failUnless(d["__loader__"] is None)
- self.failUnless(d["__package__"] is None)
- self.failUnless(d["run_argv0"] is saved_argv0)
- self.failUnless("run_name" not in d)
- self.failUnless(sys.argv[0] is saved_argv0)
+ self.assertTrue(d["result"] == self.expected_result)
+ self.assertTrue(d["__name__"] is None)
+ self.assertTrue(d["__file__"] is None)
+ self.assertTrue(d["__loader__"] is None)
+ self.assertTrue(d["__package__"] is None)
+ self.assertTrue(d["run_argv0"] is saved_argv0)
+ self.assertTrue("run_name" not in d)
+ self.assertTrue(sys.argv[0] is saved_argv0)
def test_run_module_code(self):
initial = object()
@@ -60,19 +60,19 @@ class RunModuleCodeTest(unittest.TestCase):
file,
loader,
package)
- self.failUnless("result" not in d1)
- self.failUnless(d2["initial"] is initial)
+ self.assertTrue("result" not in d1)
+ self.assertTrue(d2["initial"] is initial)
self.assertEqual(d2["result"], self.expected_result)
self.assertEqual(d2["nested"]["x"], 1)
- self.failUnless(d2["__name__"] is name)
- self.failUnless(d2["run_name_in_sys_modules"])
- self.failUnless(d2["module_in_sys_modules"])
- self.failUnless(d2["__file__"] is file)
- self.failUnless(d2["run_argv0"] is file)
- self.failUnless(d2["__loader__"] is loader)
- self.failUnless(d2["__package__"] is package)
- self.failUnless(sys.argv[0] is saved_argv0)
- self.failUnless(name not in sys.modules)
+ self.assertTrue(d2["__name__"] is name)
+ self.assertTrue(d2["run_name_in_sys_modules"])
+ self.assertTrue(d2["module_in_sys_modules"])
+ self.assertTrue(d2["__file__"] is file)
+ self.assertTrue(d2["run_argv0"] is file)
+ self.assertTrue(d2["__loader__"] is loader)
+ self.assertTrue(d2["__package__"] is package)
+ self.assertTrue(sys.argv[0] is saved_argv0)
+ self.assertTrue(name not in sys.modules)
class RunModuleTest(unittest.TestCase):
@@ -159,14 +159,14 @@ class RunModuleTest(unittest.TestCase):
try:
if verbose: print("Running from source:", mod_name)
d1 = run_module(mod_name) # Read from source
- self.failUnless("x" in d1)
+ self.assertTrue("x" in d1)
self.assertEqual(d1["x"], 1)
del d1 # Ensure __loader__ entry doesn't keep file open
__import__(mod_name)
os.remove(mod_fname)
if verbose: print("Running from compiled:", mod_name)
d2 = run_module(mod_name) # Read from bytecode
- self.failUnless("x" in d2)
+ self.assertTrue("x" in d2)
self.assertEqual(d2["x"], 1)
del d2 # Ensure __loader__ entry doesn't keep file open
finally:
@@ -211,19 +211,19 @@ from ..uncle.cousin import nephew
pkg_name = mod_name.rpartition('.')[0]
if verbose: print("Running from source:", mod_name)
d1 = run_module(mod_name, run_name=run_name) # Read from source
- self.failUnless("__package__" in d1)
- self.failUnless(d1["__package__"] == pkg_name)
- self.failUnless("sibling" in d1)
- self.failUnless("nephew" in d1)
+ self.assertTrue("__package__" in d1)
+ self.assertTrue(d1["__package__"] == pkg_name)
+ self.assertTrue("sibling" in d1)
+ self.assertTrue("nephew" in d1)
del d1 # Ensure __loader__ entry doesn't keep file open
__import__(mod_name)
os.remove(mod_fname)
if verbose: print("Running from compiled:", mod_name)
d2 = run_module(mod_name, run_name=run_name) # Read from bytecode
- self.failUnless("__package__" in d2)
- self.failUnless(d2["__package__"] == pkg_name)
- self.failUnless("sibling" in d2)
- self.failUnless("nephew" in d2)
+ self.assertTrue("__package__" in d2)
+ self.assertTrue(d2["__package__"] == pkg_name)
+ self.assertTrue("sibling" in d2)
+ self.assertTrue("nephew" in d2)
del d2 # Ensure __loader__ entry doesn't keep file open
finally:
self._del_pkg(pkg_dir, depth, mod_name)
diff --git a/Lib/test/test_scope.py b/Lib/test/test_scope.py
index fb1e26f1f5..84ceafabd6 100644
--- a/Lib/test/test_scope.py
+++ b/Lib/test/test_scope.py
@@ -443,7 +443,7 @@ class X:
locals()['looked_up_by_load_name'] = True
passed = looked_up_by_load_name
-self.assert_(X.passed)
+self.assertTrue(X.passed)
""")
def testLocalsFunction(self):
@@ -458,7 +458,7 @@ self.assert_(X.passed)
return g
d = f(2)(4)
- self.assert_('h' in d)
+ self.assertTrue('h' in d)
del d['h']
self.assertEqual(d, {'x': 2, 'y': 7, 'w': 6})
@@ -492,8 +492,8 @@ self.assert_(X.passed)
return C
varnames = f(1).z
- self.assert_("x" not in varnames)
- self.assert_("y" in varnames)
+ self.assertTrue("x" not in varnames)
+ self.assertTrue("y" in varnames)
def testLocalsClass_WithTrace(self):
# Issue23728: after the trace function returns, the locals()
@@ -671,7 +671,7 @@ result2 = h()
c = f(0)
self.assertEqual(c.get(), 1)
- self.assert_("x" not in c.__class__.__dict__)
+ self.assertTrue("x" not in c.__class__.__dict__)
def testNonLocalGenerator(self):
diff --git a/Lib/test/test_set.py b/Lib/test/test_set.py
index 15d3c6f97d..a13f886aa3 100644
--- a/Lib/test/test_set.py
+++ b/Lib/test/test_set.py
@@ -65,7 +65,7 @@ class TestJointOps(unittest.TestCase):
self.assertEqual(c in self.s, c in self.d)
self.assertRaises(TypeError, self.s.__contains__, [[]])
s = self.thetype([frozenset(self.letters)])
- self.assert_(self.thetype(self.letters) in s)
+ self.assertTrue(self.thetype(self.letters) in s)
def test_union(self):
u = self.s.union(self.otherword)
@@ -125,7 +125,7 @@ class TestJointOps(unittest.TestCase):
actual = s1.isdisjoint(s2)
expected = f(s1, s2)
self.assertEqual(actual, expected)
- self.assert_(actual is True or actual is False)
+ self.assertTrue(actual is True or actual is False)
def test_and(self):
i = self.s.intersection(self.otherword)
@@ -205,19 +205,19 @@ class TestJointOps(unittest.TestCase):
def test_sub_and_super(self):
p, q, r = map(self.thetype, ['ab', 'abcde', 'def'])
- self.assert_(p < q)
- self.assert_(p <= q)
- self.assert_(q <= q)
- self.assert_(q > p)
- self.assert_(q >= p)
- self.failIf(q < r)
- self.failIf(q <= r)
- self.failIf(q > r)
- self.failIf(q >= r)
- self.assert_(set('a').issubset('abc'))
- self.assert_(set('abc').issuperset('a'))
- self.failIf(set('a').issubset('cbs'))
- self.failIf(set('cbs').issuperset('a'))
+ self.assertTrue(p < q)
+ self.assertTrue(p <= q)
+ self.assertTrue(q <= q)
+ self.assertTrue(q > p)
+ self.assertTrue(q >= p)
+ self.assertFalse(q < r)
+ self.assertFalse(q <= r)
+ self.assertFalse(q > r)
+ self.assertFalse(q >= r)
+ self.assertTrue(set('a').issubset('abc'))
+ self.assertTrue(set('abc').issuperset('a'))
+ self.assertFalse(set('a').issubset('cbs'))
+ self.assertFalse(set('cbs').issuperset('a'))
def test_pickling(self):
for i in range(pickle.HIGHEST_PROTOCOL + 1):
@@ -265,7 +265,7 @@ class TestJointOps(unittest.TestCase):
s=H()
f=set()
f.add(s)
- self.assert_(s in f)
+ self.assertTrue(s in f)
f.remove(s)
f.add(s)
f.discard(s)
@@ -334,7 +334,7 @@ class TestJointOps(unittest.TestCase):
obj.x = iter(container)
del obj, container
gc.collect()
- self.assert_(ref() is None, "Cycle was not collected")
+ self.assertTrue(ref() is None, "Cycle was not collected")
class TestSet(TestJointOps):
thetype = set
@@ -375,7 +375,7 @@ class TestSet(TestJointOps):
def test_add(self):
self.s.add('Q')
- self.assert_('Q' in self.s)
+ self.assertTrue('Q' in self.s)
dup = self.s.copy()
self.s.add('Q')
self.assertEqual(self.s, dup)
@@ -383,13 +383,13 @@ class TestSet(TestJointOps):
def test_remove(self):
self.s.remove('a')
- self.assert_('a' not in self.s)
+ self.assertTrue('a' not in self.s)
self.assertRaises(KeyError, self.s.remove, 'Q')
self.assertRaises(TypeError, self.s.remove, [])
s = self.thetype([frozenset(self.word)])
- self.assert_(self.thetype(self.word) in s)
+ self.assertTrue(self.thetype(self.word) in s)
s.remove(self.thetype(self.word))
- self.assert_(self.thetype(self.word) not in s)
+ self.assertTrue(self.thetype(self.word) not in s)
self.assertRaises(KeyError, self.s.remove, self.thetype(self.word))
def test_remove_keyerror_unpacking(self):
@@ -408,7 +408,7 @@ class TestSet(TestJointOps):
try:
self.s.remove(key)
except KeyError as e:
- self.assert_(e.args[0] is key,
+ self.assertTrue(e.args[0] is key,
"KeyError should be {0}, not {1}".format(key,
e.args[0]))
else:
@@ -416,26 +416,26 @@ class TestSet(TestJointOps):
def test_discard(self):
self.s.discard('a')
- self.assert_('a' not in self.s)
+ self.assertTrue('a' not in self.s)
self.s.discard('Q')
self.assertRaises(TypeError, self.s.discard, [])
s = self.thetype([frozenset(self.word)])
- self.assert_(self.thetype(self.word) in s)
+ self.assertTrue(self.thetype(self.word) in s)
s.discard(self.thetype(self.word))
- self.assert_(self.thetype(self.word) not in s)
+ self.assertTrue(self.thetype(self.word) not in s)
s.discard(self.thetype(self.word))
def test_pop(self):
for i in range(len(self.s)):
elem = self.s.pop()
- self.assert_(elem not in self.s)
+ self.assertTrue(elem not in self.s)
self.assertRaises(KeyError, self.s.pop)
def test_update(self):
retval = self.s.update(self.otherword)
self.assertEqual(retval, None)
for c in (self.word + self.otherword):
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
self.assertRaises(PassThru, self.s.update, check_pass_thru())
self.assertRaises(TypeError, self.s.update, [[]])
for p, q in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')):
@@ -453,16 +453,16 @@ class TestSet(TestJointOps):
def test_ior(self):
self.s |= set(self.otherword)
for c in (self.word + self.otherword):
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
def test_intersection_update(self):
retval = self.s.intersection_update(self.otherword)
self.assertEqual(retval, None)
for c in (self.word + self.otherword):
if c in self.otherword and c in self.word:
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
else:
- self.assert_(c not in self.s)
+ self.assertTrue(c not in self.s)
self.assertRaises(PassThru, self.s.intersection_update, check_pass_thru())
self.assertRaises(TypeError, self.s.intersection_update, [[]])
for p, q in (('cdc', 'c'), ('efgfe', ''), ('ccb', 'bc'), ('ef', '')):
@@ -480,18 +480,18 @@ class TestSet(TestJointOps):
self.s &= set(self.otherword)
for c in (self.word + self.otherword):
if c in self.otherword and c in self.word:
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
else:
- self.assert_(c not in self.s)
+ self.assertTrue(c not in self.s)
def test_difference_update(self):
retval = self.s.difference_update(self.otherword)
self.assertEqual(retval, None)
for c in (self.word + self.otherword):
if c in self.word and c not in self.otherword:
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
else:
- self.assert_(c not in self.s)
+ self.assertTrue(c not in self.s)
self.assertRaises(PassThru, self.s.difference_update, check_pass_thru())
self.assertRaises(TypeError, self.s.difference_update, [[]])
self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]])
@@ -517,18 +517,18 @@ class TestSet(TestJointOps):
self.s -= set(self.otherword)
for c in (self.word + self.otherword):
if c in self.word and c not in self.otherword:
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
else:
- self.assert_(c not in self.s)
+ self.assertTrue(c not in self.s)
def test_symmetric_difference_update(self):
retval = self.s.symmetric_difference_update(self.otherword)
self.assertEqual(retval, None)
for c in (self.word + self.otherword):
if (c in self.word) ^ (c in self.otherword):
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
else:
- self.assert_(c not in self.s)
+ self.assertTrue(c not in self.s)
self.assertRaises(PassThru, self.s.symmetric_difference_update, check_pass_thru())
self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]])
for p, q in (('cdc', 'abd'), ('efgfe', 'abcefg'), ('ccb', 'a'), ('ef', 'abcef')):
@@ -541,9 +541,9 @@ class TestSet(TestJointOps):
self.s ^= set(self.otherword)
for c in (self.word + self.otherword):
if (c in self.word) ^ (c in self.otherword):
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
else:
- self.assert_(c not in self.s)
+ self.assertTrue(c not in self.s)
def test_inplace_on_self(self):
t = self.s.copy()
@@ -586,19 +586,19 @@ class TestSet(TestJointOps):
myobj = TestRichSetCompare()
myset < myobj
- self.assert_(myobj.gt_called)
+ self.assertTrue(myobj.gt_called)
myobj = TestRichSetCompare()
myset > myobj
- self.assert_(myobj.lt_called)
+ self.assertTrue(myobj.lt_called)
myobj = TestRichSetCompare()
myset <= myobj
- self.assert_(myobj.ge_called)
+ self.assertTrue(myobj.ge_called)
myobj = TestRichSetCompare()
myset >= myobj
- self.assert_(myobj.le_called)
+ self.assertTrue(myobj.le_called)
# C API test only available in a debug build
if hasattr(set, "test_c_api"):
@@ -810,7 +810,7 @@ class TestBasicOps(unittest.TestCase):
def test_iteration(self):
for v in self.set:
- self.assert_(v in self.values)
+ self.assertTrue(v in self.values)
setiter = iter(self.set)
# note: __length_hint__ is an internal undocumented API,
# don't rely on it in your own programs
@@ -845,10 +845,10 @@ class TestBasicOpsSingleton(TestBasicOps):
self.repr = "{3}"
def test_in(self):
- self.failUnless(3 in self.set)
+ self.assertTrue(3 in self.set)
def test_not_in(self):
- self.failUnless(2 not in self.set)
+ self.assertTrue(2 not in self.set)
#------------------------------------------------------------------------------
@@ -862,10 +862,10 @@ class TestBasicOpsTuple(TestBasicOps):
self.repr = "{(0, 'zero')}"
def test_in(self):
- self.failUnless((0, "zero") in self.set)
+ self.assertTrue((0, "zero") in self.set)
def test_not_in(self):
- self.failUnless(9 not in self.set)
+ self.assertTrue(9 not in self.set)
#------------------------------------------------------------------------------
@@ -1182,7 +1182,7 @@ class TestMutate(unittest.TestCase):
popped[self.set.pop()] = None
self.assertEqual(len(popped), len(self.values))
for v in self.values:
- self.failUnless(v in popped)
+ self.assertTrue(v in popped)
def test_update_empty_tuple(self):
self.set.update(())
@@ -1451,7 +1451,7 @@ class TestCopying(unittest.TestCase):
set_list = sorted(self.set, key=repr)
self.assertEqual(len(dup_list), len(set_list))
for i in range(len(dup_list)):
- self.failUnless(dup_list[i] is set_list[i])
+ self.assertTrue(dup_list[i] is set_list[i])
def test_deep_copy(self):
dup = copy.deepcopy(self.set)
@@ -1501,13 +1501,13 @@ class TestIdentities(unittest.TestCase):
def test_binopsVsSubsets(self):
a, b = self.a, self.b
- self.assert_(a - b < a)
- self.assert_(b - a < b)
- self.assert_(a & b < a)
- self.assert_(a & b < b)
- self.assert_(a | b > a)
- self.assert_(a | b > b)
- self.assert_(a ^ b < a | b)
+ self.assertTrue(a - b < a)
+ self.assertTrue(b - a < b)
+ self.assertTrue(a & b < a)
+ self.assertTrue(a & b < b)
+ self.assertTrue(a | b > a)
+ self.assertTrue(a | b > b)
+ self.assertTrue(a ^ b < a | b)
def test_commutativity(self):
a, b = self.a, self.b
@@ -1756,7 +1756,7 @@ class TestGraphs(unittest.TestCase):
edge = vertex # Cuboctahedron vertices are edges in Cube
self.assertEqual(len(edge), 2) # Two cube vertices define an edge
for cubevert in edge:
- self.assert_(cubevert in g)
+ self.assertTrue(cubevert in g)
#==============================================================================
diff --git a/Lib/test/test_shutil.py b/Lib/test/test_shutil.py
index 5a546ecd87..60352a2b8b 100644
--- a/Lib/test/test_shutil.py
+++ b/Lib/test/test_shutil.py
@@ -63,12 +63,12 @@ class TestShutil(unittest.TestCase):
self.assertIs(func, os.listdir,
"func must be either os.remove or os.listdir")
self.assertEqual(arg, TESTFN)
- self.failUnless(issubclass(exc[0], OSError))
+ self.assertTrue(issubclass(exc[0], OSError))
self.errorState = 1
else:
self.assertEqual(func, os.rmdir)
self.assertEqual(arg, TESTFN)
- self.failUnless(issubclass(exc[0], OSError))
+ self.assertTrue(issubclass(exc[0], OSError))
self.errorState = 2
def test_rmtree_dont_delete_file(self):
@@ -158,9 +158,9 @@ class TestShutil(unittest.TestCase):
patterns = shutil.ignore_patterns('*.tmp', 'test_dir2')
shutil.copytree(src_dir, dst_dir, ignore=patterns)
# checking the result: some elements should not be copied
- self.assert_(exists(join(dst_dir, 'test.txt')))
- self.assert_(not exists(join(dst_dir, 'test.tmp')))
- self.assert_(not exists(join(dst_dir, 'test_dir2')))
+ self.assertTrue(exists(join(dst_dir, 'test.txt')))
+ self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
+ self.assertTrue(not exists(join(dst_dir, 'test_dir2')))
finally:
if os.path.exists(dst_dir):
shutil.rmtree(dst_dir)
@@ -168,9 +168,9 @@ class TestShutil(unittest.TestCase):
patterns = shutil.ignore_patterns('*.tmp', 'subdir*')
shutil.copytree(src_dir, dst_dir, ignore=patterns)
# checking the result: some elements should not be copied
- self.assert_(not exists(join(dst_dir, 'test.tmp')))
- self.assert_(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
- self.assert_(not exists(join(dst_dir, 'test_dir2', 'subdir')))
+ self.assertTrue(not exists(join(dst_dir, 'test.tmp')))
+ self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2')))
+ self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
finally:
if os.path.exists(dst_dir):
shutil.rmtree(dst_dir)
@@ -192,9 +192,9 @@ class TestShutil(unittest.TestCase):
shutil.copytree(src_dir, dst_dir, ignore=_filter)
# checking the result: some elements should not be copied
- self.assert_(not exists(join(dst_dir, 'test_dir2', 'subdir2',
+ self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir2',
'test.py')))
- self.assert_(not exists(join(dst_dir, 'test_dir2', 'subdir')))
+ self.assertTrue(not exists(join(dst_dir, 'test_dir2', 'subdir')))
finally:
if os.path.exists(dst_dir):
@@ -393,7 +393,7 @@ class TestMove(unittest.TestCase):
for src, dst in [('srcdir', 'srcdir/dest')]:
src = os.path.join(TESTFN, src)
dst = os.path.join(TESTFN, dst)
- self.assert_(shutil._destinsrc(src, dst),
+ self.assertTrue(shutil._destinsrc(src, dst),
msg='_destinsrc() wrongly concluded that '
'dst (%s) is not in src (%s)' % (dst, src))
finally:
@@ -405,7 +405,7 @@ class TestMove(unittest.TestCase):
for src, dst in [('srcdir', 'src/dest'), ('srcdir', 'srcdir.new')]:
src = os.path.join(TESTFN, src)
dst = os.path.join(TESTFN, dst)
- self.failIf(shutil._destinsrc(src, dst),
+ self.assertFalse(shutil._destinsrc(src, dst),
msg='_destinsrc() wrongly concluded that '
'dst (%s) is in src (%s)' % (dst, src))
finally:
diff --git a/Lib/test/test_signal.py b/Lib/test/test_signal.py
index ef19641f89..5fc4220d1f 100644
--- a/Lib/test/test_signal.py
+++ b/Lib/test/test_signal.py
@@ -217,10 +217,10 @@ class WakeupSignalTests(unittest.TestCase):
# before select is called
time.sleep(self.TIMEOUT_FULL)
mid_time = time.time()
- self.assert_(mid_time - before_time < self.TIMEOUT_HALF)
+ self.assertTrue(mid_time - before_time < self.TIMEOUT_HALF)
select.select([self.read], [], [], self.TIMEOUT_FULL)
after_time = time.time()
- self.assert_(after_time - mid_time < self.TIMEOUT_HALF)
+ self.assertTrue(after_time - mid_time < self.TIMEOUT_HALF)
def test_wakeup_fd_during(self):
import select
@@ -231,7 +231,7 @@ class WakeupSignalTests(unittest.TestCase):
self.assertRaises(select.error, select.select,
[self.read], [], [], self.TIMEOUT_FULL)
after_time = time.time()
- self.assert_(after_time - before_time < self.TIMEOUT_HALF)
+ self.assertTrue(after_time - before_time < self.TIMEOUT_HALF)
def setUp(self):
import fcntl
diff --git a/Lib/test/test_site.py b/Lib/test/test_site.py
index 8d101b308b..7ed0ee24d4 100644
--- a/Lib/test/test_site.py
+++ b/Lib/test/test_site.py
@@ -47,26 +47,26 @@ class HelperFunctionsTests(unittest.TestCase):
path_parts = ("Beginning", "End")
original_dir = os.path.join(*path_parts)
abs_dir, norm_dir = site.makepath(*path_parts)
- self.failUnlessEqual(os.path.abspath(original_dir), abs_dir)
+ self.assertEqual(os.path.abspath(original_dir), abs_dir)
if original_dir == os.path.normcase(original_dir):
- self.failUnlessEqual(abs_dir, norm_dir)
+ self.assertEqual(abs_dir, norm_dir)
else:
- self.failUnlessEqual(os.path.normcase(abs_dir), norm_dir)
+ self.assertEqual(os.path.normcase(abs_dir), norm_dir)
def test_init_pathinfo(self):
dir_set = site._init_pathinfo()
for entry in [site.makepath(path)[1] for path in sys.path
if path and os.path.isdir(path)]:
- self.failUnless(entry in dir_set,
+ self.assertTrue(entry in dir_set,
"%s from sys.path not found in set returned "
"by _init_pathinfo(): %s" % (entry, dir_set))
def pth_file_tests(self, pth_file):
"""Contain common code for testing results of reading a .pth file"""
- self.failUnless(pth_file.imported in sys.modules,
+ self.assertTrue(pth_file.imported in sys.modules,
"%s not in sys.path" % pth_file.imported)
- self.failUnless(site.makepath(pth_file.good_dir_path)[0] in sys.path)
- self.failUnless(not os.path.exists(pth_file.bad_dir_path))
+ self.assertTrue(site.makepath(pth_file.good_dir_path)[0] in sys.path)
+ self.assertTrue(not os.path.exists(pth_file.bad_dir_path))
def test_addpackage(self):
# Make sure addpackage() imports if the line starts with 'import',
@@ -98,7 +98,7 @@ class HelperFunctionsTests(unittest.TestCase):
def test_s_option(self):
usersite = site.USER_SITE
- self.assert_(usersite in sys.path)
+ self.assertTrue(usersite in sys.path)
rc = subprocess.call([sys.executable, '-c',
'import sys; sys.exit(%r in sys.path)' % usersite])
@@ -196,7 +196,7 @@ class ImportSideEffectTests(unittest.TestCase):
site.abs__file__()
for module in (sys, os, builtins):
try:
- self.failUnless(os.path.isabs(module.__file__), repr(module))
+ self.assertTrue(os.path.isabs(module.__file__), repr(module))
except AttributeError:
continue
# We could try everything in sys.modules; however, when regrtest.py
@@ -209,7 +209,7 @@ class ImportSideEffectTests(unittest.TestCase):
site.removeduppaths()
seen_paths = set()
for path in sys.path:
- self.failUnless(path not in seen_paths)
+ self.assertTrue(path not in seen_paths)
seen_paths.add(path)
def test_add_build_dir(self):
@@ -220,17 +220,17 @@ class ImportSideEffectTests(unittest.TestCase):
def test_setting_quit(self):
# 'quit' and 'exit' should be injected into builtins
- self.failUnless(hasattr(builtins, "quit"))
- self.failUnless(hasattr(builtins, "exit"))
+ self.assertTrue(hasattr(builtins, "quit"))
+ self.assertTrue(hasattr(builtins, "exit"))
def test_setting_copyright(self):
# 'copyright' and 'credits' should be in builtins
- self.failUnless(hasattr(builtins, "copyright"))
- self.failUnless(hasattr(builtins, "credits"))
+ self.assertTrue(hasattr(builtins, "copyright"))
+ self.assertTrue(hasattr(builtins, "credits"))
def test_setting_help(self):
# 'help' should be set in builtins
- self.failUnless(hasattr(builtins, "help"))
+ self.assertTrue(hasattr(builtins, "help"))
def test_aliasing_mbcs(self):
if sys.platform == "win32":
@@ -244,7 +244,7 @@ class ImportSideEffectTests(unittest.TestCase):
def test_setdefaultencoding_removed(self):
# Make sure sys.setdefaultencoding is gone
- self.failUnless(not hasattr(sys, "setdefaultencoding"))
+ self.assertTrue(not hasattr(sys, "setdefaultencoding"))
def test_sitecustomize_executed(self):
# If sitecustomize is available, it should have been imported.
diff --git a/Lib/test/test_slice.py b/Lib/test/test_slice.py
index 640c8c0742..2ecb59a782 100644
--- a/Lib/test/test_slice.py
+++ b/Lib/test/test_slice.py
@@ -73,7 +73,7 @@ class SliceTest(unittest.TestCase):
obj = AnyClass()
s = slice(obj)
- self.assert_(s.stop is obj)
+ self.assertTrue(s.stop is obj)
def test_indices(self):
self.assertEqual(slice(None ).indices(10), (0, 10, 1))
diff --git a/Lib/test/test_socket.py b/Lib/test/test_socket.py
index e8a9fc42ac..8313006e34 100644
--- a/Lib/test/test_socket.py
+++ b/Lib/test/test_socket.py
@@ -224,7 +224,7 @@ class GeneralModuleTests(unittest.TestCase):
def test_repr(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
- self.assert_(repr(s).startswith("<socket.socket object"))
+ self.assertTrue(repr(s).startswith("<socket.socket object"))
def test_weakref(self):
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
@@ -247,11 +247,11 @@ class GeneralModuleTests(unittest.TestCase):
raise socket.herror
def raise_gaierror(*args, **kwargs):
raise socket.gaierror
- self.failUnlessRaises(socket.error, raise_error,
+ self.assertRaises(socket.error, raise_error,
"Error raising socket exception.")
- self.failUnlessRaises(socket.error, raise_herror,
+ self.assertRaises(socket.error, raise_herror,
"Error raising socket exception.")
- self.failUnlessRaises(socket.error, raise_gaierror,
+ self.assertRaises(socket.error, raise_gaierror,
"Error raising socket exception.")
def testCrucialConstants(self):
@@ -273,7 +273,7 @@ class GeneralModuleTests(unittest.TestCase):
except socket.error:
# Probably name lookup wasn't set up right; skip this test
return
- self.assert_(ip.find('.') >= 0, "Error resolving host to ip.")
+ self.assertTrue(ip.find('.') >= 0, "Error resolving host to ip.")
try:
hname, aliases, ipaddrs = socket.gethostbyaddr(ip)
except socket.error:
@@ -501,7 +501,7 @@ class GeneralModuleTests(unittest.TestCase):
# it reasonable to get the host's addr in addition to 0.0.0.0.
# At least for eCos. This is required for the S/390 to pass.
my_ip_addr = socket.gethostbyname(socket.gethostname())
- self.assert_(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
+ self.assertTrue(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
self.assertEqual(name[1], port)
def testGetSockOpt(self):
@@ -509,14 +509,14 @@ class GeneralModuleTests(unittest.TestCase):
# We know a socket should start without reuse==0
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
- self.failIf(reuse != 0, "initial mode is reuse")
+ self.assertFalse(reuse != 0, "initial mode is reuse")
def testSetSockOpt(self):
# Testing setsockopt()
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
sock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
reuse = sock.getsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR)
- self.failIf(reuse == 0, "failed to set reuse mode")
+ self.assertFalse(reuse == 0, "failed to set reuse mode")
def testSendAfterClose(self):
# testing send() after close() with timeout
@@ -549,10 +549,10 @@ class GeneralModuleTests(unittest.TestCase):
def test_sock_ioctl(self):
if os.name != "nt":
return
- self.assert_(hasattr(socket.socket, 'ioctl'))
- self.assert_(hasattr(socket, 'SIO_RCVALL'))
- self.assert_(hasattr(socket, 'RCVALL_ON'))
- self.assert_(hasattr(socket, 'RCVALL_OFF'))
+ self.assertTrue(hasattr(socket.socket, 'ioctl'))
+ self.assertTrue(hasattr(socket, 'SIO_RCVALL'))
+ self.assertTrue(hasattr(socket, 'RCVALL_ON'))
+ self.assertTrue(hasattr(socket, 'RCVALL_OFF'))
class BasicTCPTest(SocketConnectedTest):
@@ -724,7 +724,7 @@ class NonBlockingTCPTests(ThreadedTCPSocketTest):
except socket.error:
pass
end = time.time()
- self.assert_((end - start) < 1.0, "Error setting non-blocking mode.")
+ self.assertTrue((end - start) < 1.0, "Error setting non-blocking mode.")
def _testSetBlocking(self):
pass
@@ -801,7 +801,7 @@ class FileObjectClassTestCase(SocketConnectedTest):
def tearDown(self):
self.serv_file.close()
- self.assert_(self.serv_file.closed)
+ self.assertTrue(self.serv_file.closed)
self.serv_file = None
SocketConnectedTest.tearDown(self)
@@ -811,7 +811,7 @@ class FileObjectClassTestCase(SocketConnectedTest):
def clientTearDown(self):
self.cli_file.close()
- self.assert_(self.cli_file.closed)
+ self.assertTrue(self.cli_file.closed)
self.cli_file = None
SocketConnectedTest.clientTearDown(self)
@@ -879,10 +879,10 @@ class FileObjectClassTestCase(SocketConnectedTest):
self.cli_file.flush()
def testClosedAttr(self):
- self.assert_(not self.serv_file.closed)
+ self.assertTrue(not self.serv_file.closed)
def _testClosedAttr(self):
- self.assert_(not self.cli_file.closed)
+ self.assertTrue(not self.cli_file.closed)
def testAttributes(self):
self.assertEqual(self.serv_file.mode, 'rb')
@@ -977,7 +977,7 @@ class NetworkConnectionNoServer(unittest.TestCase):
def testWithoutServer(self):
port = support.find_unused_port()
- self.failUnlessRaises(
+ self.assertRaises(
socket.error,
lambda: socket.create_connection((HOST, port))
)
@@ -1007,7 +1007,7 @@ class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
testTimeoutDefault = _justAccept
def _testTimeoutDefault(self):
# passing no explicit timeout uses socket's global default
- self.assert_(socket.getdefaulttimeout() is None)
+ self.assertTrue(socket.getdefaulttimeout() is None)
socket.setdefaulttimeout(42)
try:
self.cli = socket.create_connection((HOST, self.port))
@@ -1018,7 +1018,7 @@ class NetworkConnectionAttributesTest(SocketTCPTest, ThreadableTest):
testTimeoutNone = _justAccept
def _testTimeoutNone(self):
# None timeout means the same as sock.settimeout(None)
- self.assert_(socket.getdefaulttimeout() is None)
+ self.assertTrue(socket.getdefaulttimeout() is None)
socket.setdefaulttimeout(30)
try:
self.cli = socket.create_connection((HOST, self.port), timeout=None)
@@ -1063,7 +1063,7 @@ class NetworkConnectionBehaviourTest(SocketTCPTest, ThreadableTest):
def _testOutsideTimeout(self):
self.cli = sock = socket.create_connection((HOST, self.port), timeout=1)
- self.failUnlessRaises(socket.timeout, lambda: sock.recv(5))
+ self.assertRaises(socket.timeout, lambda: sock.recv(5))
class TCPTimeoutTest(SocketTCPTest):
@@ -1072,7 +1072,7 @@ class TCPTimeoutTest(SocketTCPTest):
def raise_timeout(*args, **kwargs):
self.serv.settimeout(1.0)
self.serv.accept()
- self.failUnlessRaises(socket.timeout, raise_timeout,
+ self.assertRaises(socket.timeout, raise_timeout,
"Error generating a timeout exception (TCP)")
def testTimeoutZero(self):
@@ -1129,7 +1129,7 @@ class UDPTimeoutTest(SocketTCPTest):
def raise_timeout(*args, **kwargs):
self.serv.settimeout(1.0)
self.serv.recv(1024)
- self.failUnlessRaises(socket.timeout, raise_timeout,
+ self.assertRaises(socket.timeout, raise_timeout,
"Error generating a timeout exception (UDP)")
def testTimeoutZero(self):
@@ -1149,10 +1149,10 @@ class UDPTimeoutTest(SocketTCPTest):
class TestExceptions(unittest.TestCase):
def testExceptionTree(self):
- self.assert_(issubclass(socket.error, Exception))
- self.assert_(issubclass(socket.herror, socket.error))
- self.assert_(issubclass(socket.gaierror, socket.error))
- self.assert_(issubclass(socket.timeout, socket.error))
+ self.assertTrue(issubclass(socket.error, Exception))
+ self.assertTrue(issubclass(socket.herror, socket.error))
+ self.assertTrue(issubclass(socket.gaierror, socket.error))
+ self.assertTrue(issubclass(socket.timeout, socket.error))
class TestLinuxAbstractNamespace(unittest.TestCase):
diff --git a/Lib/test/test_stringprep.py b/Lib/test/test_stringprep.py
index f3d3327ab0..aa7122172f 100644
--- a/Lib/test/test_stringprep.py
+++ b/Lib/test/test_stringprep.py
@@ -8,66 +8,66 @@ from stringprep import *
class StringprepTests(unittest.TestCase):
def test(self):
- self.failUnless(in_table_a1("\u0221"))
- self.failIf(in_table_a1("\u0222"))
+ self.assertTrue(in_table_a1("\u0221"))
+ self.assertFalse(in_table_a1("\u0222"))
- self.failUnless(in_table_b1("\u00ad"))
- self.failIf(in_table_b1("\u00ae"))
+ self.assertTrue(in_table_b1("\u00ad"))
+ self.assertFalse(in_table_b1("\u00ae"))
- self.failUnless(map_table_b2("\u0041"), "\u0061")
- self.failUnless(map_table_b2("\u0061"), "\u0061")
+ self.assertTrue(map_table_b2("\u0041"), "\u0061")
+ self.assertTrue(map_table_b2("\u0061"), "\u0061")
- self.failUnless(map_table_b3("\u0041"), "\u0061")
- self.failUnless(map_table_b3("\u0061"), "\u0061")
+ self.assertTrue(map_table_b3("\u0041"), "\u0061")
+ self.assertTrue(map_table_b3("\u0061"), "\u0061")
- self.failUnless(in_table_c11("\u0020"))
- self.failIf(in_table_c11("\u0021"))
+ self.assertTrue(in_table_c11("\u0020"))
+ self.assertFalse(in_table_c11("\u0021"))
- self.failUnless(in_table_c12("\u00a0"))
- self.failIf(in_table_c12("\u00a1"))
+ self.assertTrue(in_table_c12("\u00a0"))
+ self.assertFalse(in_table_c12("\u00a1"))
- self.failUnless(in_table_c12("\u00a0"))
- self.failIf(in_table_c12("\u00a1"))
+ self.assertTrue(in_table_c12("\u00a0"))
+ self.assertFalse(in_table_c12("\u00a1"))
- self.failUnless(in_table_c11_c12("\u00a0"))
- self.failIf(in_table_c11_c12("\u00a1"))
+ self.assertTrue(in_table_c11_c12("\u00a0"))
+ self.assertFalse(in_table_c11_c12("\u00a1"))
- self.failUnless(in_table_c21("\u001f"))
- self.failIf(in_table_c21("\u0020"))
+ self.assertTrue(in_table_c21("\u001f"))
+ self.assertFalse(in_table_c21("\u0020"))
- self.failUnless(in_table_c22("\u009f"))
- self.failIf(in_table_c22("\u00a0"))
+ self.assertTrue(in_table_c22("\u009f"))
+ self.assertFalse(in_table_c22("\u00a0"))
- self.failUnless(in_table_c21_c22("\u009f"))
- self.failIf(in_table_c21_c22("\u00a0"))
+ self.assertTrue(in_table_c21_c22("\u009f"))
+ self.assertFalse(in_table_c21_c22("\u00a0"))
- self.failUnless(in_table_c3("\ue000"))
- self.failIf(in_table_c3("\uf900"))
+ self.assertTrue(in_table_c3("\ue000"))
+ self.assertFalse(in_table_c3("\uf900"))
- self.failUnless(in_table_c4("\uffff"))
- self.failIf(in_table_c4("\u0000"))
+ self.assertTrue(in_table_c4("\uffff"))
+ self.assertFalse(in_table_c4("\u0000"))
- self.failUnless(in_table_c5("\ud800"))
- self.failIf(in_table_c5("\ud7ff"))
+ self.assertTrue(in_table_c5("\ud800"))
+ self.assertFalse(in_table_c5("\ud7ff"))
- self.failUnless(in_table_c6("\ufff9"))
- self.failIf(in_table_c6("\ufffe"))
+ self.assertTrue(in_table_c6("\ufff9"))
+ self.assertFalse(in_table_c6("\ufffe"))
- self.failUnless(in_table_c7("\u2ff0"))
- self.failIf(in_table_c7("\u2ffc"))
+ self.assertTrue(in_table_c7("\u2ff0"))
+ self.assertFalse(in_table_c7("\u2ffc"))
- self.failUnless(in_table_c8("\u0340"))
- self.failIf(in_table_c8("\u0342"))
+ self.assertTrue(in_table_c8("\u0340"))
+ self.assertFalse(in_table_c8("\u0342"))
# C.9 is not in the bmp
- # self.failUnless(in_table_c9(u"\U000E0001"))
- # self.failIf(in_table_c8(u"\U000E0002"))
+ # self.assertTrue(in_table_c9(u"\U000E0001"))
+ # self.assertFalse(in_table_c8(u"\U000E0002"))
- self.failUnless(in_table_d1("\u05be"))
- self.failIf(in_table_d1("\u05bf"))
+ self.assertTrue(in_table_d1("\u05be"))
+ self.assertFalse(in_table_d1("\u05bf"))
- self.failUnless(in_table_d2("\u0041"))
- self.failIf(in_table_d2("\u0040"))
+ self.assertTrue(in_table_d2("\u0041"))
+ self.assertFalse(in_table_d2("\u0040"))
# This would generate a hash of all predicates. However, running
# it is quite expensive, and only serves to detect changes in the
diff --git a/Lib/test/test_strptime.py b/Lib/test/test_strptime.py
index 436a487dff..fb60ee4646 100644
--- a/Lib/test/test_strptime.py
+++ b/Lib/test/test_strptime.py
@@ -13,7 +13,7 @@ import _strptime
class getlang_Tests(unittest.TestCase):
"""Test _getlang"""
def test_basic(self):
- self.failUnlessEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME))
+ self.assertEqual(_strptime._getlang(), locale.getlocale(locale.LC_TIME))
class LocaleTime_Tests(unittest.TestCase):
"""Tests for _strptime.LocaleTime.
@@ -36,9 +36,9 @@ class LocaleTime_Tests(unittest.TestCase):
"""
strftime_output = time.strftime(directive, self.time_tuple).lower()
comparison = testing[self.time_tuple[tuple_position]]
- self.failUnless(strftime_output in testing, "%s: not found in tuple" %
+ self.assertTrue(strftime_output in testing, "%s: not found in tuple" %
error_msg)
- self.failUnless(comparison == strftime_output,
+ self.assertTrue(comparison == strftime_output,
"%s: position within tuple incorrect; %s != %s" %
(error_msg, comparison, strftime_output))
@@ -61,18 +61,18 @@ class LocaleTime_Tests(unittest.TestCase):
def test_am_pm(self):
# Make sure AM/PM representation done properly
strftime_output = time.strftime("%p", self.time_tuple).lower()
- self.failUnless(strftime_output in self.LT_ins.am_pm,
+ self.assertTrue(strftime_output in self.LT_ins.am_pm,
"AM/PM representation not in tuple")
if self.time_tuple[3] < 12: position = 0
else: position = 1
- self.failUnless(strftime_output == self.LT_ins.am_pm[position],
+ self.assertTrue(strftime_output == self.LT_ins.am_pm[position],
"AM/PM representation in the wrong position within the tuple")
def test_timezone(self):
# Make sure timezone is correct
timezone = time.strftime("%Z", self.time_tuple).lower()
if timezone:
- self.failUnless(timezone in self.LT_ins.timezone[0] or \
+ self.assertTrue(timezone in self.LT_ins.timezone[0] or \
timezone in self.LT_ins.timezone[1],
"timezone %s not found in %s" %
(timezone, self.LT_ins.timezone))
@@ -86,26 +86,26 @@ class LocaleTime_Tests(unittest.TestCase):
# output.
magic_date = (1999, 3, 17, 22, 44, 55, 2, 76, 0)
strftime_output = time.strftime("%c", magic_date)
- self.failUnless(strftime_output == time.strftime(self.LT_ins.LC_date_time,
+ self.assertTrue(strftime_output == time.strftime(self.LT_ins.LC_date_time,
magic_date),
"LC_date_time incorrect")
strftime_output = time.strftime("%x", magic_date)
- self.failUnless(strftime_output == time.strftime(self.LT_ins.LC_date,
+ self.assertTrue(strftime_output == time.strftime(self.LT_ins.LC_date,
magic_date),
"LC_date incorrect")
strftime_output = time.strftime("%X", magic_date)
- self.failUnless(strftime_output == time.strftime(self.LT_ins.LC_time,
+ self.assertTrue(strftime_output == time.strftime(self.LT_ins.LC_time,
magic_date),
"LC_time incorrect")
LT = _strptime.LocaleTime()
LT.am_pm = ('', '')
- self.failUnless(LT.LC_time, "LocaleTime's LC directives cannot handle "
+ self.assertTrue(LT.LC_time, "LocaleTime's LC directives cannot handle "
"empty strings")
def test_lang(self):
# Make sure lang is set to what _getlang() returns
# Assuming locale has not changed between now and when self.LT_ins was created
- self.failUnlessEqual(self.LT_ins.lang, _strptime._getlang())
+ self.assertEqual(self.LT_ins.lang, _strptime._getlang())
class TimeRETests(unittest.TestCase):
@@ -119,13 +119,13 @@ class TimeRETests(unittest.TestCase):
def test_pattern(self):
# Test TimeRE.pattern
pattern_string = self.time_re.pattern(r"%a %A %d")
- self.failUnless(pattern_string.find(self.locale_time.a_weekday[2]) != -1,
+ self.assertTrue(pattern_string.find(self.locale_time.a_weekday[2]) != -1,
"did not find abbreviated weekday in pattern string '%s'" %
pattern_string)
- self.failUnless(pattern_string.find(self.locale_time.f_weekday[4]) != -1,
+ self.assertTrue(pattern_string.find(self.locale_time.f_weekday[4]) != -1,
"did not find full weekday in pattern string '%s'" %
pattern_string)
- self.failUnless(pattern_string.find(self.time_re['d']) != -1,
+ self.assertTrue(pattern_string.find(self.time_re['d']) != -1,
"did not find 'd' directive pattern string '%s'" %
pattern_string)
@@ -133,23 +133,23 @@ class TimeRETests(unittest.TestCase):
# Make sure any characters in the format string that might be taken as
# regex syntax is escaped.
pattern_string = self.time_re.pattern("\d+")
- self.failUnless(r"\\d\+" in pattern_string,
+ self.assertTrue(r"\\d\+" in pattern_string,
"%s does not have re characters escaped properly" %
pattern_string)
def test_compile(self):
# Check that compiled regex is correct
found = self.time_re.compile(r"%A").match(self.locale_time.f_weekday[6])
- self.failUnless(found and found.group('A') == self.locale_time.f_weekday[6],
+ self.assertTrue(found and found.group('A') == self.locale_time.f_weekday[6],
"re object for '%A' failed")
compiled = self.time_re.compile(r"%a %b")
found = compiled.match("%s %s" % (self.locale_time.a_weekday[4],
self.locale_time.a_month[4]))
- self.failUnless(found,
+ self.assertTrue(found,
"Match failed with '%s' regex and '%s' string" %
(compiled.pattern, "%s %s" % (self.locale_time.a_weekday[4],
self.locale_time.a_month[4])))
- self.failUnless(found.group('a') == self.locale_time.a_weekday[4] and
+ self.assertTrue(found.group('a') == self.locale_time.a_weekday[4] and
found.group('b') == self.locale_time.a_month[4],
"re object couldn't find the abbreviated weekday month in "
"'%s' using '%s'; group 'a' = '%s', group 'b' = %s'" %
@@ -159,7 +159,7 @@ class TimeRETests(unittest.TestCase):
'U','w','W','x','X','y','Y','Z','%'):
compiled = self.time_re.compile("%" + directive)
found = compiled.match(time.strftime("%" + directive))
- self.failUnless(found, "Matching failed on '%s' using '%s' regex" %
+ self.assertTrue(found, "Matching failed on '%s' using '%s' regex" %
(time.strftime("%" + directive),
compiled.pattern))
@@ -168,14 +168,14 @@ class TimeRETests(unittest.TestCase):
# Fixes bug #661354
test_locale = _strptime.LocaleTime()
test_locale.timezone = (frozenset(), frozenset())
- self.failUnless(_strptime.TimeRE(test_locale).pattern("%Z") == '',
+ self.assertTrue(_strptime.TimeRE(test_locale).pattern("%Z") == '',
"with timezone == ('',''), TimeRE().pattern('%Z') != ''")
def test_matching_with_escapes(self):
# Make sure a format that requires escaping of characters works
compiled_re = self.time_re.compile("\w+ %m")
found = compiled_re.match("\w+ 10")
- self.failUnless(found, "Escaping failed of format '\w+ 10'")
+ self.assertTrue(found, "Escaping failed of format '\w+ 10'")
def test_locale_data_w_regex_metacharacters(self):
# Check that if locale data contains regex metacharacters they are
@@ -186,7 +186,7 @@ class TimeRETests(unittest.TestCase):
"Tokyo (standard time)")),
frozenset("Tokyo (daylight time)"))
time_re = _strptime.TimeRE(locale_time)
- self.failUnless(time_re.compile("%Z").match("Tokyo (standard time)"),
+ self.assertTrue(time_re.compile("%Z").match("Tokyo (standard time)"),
"locale data that contains regex metacharacters is not"
" properly escaped")
@@ -195,8 +195,8 @@ class TimeRETests(unittest.TestCase):
# so as to not allow to subpatterns to end up next to each other and
# "steal" characters from each other.
pattern = self.time_re.pattern('%j %H')
- self.failUnless(not re.match(pattern, "180"))
- self.failUnless(re.match(pattern, "18 0"))
+ self.assertTrue(not re.match(pattern, "180"))
+ self.assertTrue(re.match(pattern, "18 0"))
class StrptimeTests(unittest.TestCase):
@@ -229,7 +229,7 @@ class StrptimeTests(unittest.TestCase):
"""Helper fxn in testing."""
strf_output = time.strftime("%" + directive, self.time_tuple)
strp_output = _strptime._strptime_time(strf_output, "%" + directive)
- self.failUnless(strp_output[position] == self.time_tuple[position],
+ self.assertTrue(strp_output[position] == self.time_tuple[position],
"testing of '%s' directive failed; '%s' -> %s != %s" %
(directive, strf_output, strp_output[position],
self.time_tuple[position]))
@@ -243,7 +243,7 @@ class StrptimeTests(unittest.TestCase):
for bound in bounds:
strp_output = _strptime._strptime_time(bound, '%y')
expected_result = century + int(bound)
- self.failUnless(strp_output[0] == expected_result,
+ self.assertTrue(strp_output[0] == expected_result,
"'y' test failed; passed in '%s' "
"and returned '%s'" % (bound, strp_output[0]))
@@ -261,7 +261,7 @@ class StrptimeTests(unittest.TestCase):
self.helper('H', 3)
strf_output = time.strftime("%I %p", self.time_tuple)
strp_output = _strptime._strptime_time(strf_output, "%I %p")
- self.failUnless(strp_output[3] == self.time_tuple[3],
+ self.assertTrue(strp_output[3] == self.time_tuple[3],
"testing of '%%I %%p' directive failed; '%s' -> %s != %s" %
(strf_output, strp_output[3], self.time_tuple[3]))
@@ -294,9 +294,9 @@ class StrptimeTests(unittest.TestCase):
# Check for equal timezone names deals with bad locale info when this
# occurs; first found in FreeBSD 4.4.
strp_output = _strptime._strptime_time("UTC", "%Z")
- self.failUnlessEqual(strp_output.tm_isdst, 0)
+ self.assertEqual(strp_output.tm_isdst, 0)
strp_output = _strptime._strptime_time("GMT", "%Z")
- self.failUnlessEqual(strp_output.tm_isdst, 0)
+ self.assertEqual(strp_output.tm_isdst, 0)
if sys.platform == "mac":
# Timezones don't really work on MacOS9
return
@@ -305,11 +305,11 @@ class StrptimeTests(unittest.TestCase):
strp_output = _strptime._strptime_time(strf_output, "%Z")
locale_time = _strptime.LocaleTime()
if time.tzname[0] != time.tzname[1] or not time.daylight:
- self.failUnless(strp_output[8] == time_tuple[8],
+ self.assertTrue(strp_output[8] == time_tuple[8],
"timezone check failed; '%s' -> %s != %s" %
(strf_output, strp_output[8], time_tuple[8]))
else:
- self.failUnless(strp_output[8] == -1,
+ self.assertTrue(strp_output[8] == -1,
"LocaleTime().timezone has duplicate values and "
"time.daylight but timezone value not set to -1")
@@ -327,7 +327,7 @@ class StrptimeTests(unittest.TestCase):
time.tzname = (tz_name, tz_name)
time.daylight = 1
tz_value = _strptime._strptime_time(tz_name, "%Z")[8]
- self.failUnlessEqual(tz_value, -1,
+ self.assertEqual(tz_value, -1,
"%s lead to a timezone value of %s instead of -1 when "
"time.daylight set to %s and passing in %s" %
(time.tzname, tz_value, time.daylight, tz_name))
@@ -354,25 +354,25 @@ class StrptimeTests(unittest.TestCase):
# Make sure % signs are handled properly
strf_output = time.strftime("%m %% %Y", self.time_tuple)
strp_output = _strptime._strptime_time(strf_output, "%m %% %Y")
- self.failUnless(strp_output[0] == self.time_tuple[0] and
+ self.assertTrue(strp_output[0] == self.time_tuple[0] and
strp_output[1] == self.time_tuple[1],
"handling of percent sign failed")
def test_caseinsensitive(self):
# Should handle names case-insensitively.
strf_output = time.strftime("%B", self.time_tuple)
- self.failUnless(_strptime._strptime_time(strf_output.upper(), "%B"),
+ self.assertTrue(_strptime._strptime_time(strf_output.upper(), "%B"),
"strptime does not handle ALL-CAPS names properly")
- self.failUnless(_strptime._strptime_time(strf_output.lower(), "%B"),
+ self.assertTrue(_strptime._strptime_time(strf_output.lower(), "%B"),
"strptime does not handle lowercase names properly")
- self.failUnless(_strptime._strptime_time(strf_output.capitalize(), "%B"),
+ self.assertTrue(_strptime._strptime_time(strf_output.capitalize(), "%B"),
"strptime does not handle capword names properly")
def test_defaults(self):
# Default return value should be (1900, 1, 1, 0, 0, 0, 0, 1, 0)
defaults = (1900, 1, 1, 0, 0, 0, 0, 1, -1)
strp_output = _strptime._strptime_time('1', '%m')
- self.failUnless(strp_output == defaults,
+ self.assertTrue(strp_output == defaults,
"Default values for strptime() are incorrect;"
" %s != %s" % (strp_output, defaults))
@@ -383,7 +383,7 @@ class StrptimeTests(unittest.TestCase):
# escaped.
# Test instigated by bug #796149 .
need_escaping = ".^$*+?{}\[]|)("
- self.failUnless(_strptime._strptime_time(need_escaping, need_escaping))
+ self.assertTrue(_strptime._strptime_time(need_escaping, need_escaping))
class Strptime12AMPMTests(unittest.TestCase):
"""Test a _strptime regression in '%I %p' at 12 noon (12 PM)"""
@@ -416,7 +416,7 @@ class CalculationTests(unittest.TestCase):
format_string = "%Y %m %d %H %M %S %w %Z"
result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple),
format_string)
- self.failUnless(result.tm_yday == self.time_tuple.tm_yday,
+ self.assertTrue(result.tm_yday == self.time_tuple.tm_yday,
"Calculation of tm_yday failed; %s != %s" %
(result.tm_yday, self.time_tuple.tm_yday))
@@ -425,7 +425,7 @@ class CalculationTests(unittest.TestCase):
format_string = "%Y %H %M %S %w %j %Z"
result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple),
format_string)
- self.failUnless(result.tm_year == self.time_tuple.tm_year and
+ self.assertTrue(result.tm_year == self.time_tuple.tm_year and
result.tm_mon == self.time_tuple.tm_mon and
result.tm_mday == self.time_tuple.tm_mday,
"Calculation of Gregorian date failed;"
@@ -439,7 +439,7 @@ class CalculationTests(unittest.TestCase):
format_string = "%Y %m %d %H %S %j %Z"
result = _strptime._strptime_time(time.strftime(format_string, self.time_tuple),
format_string)
- self.failUnless(result.tm_wday == self.time_tuple.tm_wday,
+ self.assertTrue(result.tm_wday == self.time_tuple.tm_wday,
"Calculation of day of the week failed;"
"%s != %s" % (result.tm_wday, self.time_tuple.tm_wday))
@@ -452,7 +452,7 @@ class CalculationTests(unittest.TestCase):
dt_date = datetime_date(*ymd_tuple)
strp_input = dt_date.strftime(format_string)
strp_output = _strptime._strptime_time(strp_input, format_string)
- self.failUnless(strp_output[:3] == ymd_tuple,
+ self.assertTrue(strp_output[:3] == ymd_tuple,
"%s(%s) test failed w/ '%s': %s != %s (%s != %s)" %
(test_reason, directive, strp_input,
strp_output[:3], ymd_tuple,
@@ -495,8 +495,8 @@ class CacheTests(unittest.TestCase):
_strptime._TimeRE_cache.locale_time.lang = "Ni"
original_time_re = id(_strptime._TimeRE_cache)
_strptime._strptime_time("10", "%d")
- self.failIfEqual(original_time_re, id(_strptime._TimeRE_cache))
- self.failUnlessEqual(len(_strptime._regex_cache), 1)
+ self.assertNotEqual(original_time_re, id(_strptime._TimeRE_cache))
+ self.assertEqual(len(_strptime._regex_cache), 1)
def test_regex_cleanup(self):
# Make sure cached regexes are discarded when cache becomes "full".
@@ -509,7 +509,7 @@ class CacheTests(unittest.TestCase):
_strptime._regex_cache[bogus_key] = None
bogus_key += 1
_strptime._strptime_time("10", "%d")
- self.failUnlessEqual(len(_strptime._regex_cache), 1)
+ self.assertEqual(len(_strptime._regex_cache), 1)
def test_new_localetime(self):
# A new LocaleTime instance should be created when a new TimeRE object
@@ -517,7 +517,7 @@ class CacheTests(unittest.TestCase):
locale_time_id = id(_strptime._TimeRE_cache.locale_time)
_strptime._TimeRE_cache.locale_time.lang = "Ni"
_strptime._strptime_time("10", "%d")
- self.failIfEqual(locale_time_id,
+ self.assertNotEqual(locale_time_id,
id(_strptime._TimeRE_cache.locale_time))
def test_TimeRE_recreation(self):
@@ -538,7 +538,7 @@ class CacheTests(unittest.TestCase):
# Get the new cache object's id.
second_time_re_id = id(_strptime._TimeRE_cache)
# They should not be equal.
- self.failIfEqual(first_time_re_id, second_time_re_id)
+ self.assertNotEqual(first_time_re_id, second_time_re_id)
# Possible test locale is not supported while initial locale is.
# If this is the case just suppress the exception and fall-through
# to the reseting to the original locale.
diff --git a/Lib/test/test_struct.py b/Lib/test/test_struct.py
index 46e777b9d1..39f6daff42 100644
--- a/Lib/test/test_struct.py
+++ b/Lib/test/test_struct.py
@@ -126,7 +126,7 @@ class StructTest(unittest.TestCase):
# encoding of the string when packed.
arg = bytes(arg, 'latin1')
if rev != arg:
- self.assert_(asy)
+ self.assertTrue(asy)
def test_native_qQ(self):
# can't pack -1 as unsigned regardless
@@ -192,7 +192,7 @@ class StructTest(unittest.TestCase):
expected = x
if x < 0:
expected += 1 << self.bitsize
- self.assert_(expected > 0)
+ self.assertTrue(expected > 0)
expected = hex(expected)[2:] # chop "0x"
if len(expected) & 1:
expected = "0" + expected
diff --git a/Lib/test/test_structseq.py b/Lib/test/test_structseq.py
index 124acff9f1..7adca53400 100644
--- a/Lib/test/test_structseq.py
+++ b/Lib/test/test_structseq.py
@@ -28,7 +28,7 @@ class StructSeqTest(unittest.TestCase):
def test_repr(self):
t = time.gmtime()
- self.assert_(repr(t))
+ self.assertTrue(repr(t))
t = time.gmtime(0)
self.assertEqual(repr(t),
"time.struct_time(tm_year=1970, tm_mon=1, tm_mday=1, tm_hour=0, "
@@ -50,8 +50,8 @@ class StructSeqTest(unittest.TestCase):
def test_contains(self):
t1 = time.gmtime()
for item in t1:
- self.assert_(item in t1)
- self.assert_(-42 not in t1)
+ self.assertTrue(item in t1)
+ self.assertTrue(-42 not in t1)
def test_hash(self):
t1 = time.gmtime()
@@ -61,11 +61,11 @@ class StructSeqTest(unittest.TestCase):
t1 = time.gmtime()
t2 = type(t1)(t1)
self.assertEqual(t1, t2)
- self.assert_(not (t1 < t2))
- self.assert_(t1 <= t2)
- self.assert_(not (t1 > t2))
- self.assert_(t1 >= t2)
- self.assert_(not (t1 != t2))
+ self.assertTrue(not (t1 < t2))
+ self.assertTrue(t1 <= t2)
+ self.assertTrue(not (t1 > t2))
+ self.assertTrue(t1 >= t2)
+ self.assertTrue(not (t1 != t2))
def test_fields(self):
t = time.gmtime()
diff --git a/Lib/test/test_subprocess.py b/Lib/test/test_subprocess.py
index 66aebfcf7f..326c996ebe 100644
--- a/Lib/test/test_subprocess.py
+++ b/Lib/test/test_subprocess.py
@@ -491,7 +491,7 @@ class ProcessTestCase(unittest.TestCase):
# but, based on system scheduling we can't control, it's possible
# poll() never returned None. It "should be" very rare that it
# didn't go around at least twice.
- self.assert_(count >= 2)
+ self.assertTrue(count >= 2)
# Subsequent invocations should just return the returncode
self.assertEqual(p.poll(), 0)
@@ -657,7 +657,7 @@ class ProcessTestCase(unittest.TestCase):
p = subprocess.Popen([sys.executable,
"-c", "input()"])
- self.assert_(p.poll() is None, p.poll())
+ self.assertTrue(p.poll() is None, p.poll())
p.send_signal(signal.SIGINT)
self.assertNotEqual(p.wait(), 0)
@@ -665,7 +665,7 @@ class ProcessTestCase(unittest.TestCase):
p = subprocess.Popen([sys.executable,
"-c", "input()"])
- self.assert_(p.poll() is None, p.poll())
+ self.assertTrue(p.poll() is None, p.poll())
p.kill()
self.assertEqual(p.wait(), -signal.SIGKILL)
@@ -673,7 +673,7 @@ class ProcessTestCase(unittest.TestCase):
p = subprocess.Popen([sys.executable,
"-c", "input()"])
- self.assert_(p.poll() is None, p.poll())
+ self.assertTrue(p.poll() is None, p.poll())
p.terminate()
self.assertEqual(p.wait(), -signal.SIGTERM)
@@ -751,7 +751,7 @@ class ProcessTestCase(unittest.TestCase):
p = subprocess.Popen([sys.executable,
"-c", "input()"])
- self.assert_(p.poll() is None, p.poll())
+ self.assertTrue(p.poll() is None, p.poll())
p.send_signal(signal.SIGTERM)
self.assertNotEqual(p.wait(), 0)
@@ -759,7 +759,7 @@ class ProcessTestCase(unittest.TestCase):
p = subprocess.Popen([sys.executable,
"-c", "input()"])
- self.assert_(p.poll() is None, p.poll())
+ self.assertTrue(p.poll() is None, p.poll())
p.kill()
self.assertNotEqual(p.wait(), 0)
@@ -767,7 +767,7 @@ class ProcessTestCase(unittest.TestCase):
p = subprocess.Popen([sys.executable,
"-c", "input()"])
- self.assert_(p.poll() is None, p.poll())
+ self.assertTrue(p.poll() is None, p.poll())
p.terminate()
self.assertNotEqual(p.wait(), 0)
diff --git a/Lib/test/test_symtable.py b/Lib/test/test_symtable.py
index f567c63dc1..7fb368abc2 100644
--- a/Lib/test/test_symtable.py
+++ b/Lib/test/test_symtable.py
@@ -122,7 +122,7 @@ class SymtableTest(unittest.TestCase):
self.assertTrue(self.top.lookup("namespace_test").is_namespace())
self.assertFalse(self.spam.lookup("x").is_namespace())
- self.assert_(self.top.lookup("spam").get_namespace() is self.spam)
+ self.assertTrue(self.top.lookup("spam").get_namespace() is self.spam)
ns_test = self.top.lookup("namespace_test")
self.assertEqual(len(ns_test.get_namespaces()), 2)
self.assertRaises(ValueError, ns_test.get_namespace)
diff --git a/Lib/test/test_sys.py b/Lib/test/test_sys.py
index 8f68cf7326..cac90f4dc9 100644
--- a/Lib/test/test_sys.py
+++ b/Lib/test/test_sys.py
@@ -30,7 +30,7 @@ class SysModuleTest(unittest.TestCase):
dh(None)
self.assertEqual(out.getvalue(), "")
- self.assert_(not hasattr(builtins, "_"))
+ self.assertTrue(not hasattr(builtins, "_"))
dh(42)
self.assertEqual(out.getvalue(), "42\n")
self.assertEqual(builtins._, 42)
@@ -62,12 +62,12 @@ class SysModuleTest(unittest.TestCase):
except ValueError as exc:
eh(*sys.exc_info())
- self.assert_(err.getvalue().endswith("ValueError: 42\n"))
+ self.assertTrue(err.getvalue().endswith("ValueError: 42\n"))
def test_excepthook(self):
with test.support.captured_output("stderr") as stderr:
sys.excepthook(1, '1', 1)
- self.assert_("TypeError: print_exception(): Exception expected for " \
+ self.assertTrue("TypeError: print_exception(): Exception expected for " \
"value, str found" in stderr.getvalue())
# FIXME: testing the code for a lost or replaced excepthook in
@@ -136,7 +136,7 @@ class SysModuleTest(unittest.TestCase):
def test_getdefaultencoding(self):
self.assertRaises(TypeError, sys.getdefaultencoding, 42)
# can't check more than the type, as the user might have changed it
- self.assert_(isinstance(sys.getdefaultencoding(), str))
+ self.assertTrue(isinstance(sys.getdefaultencoding(), str))
# testing sys.settrace() is done in test_trace.py
# testing sys.setprofile() is done in test_profile.py
@@ -203,20 +203,20 @@ class SysModuleTest(unittest.TestCase):
def test_getwindowsversion(self):
if hasattr(sys, "getwindowsversion"):
v = sys.getwindowsversion()
- self.assert_(isinstance(v, tuple))
+ self.assertTrue(isinstance(v, tuple))
self.assertEqual(len(v), 5)
- self.assert_(isinstance(v[0], int))
- self.assert_(isinstance(v[1], int))
- self.assert_(isinstance(v[2], int))
- self.assert_(isinstance(v[3], int))
- self.assert_(isinstance(v[4], str))
+ self.assertTrue(isinstance(v[0], int))
+ self.assertTrue(isinstance(v[1], int))
+ self.assertTrue(isinstance(v[2], int))
+ self.assertTrue(isinstance(v[3], int))
+ self.assertTrue(isinstance(v[4], str))
def test_call_tracing(self):
self.assertRaises(TypeError, sys.call_tracing, type, 2)
def test_dlopenflags(self):
if hasattr(sys, "setdlopenflags"):
- self.assert_(hasattr(sys, "getdlopenflags"))
+ self.assertTrue(hasattr(sys, "getdlopenflags"))
self.assertRaises(TypeError, sys.getdlopenflags, 42)
oldflags = sys.getdlopenflags()
self.assertRaises(TypeError, sys.setdlopenflags)
@@ -237,12 +237,12 @@ class SysModuleTest(unittest.TestCase):
del n
self.assertEqual(sys.getrefcount(None), c)
if hasattr(sys, "gettotalrefcount"):
- self.assert_(isinstance(sys.gettotalrefcount(), int))
+ self.assertTrue(isinstance(sys.gettotalrefcount(), int))
def test_getframe(self):
self.assertRaises(TypeError, sys._getframe, 42, 42)
self.assertRaises(ValueError, sys._getframe, 2000000000)
- self.assert_(
+ self.assertTrue(
SysModuleTest.test_getframe.__code__ \
is sys._getframe().f_code
)
@@ -293,12 +293,12 @@ class SysModuleTest(unittest.TestCase):
d = sys._current_frames()
main_id = _thread.get_ident()
- self.assert_(main_id in d)
- self.assert_(thread_id in d)
+ self.assertTrue(main_id in d)
+ self.assertTrue(thread_id in d)
# Verify that the captured main-thread frame is _this_ frame.
frame = d.pop(main_id)
- self.assert_(frame is sys._getframe())
+ self.assertTrue(frame is sys._getframe())
# Verify that the captured thread frame is blocked in g456, called
# from f123. This is a litte tricky, since various bits of
@@ -316,7 +316,7 @@ class SysModuleTest(unittest.TestCase):
# And the next record must be for g456().
filename, lineno, funcname, sourceline = stack[i+1]
self.assertEqual(funcname, "g456")
- self.assert_(sourceline in ["leave_g.wait()", "entered_g.set()"])
+ self.assertTrue(sourceline in ["leave_g.wait()", "entered_g.set()"])
# Reap the spawned thread.
leave_g.set()
@@ -328,50 +328,50 @@ class SysModuleTest(unittest.TestCase):
# "thread id" 0.
d = sys._current_frames()
self.assertEqual(len(d), 1)
- self.assert_(0 in d)
- self.assert_(d[0] is sys._getframe())
+ self.assertTrue(0 in d)
+ self.assertTrue(d[0] is sys._getframe())
def test_attributes(self):
- self.assert_(isinstance(sys.api_version, int))
- self.assert_(isinstance(sys.argv, list))
- self.assert_(sys.byteorder in ("little", "big"))
- self.assert_(isinstance(sys.builtin_module_names, tuple))
- self.assert_(isinstance(sys.copyright, str))
- self.assert_(isinstance(sys.exec_prefix, str))
- self.assert_(isinstance(sys.executable, str))
+ self.assertTrue(isinstance(sys.api_version, int))
+ self.assertTrue(isinstance(sys.argv, list))
+ self.assertTrue(sys.byteorder in ("little", "big"))
+ self.assertTrue(isinstance(sys.builtin_module_names, tuple))
+ self.assertTrue(isinstance(sys.copyright, str))
+ self.assertTrue(isinstance(sys.exec_prefix, str))
+ self.assertTrue(isinstance(sys.executable, str))
self.assertEqual(len(sys.float_info), 11)
self.assertEqual(sys.float_info.radix, 2)
self.assertEqual(len(sys.int_info), 2)
- self.assert_(sys.int_info.bits_per_digit % 5 == 0)
- self.assert_(sys.int_info.sizeof_digit >= 1)
+ self.assertTrue(sys.int_info.bits_per_digit % 5 == 0)
+ self.assertTrue(sys.int_info.sizeof_digit >= 1)
self.assertEqual(type(sys.int_info.bits_per_digit), int)
self.assertEqual(type(sys.int_info.sizeof_digit), int)
- self.assert_(isinstance(sys.hexversion, int))
- self.assert_(isinstance(sys.maxsize, int))
- self.assert_(isinstance(sys.maxunicode, int))
- self.assert_(isinstance(sys.platform, str))
- self.assert_(isinstance(sys.prefix, str))
- self.assert_(isinstance(sys.version, str))
+ self.assertTrue(isinstance(sys.hexversion, int))
+ self.assertTrue(isinstance(sys.maxsize, int))
+ self.assertTrue(isinstance(sys.maxunicode, int))
+ self.assertTrue(isinstance(sys.platform, str))
+ self.assertTrue(isinstance(sys.prefix, str))
+ self.assertTrue(isinstance(sys.version, str))
vi = sys.version_info
- self.assert_(isinstance(vi[:], tuple))
+ self.assertTrue(isinstance(vi[:], tuple))
self.assertEqual(len(vi), 5)
- self.assert_(isinstance(vi[0], int))
- self.assert_(isinstance(vi[1], int))
- self.assert_(isinstance(vi[2], int))
- self.assert_(vi[3] in ("alpha", "beta", "candidate", "final"))
- self.assert_(isinstance(vi[4], int))
- self.assert_(isinstance(vi.major, int))
- self.assert_(isinstance(vi.minor, int))
- self.assert_(isinstance(vi.micro, int))
- self.assert_(vi.releaselevel in
+ self.assertTrue(isinstance(vi[0], int))
+ self.assertTrue(isinstance(vi[1], int))
+ self.assertTrue(isinstance(vi[2], int))
+ self.assertTrue(vi[3] in ("alpha", "beta", "candidate", "final"))
+ self.assertTrue(isinstance(vi[4], int))
+ self.assertTrue(isinstance(vi.major, int))
+ self.assertTrue(isinstance(vi.minor, int))
+ self.assertTrue(isinstance(vi.micro, int))
+ self.assertTrue(vi.releaselevel in
("alpha", "beta", "candidate", "final"))
- self.assert_(isinstance(vi.serial, int))
+ self.assertTrue(isinstance(vi.serial, int))
self.assertEqual(vi[0], vi.major)
self.assertEqual(vi[1], vi.minor)
self.assertEqual(vi[2], vi.micro)
self.assertEqual(vi[3], vi.releaselevel)
self.assertEqual(vi[4], vi.serial)
- self.assert_(vi > (1,0,0))
+ self.assertTrue(vi > (1,0,0))
def test_43581(self):
# Can't use sys.stdout, as this is a StringIO object when
@@ -381,9 +381,9 @@ class SysModuleTest(unittest.TestCase):
def test_intern(self):
self.assertRaises(TypeError, sys.intern)
s = "never interned before"
- self.assert_(sys.intern(s) is s)
+ self.assertTrue(sys.intern(s) is s)
s2 = s.swapcase().swapcase()
- self.assert_(sys.intern(s2) is s)
+ self.assertTrue(sys.intern(s2) is s)
# Subclasses of string can't be interned, because they
# provide too much opportunity for insane things to happen.
@@ -398,15 +398,15 @@ class SysModuleTest(unittest.TestCase):
def test_sys_flags(self):
- self.failUnless(sys.flags)
+ self.assertTrue(sys.flags)
attrs = ("debug", "division_warning",
"inspect", "interactive", "optimize", "dont_write_bytecode",
"no_user_site", "no_site", "ignore_environment", "verbose",
"bytes_warning")
for attr in attrs:
- self.assert_(hasattr(sys.flags, attr), attr)
+ self.assertTrue(hasattr(sys.flags, attr), attr)
self.assertEqual(type(getattr(sys.flags, attr)), int, attr)
- self.assert_(repr(sys.flags))
+ self.assertTrue(repr(sys.flags))
self.assertEqual(len(sys.flags), len(attrs))
def test_clear_type_cache(self):
diff --git a/Lib/test/test_tarfile.py b/Lib/test/test_tarfile.py
index f4c0035985..76390c76f1 100644
--- a/Lib/test/test_tarfile.py
+++ b/Lib/test/test_tarfile.py
@@ -57,7 +57,7 @@ class UstarReadTest(ReadTest):
tarinfo = self.tar.getmember("ustar/regtype")
fobj = self.tar.extractfile(tarinfo)
data = fobj.read()
- self.assert_((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
+ self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
"regular file extraction failed")
def test_fileobj_readlines(self):
@@ -68,11 +68,11 @@ class UstarReadTest(ReadTest):
lines1 = fobj1.readlines()
lines2 = fobj2.readlines()
- self.assert_(lines1 == lines2,
+ self.assertTrue(lines1 == lines2,
"fileobj.readlines() failed")
- self.assert_(len(lines2) == 114,
+ self.assertTrue(len(lines2) == 114,
"fileobj.readlines() failed")
- self.assert_(lines2[83] == \
+ self.assertTrue(lines2[83] == \
"I will gladly admit that Python is not the fastest running scripting language.\n",
"fileobj.readlines() failed")
@@ -83,7 +83,7 @@ class UstarReadTest(ReadTest):
fobj2 = self.tar.extractfile(tarinfo)
lines1 = fobj1.readlines()
lines2 = list(io.TextIOWrapper(fobj2))
- self.assert_(lines1 == lines2,
+ self.assertTrue(lines1 == lines2,
"fileobj.__iter__() failed")
def test_fileobj_seek(self):
@@ -109,12 +109,12 @@ class UstarReadTest(ReadTest):
self.assertEqual(2048, fobj.tell(),
"seek() to positive relative position failed")
s = fobj.read(10)
- self.assert_(s == data[2048:2058],
+ self.assertTrue(s == data[2048:2058],
"read() after seek failed")
fobj.seek(0, 2)
self.assertEqual(tarinfo.size, fobj.tell(),
"seek() to file's end failed")
- self.assert_(fobj.read() == b"",
+ self.assertTrue(fobj.read() == b"",
"read() at file's end did not return empty string")
fobj.seek(-tarinfo.size, 2)
self.assertEqual(0, fobj.tell(),
@@ -123,13 +123,13 @@ class UstarReadTest(ReadTest):
s1 = fobj.readlines()
fobj.seek(512)
s2 = fobj.readlines()
- self.assert_(s1 == s2,
+ self.assertTrue(s1 == s2,
"readlines() after seek failed")
fobj.seek(0)
self.assertEqual(len(fobj.readline()), fobj.tell(),
"tell() after readline() failed")
fobj.seek(512)
- self.assert_(len(fobj.readline()) + 512 == fobj.tell(),
+ self.assertTrue(len(fobj.readline()) + 512 == fobj.tell(),
"tell() after seek() and readline() failed")
fobj.seek(0)
line = fobj.readline()
@@ -204,7 +204,7 @@ class MiscReadTest(ReadTest):
# Old V7 tars create directory members using an AREGTYPE
# header with a "/" appended to the filename field.
tarinfo = self.tar.getmember("misc/dirtype-old-v7")
- self.assert_(tarinfo.type == tarfile.DIRTYPE,
+ self.assertTrue(tarinfo.type == tarfile.DIRTYPE,
"v7 dirtype failed")
def test_xstar_type(self):
@@ -218,15 +218,15 @@ class MiscReadTest(ReadTest):
def test_check_members(self):
for tarinfo in self.tar:
- self.assert_(int(tarinfo.mtime) == 0o7606136617,
+ self.assertTrue(int(tarinfo.mtime) == 0o7606136617,
"wrong mtime for %s" % tarinfo.name)
if not tarinfo.name.startswith("ustar/"):
continue
- self.assert_(tarinfo.uname == "tarfile",
+ self.assertTrue(tarinfo.uname == "tarfile",
"wrong uname for %s" % tarinfo.name)
def test_find_members(self):
- self.assert_(self.tar.getmembers()[-1].name == "misc/eof",
+ self.assertTrue(self.tar.getmembers()[-1].name == "misc/eof",
"could not find all members")
def test_extract_hardlink(self):
@@ -275,7 +275,7 @@ class StreamReadTest(ReadTest):
tarinfo = self.tar.next() # get "regtype" (can't use getmember)
fobj = self.tar.extractfile(tarinfo)
data = fobj.read()
- self.assert_((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
+ self.assertTrue((len(data), md5sum(data)) == (tarinfo.size, md5_regtype),
"regular file extraction failed")
def test_provoke_stream_error(self):
@@ -292,7 +292,7 @@ class StreamReadTest(ReadTest):
t2 = tar2.next()
if t1 is None:
break
- self.assert_(t2 is not None, "stream.next() failed.")
+ self.assertTrue(t2 is not None, "stream.next() failed.")
if t2.islnk() or t2.issym():
self.assertRaises(tarfile.StreamError, tar2.extractfile, t2)
@@ -302,7 +302,7 @@ class StreamReadTest(ReadTest):
v2 = tar2.extractfile(t2)
if v1 is None:
continue
- self.assert_(v2 is not None, "stream.extractfile() failed")
+ self.assertTrue(v2 is not None, "stream.extractfile() failed")
self.assertEqual(v1.read(), v2.read(), "stream extraction failed")
tar1.close()
@@ -364,7 +364,7 @@ class MemberReadTest(ReadTest):
def _test_member(self, tarinfo, chksum=None, **kwargs):
if chksum is not None:
- self.assert_(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
+ self.assertTrue(md5sum(self.tar.extractfile(tarinfo).read()) == chksum,
"wrong md5sum for %s" % tarinfo.name)
kwargs["mtime"] = 0o7606136617
@@ -375,7 +375,7 @@ class MemberReadTest(ReadTest):
kwargs["uname"] = "tarfile"
kwargs["gname"] = "tarfile"
for k, v in kwargs.items():
- self.assert_(getattr(tarinfo, k) == v,
+ self.assertTrue(getattr(tarinfo, k) == v,
"wrong value in %s field of %s" % (k, tarinfo.name))
def test_find_regtype(self):
@@ -424,7 +424,7 @@ class MemberReadTest(ReadTest):
def test_find_ustar_longname(self):
name = "ustar/" + "12345/" * 39 + "1234567/longname"
- self.assert_(name in self.tar.getnames())
+ self.assertTrue(name in self.tar.getnames())
def test_find_regtype_oldv7(self):
tarinfo = self.tar.getmember("misc/regtype-old-v7")
@@ -445,7 +445,7 @@ class LongnameTest(ReadTest):
tarinfo = self.tar.getmember(longname)
except KeyError:
self.fail("longname not found")
- self.assert_(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
+ self.assertTrue(tarinfo.type != tarfile.DIRTYPE, "read longname as dirtype")
def test_read_longlink(self):
longname = self.subdir + "/" + "123/" * 125 + "longname"
@@ -454,7 +454,7 @@ class LongnameTest(ReadTest):
tarinfo = self.tar.getmember(longlink)
except KeyError:
self.fail("longlink not found")
- self.assert_(tarinfo.linkname == longname, "linkname wrong")
+ self.assertTrue(tarinfo.linkname == longname, "linkname wrong")
def test_truncated_longname(self):
longname = self.subdir + "/" + "123/" * 125 + "longname"
@@ -534,7 +534,7 @@ class WriteTestBase(unittest.TestCase):
tar = tarfile.open(fileobj=fobj, mode=self.mode)
tar.addfile(tarfile.TarInfo("foo"))
tar.close()
- self.assert_(fobj.closed is False, "external fileobjs must never closed")
+ self.assertTrue(fobj.closed is False, "external fileobjs must never closed")
class WriteTest(WriteTestBase):
@@ -553,7 +553,7 @@ class WriteTest(WriteTestBase):
tar.close()
tar = tarfile.open(tmpname)
- self.assert_(tar.getnames()[0] == name,
+ self.assertTrue(tar.getnames()[0] == name,
"failed to store 100 char filename")
tar.close()
@@ -566,7 +566,7 @@ class WriteTest(WriteTestBase):
fobj.close()
tar.add(path)
tar.close()
- self.assert_(os.path.getsize(tmpname) > 0,
+ self.assertTrue(os.path.getsize(tmpname) > 0,
"tarfile is empty")
# The test_*_size tests test for bug #1167128.
@@ -627,16 +627,16 @@ class WriteTest(WriteTestBase):
dstname = os.path.abspath(tmpname)
tar = tarfile.open(tmpname, self.mode)
- self.assert_(tar.name == dstname, "archive name must be absolute")
+ self.assertTrue(tar.name == dstname, "archive name must be absolute")
tar.add(dstname)
- self.assert_(tar.getnames() == [], "added the archive to itself")
+ self.assertTrue(tar.getnames() == [], "added the archive to itself")
cwd = os.getcwd()
os.chdir(TEMPDIR)
tar.add(dstname)
os.chdir(cwd)
- self.assert_(tar.getnames() == [], "added the archive to itself")
+ self.assertTrue(tar.getnames() == [], "added the archive to itself")
def test_exclude(self):
tempdir = os.path.join(TEMPDIR, "exclude")
@@ -677,14 +677,14 @@ class StreamWriteTest(WriteTestBase):
dec = bz2.BZ2Decompressor()
data = open(tmpname, "rb").read()
data = dec.decompress(data)
- self.assert_(len(dec.unused_data) == 0,
+ self.assertTrue(len(dec.unused_data) == 0,
"found trailing data")
else:
fobj = open(tmpname, "rb")
data = fobj.read()
fobj.close()
- self.assert_(data.count(b"\0") == tarfile.RECORDSIZE,
+ self.assertTrue(data.count(b"\0") == tarfile.RECORDSIZE,
"incorrect zero padding")
@@ -724,14 +724,14 @@ class GNUWriteTest(unittest.TestCase):
v1 = self._calc_size(name, link)
v2 = tar.offset
- self.assert_(v1 == v2, "GNU longname/longlink creation failed")
+ self.assertTrue(v1 == v2, "GNU longname/longlink creation failed")
tar.close()
tar = tarfile.open(tmpname)
member = tar.next()
- self.failIf(member is None, "unable to read longname member")
- self.assert_(tarinfo.name == member.name and \
+ self.assertFalse(member is None, "unable to read longname member")
+ self.assertTrue(tarinfo.name == member.name and \
tarinfo.linkname == member.linkname, \
"unable to read longname member")
@@ -791,18 +791,18 @@ class HardlinkTest(unittest.TestCase):
# The same name will be added as a REGTYPE every
# time regardless of st_nlink.
tarinfo = self.tar.gettarinfo(self.foo)
- self.assert_(tarinfo.type == tarfile.REGTYPE,
+ self.assertTrue(tarinfo.type == tarfile.REGTYPE,
"add file as regular failed")
def test_add_hardlink(self):
tarinfo = self.tar.gettarinfo(self.bar)
- self.assert_(tarinfo.type == tarfile.LNKTYPE,
+ self.assertTrue(tarinfo.type == tarfile.LNKTYPE,
"add file as hardlink failed")
def test_dereference_hardlink(self):
self.tar.dereference = True
tarinfo = self.tar.gettarinfo(self.bar)
- self.assert_(tarinfo.type == tarfile.REGTYPE,
+ self.assertTrue(tarinfo.type == tarfile.REGTYPE,
"dereferencing hardlink failed")
@@ -822,10 +822,10 @@ class PaxWriteTest(GNUWriteTest):
tar = tarfile.open(tmpname)
if link:
l = tar.getmembers()[0].linkname
- self.assert_(link == l, "PAX longlink creation failed")
+ self.assertTrue(link == l, "PAX longlink creation failed")
else:
n = tar.getmembers()[0].name
- self.assert_(name == n, "PAX longname creation failed")
+ self.assertTrue(name == n, "PAX longname creation failed")
def test_pax_global_header(self):
pax_headers = {
@@ -847,8 +847,8 @@ class PaxWriteTest(GNUWriteTest):
# Test if all the fields are strings.
for key, val in tar.pax_headers.items():
- self.assert_(type(key) is not bytes)
- self.assert_(type(val) is not bytes)
+ self.assertTrue(type(key) is not bytes)
+ self.assertTrue(type(val) is not bytes)
if key in tarfile.PAX_NUMBER_FIELDS:
try:
tarfile.PAX_NUMBER_FIELDS[key](val)
@@ -916,10 +916,10 @@ class UstarUnicodeTest(unittest.TestCase):
def test_unicode_argument(self):
tar = tarfile.open(tarname, "r", encoding="iso8859-1", errors="strict")
for t in tar:
- self.assert_(type(t.name) is str)
- self.assert_(type(t.linkname) is str)
- self.assert_(type(t.uname) is str)
- self.assert_(type(t.gname) is str)
+ self.assertTrue(type(t.name) is str)
+ self.assertTrue(type(t.linkname) is str)
+ self.assertTrue(type(t.uname) is str)
+ self.assertTrue(type(t.gname) is str)
tar.close()
def test_uname_unicode(self):
diff --git a/Lib/test/test_tempfile.py b/Lib/test/test_tempfile.py
index 69b2e6c2c8..a1bafc25c5 100644
--- a/Lib/test/test_tempfile.py
+++ b/Lib/test/test_tempfile.py
@@ -59,7 +59,7 @@ class TC(unittest.TestCase):
"file '%s' does not end with '%s'" % (nbase, suf))
nbase = nbase[len(pre):len(nbase)-len(suf)]
- self.assert_(self.str_check.match(nbase),
+ self.assertTrue(self.str_check.match(nbase),
"random string '%s' does not match /^[a-zA-Z0-9_-]{6}$/"
% nbase)
@@ -88,7 +88,7 @@ class test_exports(TC):
for key in dict:
if key[0] != '_' and key not in expected:
unexp.append(key)
- self.failUnless(len(unexp) == 0,
+ self.assertTrue(len(unexp) == 0,
"unexpected keys: %s" % unexp)
test_classes.append(test_exports)
@@ -113,7 +113,7 @@ class test__RandomNameSequence(TC):
for i in range(TEST_FILES):
s = next(r)
self.nameCheck(s, '', '', '')
- self.failIf(s in dict)
+ self.assertFalse(s in dict)
dict[s] = 1
def supports_iter(self):
@@ -140,9 +140,9 @@ class test__candidate_tempdir_list(TC):
cand = tempfile._candidate_tempdir_list()
- self.failIf(len(cand) == 0)
+ self.assertFalse(len(cand) == 0)
for c in cand:
- self.assert_(isinstance(c, str),
+ self.assertTrue(isinstance(c, str),
"%s is not a string" % c)
def test_wanted_dirs(self):
@@ -160,14 +160,14 @@ class test__candidate_tempdir_list(TC):
for envname in 'TMPDIR', 'TEMP', 'TMP':
dirname = os.getenv(envname)
if not dirname: raise ValueError
- self.assert_(dirname in cand)
+ self.assertTrue(dirname in cand)
try:
dirname = os.getcwd()
except (AttributeError, os.error):
dirname = os.curdir
- self.assert_(dirname in cand)
+ self.assertTrue(dirname in cand)
# Not practical to try to verify the presence of OS-specific
# paths in this list.
@@ -184,14 +184,14 @@ class test__get_candidate_names(TC):
def test_retval(self):
# _get_candidate_names returns a _RandomNameSequence object
obj = tempfile._get_candidate_names()
- self.assert_(isinstance(obj, tempfile._RandomNameSequence))
+ self.assertTrue(isinstance(obj, tempfile._RandomNameSequence))
def test_same_thing(self):
# _get_candidate_names always returns the same object
a = tempfile._get_candidate_names()
b = tempfile._get_candidate_names()
- self.assert_(a is b)
+ self.assertTrue(a is b)
test_classes.append(test__get_candidate_names)
@@ -300,9 +300,9 @@ class test__mkstemp_inner(TC):
decorated = sys.executable
retval = os.spawnl(os.P_WAIT, sys.executable, decorated, tester, v, fd)
- self.failIf(retval < 0,
+ self.assertFalse(retval < 0,
"child process caught fatal signal %d" % -retval)
- self.failIf(retval > 0, "child process reports failure %d"%retval)
+ self.assertFalse(retval > 0, "child process reports failure %d"%retval)
def test_textmode(self):
# _mkstemp_inner can create files in text mode
@@ -322,8 +322,8 @@ class test_gettempprefix(TC):
# gettempprefix returns a nonempty prefix string
p = tempfile.gettempprefix()
- self.assert_(isinstance(p, str))
- self.assert_(len(p) > 0)
+ self.assertTrue(isinstance(p, str))
+ self.assertTrue(len(p) > 0)
def test_usable_template(self):
# gettempprefix returns a usable prefix string
@@ -354,9 +354,9 @@ class test_gettempdir(TC):
# gettempdir returns a directory which exists
dir = tempfile.gettempdir()
- self.assert_(os.path.isabs(dir) or dir == os.curdir,
+ self.assertTrue(os.path.isabs(dir) or dir == os.curdir,
"%s is not an absolute path" % dir)
- self.assert_(os.path.isdir(dir),
+ self.assertTrue(os.path.isdir(dir),
"%s is not a directory" % dir)
def test_directory_writable(self):
@@ -377,7 +377,7 @@ class test_gettempdir(TC):
a = tempfile.gettempdir()
b = tempfile.gettempdir()
- self.assert_(a is b)
+ self.assertTrue(a is b)
test_classes.append(test_gettempdir)
@@ -580,7 +580,7 @@ class test_NamedTemporaryFile(TC):
def test_creates_named(self):
# NamedTemporaryFile creates files with names
f = tempfile.NamedTemporaryFile()
- self.failUnless(os.path.exists(f.name),
+ self.assertTrue(os.path.exists(f.name),
"NamedTemporaryFile %s does not exist" % f.name)
def test_del_on_close(self):
@@ -590,7 +590,7 @@ class test_NamedTemporaryFile(TC):
f = tempfile.NamedTemporaryFile(dir=dir)
f.write(b'blat')
f.close()
- self.failIf(os.path.exists(f.name),
+ self.assertFalse(os.path.exists(f.name),
"NamedTemporaryFile %s exists after close" % f.name)
finally:
os.rmdir(dir)
@@ -604,7 +604,7 @@ class test_NamedTemporaryFile(TC):
tmp = f.name
f.write(b'blat')
f.close()
- self.failUnless(os.path.exists(f.name),
+ self.assertTrue(os.path.exists(f.name),
"NamedTemporaryFile %s missing after close" % f.name)
finally:
if tmp is not None:
@@ -625,12 +625,12 @@ class test_NamedTemporaryFile(TC):
def test_context_manager(self):
# A NamedTemporaryFile can be used as a context manager
with tempfile.NamedTemporaryFile() as f:
- self.failUnless(os.path.exists(f.name))
- self.failIf(os.path.exists(f.name))
+ self.assertTrue(os.path.exists(f.name))
+ self.assertFalse(os.path.exists(f.name))
def use_closed():
with f:
pass
- self.failUnlessRaises(ValueError, use_closed)
+ self.assertRaises(ValueError, use_closed)
# How to test the mode and bufsize parameters?
@@ -653,21 +653,21 @@ class test_SpooledTemporaryFile(TC):
def test_basic(self):
# SpooledTemporaryFile can create files
f = self.do_create()
- self.failIf(f._rolled)
+ self.assertFalse(f._rolled)
f = self.do_create(max_size=100, pre="a", suf=".txt")
- self.failIf(f._rolled)
+ self.assertFalse(f._rolled)
def test_del_on_close(self):
# A SpooledTemporaryFile is deleted when closed
dir = tempfile.mkdtemp()
try:
f = tempfile.SpooledTemporaryFile(max_size=10, dir=dir)
- self.failIf(f._rolled)
+ self.assertFalse(f._rolled)
f.write(b'blat ' * 5)
- self.failUnless(f._rolled)
+ self.assertTrue(f._rolled)
filename = f.name
f.close()
- self.failIf(isinstance(filename, str) and os.path.exists(filename),
+ self.assertFalse(isinstance(filename, str) and os.path.exists(filename),
"SpooledTemporaryFile %s exists after close" % filename)
finally:
os.rmdir(dir)
@@ -675,46 +675,46 @@ class test_SpooledTemporaryFile(TC):
def test_rewrite_small(self):
# A SpooledTemporaryFile can be written to multiple within the max_size
f = self.do_create(max_size=30)
- self.failIf(f._rolled)
+ self.assertFalse(f._rolled)
for i in range(5):
f.seek(0, 0)
f.write(b'x' * 20)
- self.failIf(f._rolled)
+ self.assertFalse(f._rolled)
def test_write_sequential(self):
# A SpooledTemporaryFile should hold exactly max_size bytes, and roll
# over afterward
f = self.do_create(max_size=30)
- self.failIf(f._rolled)
+ self.assertFalse(f._rolled)
f.write(b'x' * 20)
- self.failIf(f._rolled)
+ self.assertFalse(f._rolled)
f.write(b'x' * 10)
- self.failIf(f._rolled)
+ self.assertFalse(f._rolled)
f.write(b'x')
- self.failUnless(f._rolled)
+ self.assertTrue(f._rolled)
def test_sparse(self):
# A SpooledTemporaryFile that is written late in the file will extend
# when that occurs
f = self.do_create(max_size=30)
- self.failIf(f._rolled)
+ self.assertFalse(f._rolled)
f.seek(100, 0)
- self.failIf(f._rolled)
+ self.assertFalse(f._rolled)
f.write(b'x')
- self.failUnless(f._rolled)
+ self.assertTrue(f._rolled)
def test_fileno(self):
# A SpooledTemporaryFile should roll over to a real file on fileno()
f = self.do_create(max_size=30)
- self.failIf(f._rolled)
- self.failUnless(f.fileno() > 0)
- self.failUnless(f._rolled)
+ self.assertFalse(f._rolled)
+ self.assertTrue(f.fileno() > 0)
+ self.assertTrue(f._rolled)
def test_multiple_close_before_rollover(self):
# A SpooledTemporaryFile can be closed many times without error
f = tempfile.SpooledTemporaryFile()
f.write(b'abc\n')
- self.failIf(f._rolled)
+ self.assertFalse(f._rolled)
f.close()
try:
f.close()
@@ -726,7 +726,7 @@ class test_SpooledTemporaryFile(TC):
# A SpooledTemporaryFile can be closed many times without error
f = tempfile.SpooledTemporaryFile(max_size=1)
f.write(b'abc\n')
- self.failUnless(f._rolled)
+ self.assertTrue(f._rolled)
f.close()
try:
f.close()
@@ -768,51 +768,51 @@ class test_SpooledTemporaryFile(TC):
f.write("\u039B\r\n")
f.seek(0)
self.assertEqual(f.read(), "\u039B\r\n")
- self.failIf(f._rolled)
+ self.assertFalse(f._rolled)
f.write("\u039B" * 20 + "\r\n")
f.seek(0)
self.assertEqual(f.read(), "\u039B\r\n" + ("\u039B" * 20) + "\r\n")
- self.failUnless(f._rolled)
+ self.assertTrue(f._rolled)
def test_context_manager_before_rollover(self):
# A SpooledTemporaryFile can be used as a context manager
with tempfile.SpooledTemporaryFile(max_size=1) as f:
- self.failIf(f._rolled)
- self.failIf(f.closed)
- self.failUnless(f.closed)
+ self.assertFalse(f._rolled)
+ self.assertFalse(f.closed)
+ self.assertTrue(f.closed)
def use_closed():
with f:
pass
- self.failUnlessRaises(ValueError, use_closed)
+ self.assertRaises(ValueError, use_closed)
def test_context_manager_during_rollover(self):
# A SpooledTemporaryFile can be used as a context manager
with tempfile.SpooledTemporaryFile(max_size=1) as f:
- self.failIf(f._rolled)
+ self.assertFalse(f._rolled)
f.write(b'abc\n')
f.flush()
- self.failUnless(f._rolled)
- self.failIf(f.closed)
- self.failUnless(f.closed)
+ self.assertTrue(f._rolled)
+ self.assertFalse(f.closed)
+ self.assertTrue(f.closed)
def use_closed():
with f:
pass
- self.failUnlessRaises(ValueError, use_closed)
+ self.assertRaises(ValueError, use_closed)
def test_context_manager_after_rollover(self):
# A SpooledTemporaryFile can be used as a context manager
f = tempfile.SpooledTemporaryFile(max_size=1)
f.write(b'abc\n')
f.flush()
- self.failUnless(f._rolled)
+ self.assertTrue(f._rolled)
with f:
- self.failIf(f.closed)
- self.failUnless(f.closed)
+ self.assertFalse(f.closed)
+ self.assertTrue(f.closed)
def use_closed():
with f:
pass
- self.failUnlessRaises(ValueError, use_closed)
+ self.assertRaises(ValueError, use_closed)
test_classes.append(test_SpooledTemporaryFile)
diff --git a/Lib/test/test_threading.py b/Lib/test/test_threading.py
index eabd7f4df4..c7a22130e9 100644
--- a/Lib/test/test_threading.py
+++ b/Lib/test/test_threading.py
@@ -41,7 +41,7 @@ class TestThread(threading.Thread):
self.nrunning.inc()
if verbose:
print(self.nrunning.get(), 'tasks are running')
- self.testcase.assert_(self.nrunning.get() <= 3)
+ self.testcase.assertTrue(self.nrunning.get() <= 3)
time.sleep(delay)
if verbose:
@@ -49,7 +49,7 @@ class TestThread(threading.Thread):
with self.mutex:
self.nrunning.dec()
- self.testcase.assert_(self.nrunning.get() >= 0)
+ self.testcase.assertTrue(self.nrunning.get() >= 0)
if verbose:
print('%s is finished. %d tasks are running' %
(self.name, self.nrunning.get()))
@@ -74,18 +74,18 @@ class ThreadTests(unittest.TestCase):
for i in range(NUMTASKS):
t = TestThread("<thread %d>"%i, self, sema, mutex, numrunning)
threads.append(t)
- self.failUnlessEqual(t.ident, None)
- self.assert_(re.match('<TestThread\(.*, initial\)>', repr(t)))
+ self.assertEqual(t.ident, None)
+ self.assertTrue(re.match('<TestThread\(.*, initial\)>', repr(t)))
t.start()
if verbose:
print('waiting for all tasks to complete')
for t in threads:
t.join(NUMTASKS)
- self.assert_(not t.is_alive())
- self.failIfEqual(t.ident, 0)
+ self.assertTrue(not t.is_alive())
+ self.assertNotEqual(t.ident, 0)
self.assertFalse(t.ident is None)
- self.assert_(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
+ self.assertTrue(re.match('<TestThread\(.*, \w+ -?\d+\)>', repr(t)))
if verbose:
print('all tasks done')
self.assertEqual(numrunning.get(), 0)
@@ -143,8 +143,8 @@ class ThreadTests(unittest.TestCase):
tid = _thread.start_new_thread(f, (mutex,))
# Wait for the thread to finish.
mutex.acquire()
- self.assert_(tid in threading._active)
- self.assert_(isinstance(threading._active[tid],
+ self.assertTrue(tid in threading._active)
+ self.assertTrue(isinstance(threading._active[tid],
threading._DummyThread))
del threading._active[tid]
@@ -204,7 +204,7 @@ class ThreadTests(unittest.TestCase):
self.assertTrue(ret)
if verbose:
print(" verifying worker hasn't exited")
- self.assert_(not t.finished)
+ self.assertTrue(not t.finished)
if verbose:
print(" attempting to raise asynch exception in worker")
result = set_async_exc(ctypes.c_long(t.id), exception)
@@ -212,7 +212,7 @@ class ThreadTests(unittest.TestCase):
if verbose:
print(" waiting for worker to say it caught the exception")
worker_saw_exception.wait(timeout=10)
- self.assert_(t.finished)
+ self.assertTrue(t.finished)
if verbose:
print(" all OK -- joining worker")
if t.finished:
@@ -283,8 +283,8 @@ class ThreadTests(unittest.TestCase):
sys.settrace(func)
"""])
- self.failIf(rc == 2, "interpreted was blocked")
- self.failUnless(rc == 0, "Unexpected error")
+ self.assertFalse(rc == 2, "interpreted was blocked")
+ self.assertTrue(rc == 0, "Unexpected error")
def test_enumerate_after_join(self):
@@ -371,8 +371,8 @@ class ThreadJoinOnShutdown(unittest.TestCase):
rc = p.wait()
data = p.stdout.read().decode().replace('\r', '')
self.assertEqual(data, "end of main\nend of thread\n")
- self.failIf(rc == 2, "interpreter was blocked")
- self.failUnless(rc == 0, "Unexpected error")
+ self.assertFalse(rc == 2, "interpreter was blocked")
+ self.assertTrue(rc == 0, "Unexpected error")
def test_1_join_on_shutdown(self):
# The usual case: on exit, wait for a non-daemon thread
diff --git a/Lib/test/test_threading_local.py b/Lib/test/test_threading_local.py
index 977a38ad7c..7f58e0451f 100644
--- a/Lib/test/test_threading_local.py
+++ b/Lib/test/test_threading_local.py
@@ -40,7 +40,7 @@ class ThreadingLocalTest(unittest.TestCase):
local.someothervar = None
gc.collect()
deadlist = [weak for weak in weaklist if weak() is None]
- self.assert_(len(deadlist) in (n-1, n), (n, len(deadlist)))
+ self.assertTrue(len(deadlist) in (n-1, n), (n, len(deadlist)))
def test_derived(self):
# Issue 3088: if there is a threads switch inside the __init__
diff --git a/Lib/test/test_time.py b/Lib/test/test_time.py
index 93d4d36a5d..49a9d17710 100644
--- a/Lib/test/test_time.py
+++ b/Lib/test/test_time.py
@@ -18,9 +18,9 @@ class TimeTestCase(unittest.TestCase):
time.clock()
def test_conversions(self):
- self.assert_(time.ctime(self.t)
+ self.assertTrue(time.ctime(self.t)
== time.asctime(time.localtime(self.t)))
- self.assert_(int(time.mktime(time.localtime(self.t)))
+ self.assertTrue(int(time.mktime(time.localtime(self.t)))
== int(self.t))
def test_sleep(self):
@@ -153,36 +153,36 @@ class TimeTestCase(unittest.TestCase):
time.tzset()
environ['TZ'] = utc
time.tzset()
- self.failUnlessEqual(
+ self.assertEqual(
time.gmtime(xmas2002), time.localtime(xmas2002)
)
- self.failUnlessEqual(time.daylight, 0)
- self.failUnlessEqual(time.timezone, 0)
- self.failUnlessEqual(time.localtime(xmas2002).tm_isdst, 0)
+ self.assertEqual(time.daylight, 0)
+ self.assertEqual(time.timezone, 0)
+ self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
# Make sure we can switch to US/Eastern
environ['TZ'] = eastern
time.tzset()
- self.failIfEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
- self.failUnlessEqual(time.tzname, ('EST', 'EDT'))
- self.failUnlessEqual(len(time.tzname), 2)
- self.failUnlessEqual(time.daylight, 1)
- self.failUnlessEqual(time.timezone, 18000)
- self.failUnlessEqual(time.altzone, 14400)
- self.failUnlessEqual(time.localtime(xmas2002).tm_isdst, 0)
- self.failUnlessEqual(len(time.tzname), 2)
+ self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
+ self.assertEqual(time.tzname, ('EST', 'EDT'))
+ self.assertEqual(len(time.tzname), 2)
+ self.assertEqual(time.daylight, 1)
+ self.assertEqual(time.timezone, 18000)
+ self.assertEqual(time.altzone, 14400)
+ self.assertEqual(time.localtime(xmas2002).tm_isdst, 0)
+ self.assertEqual(len(time.tzname), 2)
# Now go to the southern hemisphere.
environ['TZ'] = victoria
time.tzset()
- self.failIfEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
- self.failUnless(time.tzname[0] == 'AEST', str(time.tzname[0]))
- self.failUnless(time.tzname[1] == 'AEDT', str(time.tzname[1]))
- self.failUnlessEqual(len(time.tzname), 2)
- self.failUnlessEqual(time.daylight, 1)
- self.failUnlessEqual(time.timezone, -36000)
- self.failUnlessEqual(time.altzone, -39600)
- self.failUnlessEqual(time.localtime(xmas2002).tm_isdst, 1)
+ self.assertNotEqual(time.gmtime(xmas2002), time.localtime(xmas2002))
+ self.assertTrue(time.tzname[0] == 'AEST', str(time.tzname[0]))
+ self.assertTrue(time.tzname[1] == 'AEDT', str(time.tzname[1]))
+ self.assertEqual(len(time.tzname), 2)
+ self.assertEqual(time.daylight, 1)
+ self.assertEqual(time.timezone, -36000)
+ self.assertEqual(time.altzone, -39600)
+ self.assertEqual(time.localtime(xmas2002).tm_isdst, 1)
finally:
# Repair TZ environment variable in case any other tests
@@ -214,14 +214,14 @@ class TimeTestCase(unittest.TestCase):
gt1 = time.gmtime(None)
t0 = time.mktime(gt0)
t1 = time.mktime(gt1)
- self.assert_(0 <= (t1-t0) < 0.2)
+ self.assertTrue(0 <= (t1-t0) < 0.2)
def test_localtime_without_arg(self):
lt0 = time.localtime()
lt1 = time.localtime(None)
t0 = time.mktime(lt0)
t1 = time.mktime(lt1)
- self.assert_(0 <= (t1-t0) < 0.2)
+ self.assertTrue(0 <= (t1-t0) < 0.2)
class TestLocale(unittest.TestCase):
def setUp(self):
diff --git a/Lib/test/test_timeout.py b/Lib/test/test_timeout.py
index 264704e7e2..e8e2a6f18f 100644
--- a/Lib/test/test_timeout.py
+++ b/Lib/test/test_timeout.py
@@ -119,11 +119,11 @@ class TimeoutTestCase(unittest.TestCase):
self.sock.settimeout(_timeout)
_t1 = time.time()
- self.failUnlessRaises(socket.error, self.sock.connect, addr)
+ self.assertRaises(socket.error, self.sock.connect, addr)
_t2 = time.time()
_delta = abs(_t1 - _t2)
- self.assert_(_delta < _timeout + self.fuzz,
+ self.assertTrue(_delta < _timeout + self.fuzz,
"timeout (%g) is more than %g seconds more than expected (%g)"
%(_delta, self.fuzz, _timeout))
@@ -134,11 +134,11 @@ class TimeoutTestCase(unittest.TestCase):
self.sock.settimeout(_timeout)
_t1 = time.time()
- self.failUnlessRaises(socket.error, self.sock.recv, 1024)
+ self.assertRaises(socket.error, self.sock.recv, 1024)
_t2 = time.time()
_delta = abs(_t1 - _t2)
- self.assert_(_delta < _timeout + self.fuzz,
+ self.assertTrue(_delta < _timeout + self.fuzz,
"timeout (%g) is %g seconds more than expected (%g)"
%(_delta, self.fuzz, _timeout))
@@ -150,11 +150,11 @@ class TimeoutTestCase(unittest.TestCase):
self.sock.listen(5)
_t1 = time.time()
- self.failUnlessRaises(socket.error, self.sock.accept)
+ self.assertRaises(socket.error, self.sock.accept)
_t2 = time.time()
_delta = abs(_t1 - _t2)
- self.assert_(_delta < _timeout + self.fuzz,
+ self.assertTrue(_delta < _timeout + self.fuzz,
"timeout (%g) is %g seconds more than expected (%g)"
%(_delta, self.fuzz, _timeout))
@@ -166,11 +166,11 @@ class TimeoutTestCase(unittest.TestCase):
self.sock.bind(self.addr_local)
_t1 = time.time()
- self.failUnlessRaises(socket.error, self.sock.recvfrom, 8192)
+ self.assertRaises(socket.error, self.sock.recvfrom, 8192)
_t2 = time.time()
_delta = abs(_t1 - _t2)
- self.assert_(_delta < _timeout + self.fuzz,
+ self.assertTrue(_delta < _timeout + self.fuzz,
"timeout (%g) is %g seconds more than expected (%g)"
%(_delta, self.fuzz, _timeout))
diff --git a/Lib/test/test_tokenize.py b/Lib/test/test_tokenize.py
index 75a7a809b4..f395ed43c9 100644
--- a/Lib/test/test_tokenize.py
+++ b/Lib/test/test_tokenize.py
@@ -629,7 +629,7 @@ class TestTokenizerAdheresToPep0263(TestCase):
behaviour of the interpreter when it encounters a similar condition.
"""
f = 'tokenize_tests-latin1-coding-cookie-and-utf8-bom-sig.txt'
- self.failUnlessRaises(SyntaxError, self._testFile, f)
+ self.assertRaises(SyntaxError, self._testFile, f)
def test_no_coding_cookie_and_utf8_bom(self):
f = 'tokenize_tests-no-coding-cookie-and-utf8-bom-sig-only.txt'
diff --git a/Lib/test/test_traceback.py b/Lib/test/test_traceback.py
index 903323840e..2145710ffc 100644
--- a/Lib/test/test_traceback.py
+++ b/Lib/test/test_traceback.py
@@ -40,15 +40,15 @@ class SyntaxTracebackCases(unittest.TestCase):
err = self.get_exception_format(self.syntax_error_with_caret,
SyntaxError)
self.assertEqual(len(err), 4)
- self.assert_(err[1].strip() == "return x!")
- self.assert_("^" in err[2]) # third line has caret
+ self.assertTrue(err[1].strip() == "return x!")
+ self.assertTrue("^" in err[2]) # third line has caret
self.assertEqual(err[1].find("!"), err[2].find("^")) # in the right place
err = self.get_exception_format(self.syntax_error_with_caret_2,
SyntaxError)
- self.assert_("^" in err[2]) # third line has caret
- self.assert_(err[2].count('\n') == 1) # and no additional newline
- self.assert_(err[1].find("+") == err[2].find("^")) # in the right place
+ self.assertTrue("^" in err[2]) # third line has caret
+ self.assertTrue(err[2].count('\n') == 1) # and no additional newline
+ self.assertTrue(err[1].find("+") == err[2].find("^")) # in the right place
def test_nocaret(self):
if is_jython:
@@ -57,14 +57,14 @@ class SyntaxTracebackCases(unittest.TestCase):
err = self.get_exception_format(self.syntax_error_without_caret,
SyntaxError)
self.assertEqual(len(err), 3)
- self.assert_(err[1].strip() == "[x for x in x] = x")
+ self.assertTrue(err[1].strip() == "[x for x in x] = x")
def test_bad_indentation(self):
err = self.get_exception_format(self.syntax_error_bad_indentation,
IndentationError)
self.assertEqual(len(err), 4)
self.assertEqual(err[1].strip(), "print(2)")
- self.assert_("^" in err[2])
+ self.assertTrue("^" in err[2])
self.assertEqual(err[1].find(")"), err[2].find("^"))
def test_base_exception(self):
@@ -131,13 +131,13 @@ class SyntaxTracebackCases(unittest.TestCase):
err_line = "raise RuntimeError('{0}')".format(message_ascii)
err_msg = "RuntimeError: {0}".format(message_ascii)
- self.assert_(("line %s" % lineno) in stdout[1],
+ self.assertTrue(("line %s" % lineno) in stdout[1],
"Invalid line number: {0!r} instead of {1}".format(
stdout[1], lineno))
- self.assert_(stdout[2].endswith(err_line),
+ self.assertTrue(stdout[2].endswith(err_line),
"Invalid traceback line: {0!r} instead of {1!r}".format(
stdout[2], err_line))
- self.assert_(stdout[3] == err_msg,
+ self.assertTrue(stdout[3] == err_msg,
"Invalid error message: {0!r} instead of {1!r}".format(
stdout[3], err_msg))
@@ -177,9 +177,9 @@ class TracebackFormatTests(unittest.TestCase):
tb_lines = python_fmt.splitlines()
self.assertEquals(len(tb_lines), 3)
banner, location, source_line = tb_lines
- self.assert_(banner.startswith('Traceback'))
- self.assert_(location.startswith(' File'))
- self.assert_(source_line.startswith(' raise'))
+ self.assertTrue(banner.startswith('Traceback'))
+ self.assertTrue(location.startswith(' File'))
+ self.assertTrue(source_line.startswith(' raise'))
cause_message = (
@@ -209,9 +209,9 @@ class BaseExceptionReportingTests:
def check_zero_div(self, msg):
lines = msg.splitlines()
- self.assert_(lines[-3].startswith(' File'))
- self.assert_('1/0 # In zero_div' in lines[-2], lines[-2])
- self.assert_(lines[-1].startswith('ZeroDivisionError'), lines[-1])
+ self.assertTrue(lines[-3].startswith(' File'))
+ self.assertTrue('1/0 # In zero_div' in lines[-2], lines[-2])
+ self.assertTrue(lines[-1].startswith('ZeroDivisionError'), lines[-1])
def test_simple(self):
try:
@@ -220,10 +220,10 @@ class BaseExceptionReportingTests:
e = _
lines = self.get_report(e).splitlines()
self.assertEquals(len(lines), 4)
- self.assert_(lines[0].startswith('Traceback'))
- self.assert_(lines[1].startswith(' File'))
- self.assert_('1/0 # Marker' in lines[2])
- self.assert_(lines[3].startswith('ZeroDivisionError'))
+ self.assertTrue(lines[0].startswith('Traceback'))
+ self.assertTrue(lines[1].startswith(' File'))
+ self.assertTrue('1/0 # Marker' in lines[2])
+ self.assertTrue(lines[3].startswith('ZeroDivisionError'))
def test_cause(self):
def inner_raise():
@@ -237,7 +237,7 @@ class BaseExceptionReportingTests:
self.assertEquals(len(blocks), 3)
self.assertEquals(blocks[1], cause_message)
self.check_zero_div(blocks[0])
- self.assert_('inner_raise() # Marker' in blocks[2])
+ self.assertTrue('inner_raise() # Marker' in blocks[2])
def test_context(self):
def inner_raise():
@@ -251,7 +251,7 @@ class BaseExceptionReportingTests:
self.assertEquals(len(blocks), 3)
self.assertEquals(blocks[1], context_message)
self.check_zero_div(blocks[0])
- self.assert_('inner_raise() # Marker' in blocks[2])
+ self.assertTrue('inner_raise() # Marker' in blocks[2])
def test_cause_recursive(self):
def inner_raise():
@@ -269,11 +269,11 @@ class BaseExceptionReportingTests:
self.assertEquals(len(blocks), 3)
self.assertEquals(blocks[1], cause_message)
# The first block is the KeyError raised from the ZeroDivisionError
- self.assert_('raise KeyError from e' in blocks[0])
- self.assert_('1/0' not in blocks[0])
+ self.assertTrue('raise KeyError from e' in blocks[0])
+ self.assertTrue('1/0' not in blocks[0])
# The second block (apart from the boundary) is the ZeroDivisionError
# re-raised from the KeyError
- self.assert_('inner_raise() # Marker' in blocks[2])
+ self.assertTrue('inner_raise() # Marker' in blocks[2])
self.check_zero_div(blocks[2])
diff --git a/Lib/test/test_tuple.py b/Lib/test/test_tuple.py
index f82af31449..c37adc2545 100644
--- a/Lib/test/test_tuple.py
+++ b/Lib/test/test_tuple.py
@@ -11,7 +11,7 @@ class TupleTest(seq_tests.CommonTest):
self.assertEqual(tuple(), ())
t0_3 = (0, 1, 2, 3)
t0_3_bis = tuple(t0_3)
- self.assert_(t0_3 is t0_3_bis)
+ self.assertTrue(t0_3 is t0_3_bis)
self.assertEqual(tuple([]), ())
self.assertEqual(tuple([0, 1, 2, 3]), (0, 1, 2, 3))
self.assertEqual(tuple(''), ())
@@ -19,8 +19,8 @@ class TupleTest(seq_tests.CommonTest):
def test_truth(self):
super().test_truth()
- self.assert_(not ())
- self.assert_((42, ))
+ self.assertTrue(not ())
+ self.assertTrue((42, ))
def test_len(self):
super().test_len()
@@ -33,14 +33,14 @@ class TupleTest(seq_tests.CommonTest):
u = (0, 1)
u2 = u
u += (2, 3)
- self.assert_(u is not u2)
+ self.assertTrue(u is not u2)
def test_imul(self):
super().test_imul()
u = (0, 1)
u2 = u
u *= 3
- self.assert_(u is not u2)
+ self.assertTrue(u is not u2)
def test_tupleresizebug(self):
# Check that a specific bug in _PyTuple_Resize() is squashed.
@@ -71,7 +71,7 @@ class TupleTest(seq_tests.CommonTest):
inps = base + [(i, j) for i in base for j in xp] + \
[(i, j) for i in xp for j in base] + xp + list(zip(base))
collisions = len(inps) - len(set(map(hash, inps)))
- self.assert_(collisions <= 15)
+ self.assertTrue(collisions <= 15)
def test_repr(self):
l0 = tuple()
diff --git a/Lib/test/test_types.py b/Lib/test/test_types.py
index b85d337481..5f5a9528f8 100644
--- a/Lib/test/test_types.py
+++ b/Lib/test/test_types.py
@@ -549,13 +549,13 @@ class TypesTests(unittest.TestCase):
result = f.__format__(fmt)
self.assertEqual(len(result), 98)
self.assertEqual(result[-7], '.')
- self.assert_(result[:12] in ('112340000000', '112339999999'))
+ self.assertTrue(result[:12] in ('112340000000', '112339999999'))
f = 1.1234e200
for fmt in 'f', 'F':
result = f.__format__(fmt)
self.assertEqual(len(result), 208)
self.assertEqual(result[-7], '.')
- self.assert_(result[:12] in ('112340000000', '112339999999'))
+ self.assertTrue(result[:12] in ('112340000000', '112339999999'))
test( 1.0, 'e', '1.000000e+00')
diff --git a/Lib/test/test_unary.py b/Lib/test/test_unary.py
index 7dd651e8db..b8355647fd 100644
--- a/Lib/test/test_unary.py
+++ b/Lib/test/test_unary.py
@@ -6,12 +6,12 @@ from test.support import run_unittest
class UnaryOpTestCase(unittest.TestCase):
def test_negative(self):
- self.assert_(-2 == 0 - 2)
+ self.assertTrue(-2 == 0 - 2)
self.assertEqual(-0, 0)
self.assertEqual(--2, 2)
- self.assert_(-2 == 0 - 2)
- self.assert_(-2.0 == 0 - 2.0)
- self.assert_(-2j == 0 - 2j)
+ self.assertTrue(-2 == 0 - 2)
+ self.assertTrue(-2.0 == 0 - 2.0)
+ self.assertTrue(-2j == 0 - 2j)
def test_positive(self):
self.assertEqual(+2, 2)
@@ -22,16 +22,16 @@ class UnaryOpTestCase(unittest.TestCase):
self.assertEqual(+2j, 2j)
def test_invert(self):
- self.assert_(-2 == 0 - 2)
+ self.assertTrue(-2 == 0 - 2)
self.assertEqual(-0, 0)
self.assertEqual(--2, 2)
- self.assert_(-2 == 0 - 2)
+ self.assertTrue(-2 == 0 - 2)
def test_no_overflow(self):
nines = "9" * 32
- self.assert_(eval("+" + nines) == 10**32-1)
- self.assert_(eval("-" + nines) == -(10**32-1))
- self.assert_(eval("~" + nines) == ~(10**32-1))
+ self.assertTrue(eval("+" + nines) == 10**32-1)
+ self.assertTrue(eval("-" + nines) == -(10**32-1))
+ self.assertTrue(eval("~" + nines) == ~(10**32-1))
def test_negation_of_exponentiation(self):
# Make sure '**' does the right thing; these form a
diff --git a/Lib/test/test_unicode.py b/Lib/test/test_unicode.py
index 1ff7ee37bd..7f87b438ea 100644
--- a/Lib/test/test_unicode.py
+++ b/Lib/test/test_unicode.py
@@ -48,7 +48,7 @@ class UnicodeTest(
method = getattr(object, methodname)
realresult = method(*args)
self.assertEqual(realresult, result)
- self.assert_(type(realresult) is type(result))
+ self.assertTrue(type(realresult) is type(result))
# if the original is returned make sure that
# this doesn't happen with subclasses
@@ -60,7 +60,7 @@ class UnicodeTest(
method = getattr(object, methodname)
realresult = method(*args)
self.assertEqual(realresult, result)
- self.assert_(object is not realresult)
+ self.assertTrue(object is not realresult)
def test_literals(self):
self.assertEqual('\xff', '\u00ff')
@@ -294,25 +294,25 @@ class UnicodeTest(
self.assertEqual('abc', 'abc')
self.assertEqual('abc', 'abc')
self.assertEqual('abc', 'abc')
- self.assert_('abcd' > 'abc')
- self.assert_('abcd' > 'abc')
- self.assert_('abcd' > 'abc')
- self.assert_('abc' < 'abcd')
- self.assert_('abc' < 'abcd')
- self.assert_('abc' < 'abcd')
+ self.assertTrue('abcd' > 'abc')
+ self.assertTrue('abcd' > 'abc')
+ self.assertTrue('abcd' > 'abc')
+ self.assertTrue('abc' < 'abcd')
+ self.assertTrue('abc' < 'abcd')
+ self.assertTrue('abc' < 'abcd')
if 0:
# Move these tests to a Unicode collation module test...
# Testing UTF-16 code point order comparisons...
# No surrogates, no fixup required.
- self.assert_('\u0061' < '\u20ac')
+ self.assertTrue('\u0061' < '\u20ac')
# Non surrogate below surrogate value, no fixup required
- self.assert_('\u0061' < '\ud800\udc02')
+ self.assertTrue('\u0061' < '\ud800\udc02')
# Non surrogate above surrogate value, fixup required
def test_lecmp(s, s2):
- self.assert_(s < s2)
+ self.assertTrue(s < s2)
def test_fixup(s):
s2 = '\ud800\udc01'
@@ -352,7 +352,7 @@ class UnicodeTest(
test_fixup('\uff61')
# Surrogates on both sides, no fixup required
- self.assert_('\ud800\udc02' < '\ud84d\udc56')
+ self.assertTrue('\ud800\udc02' < '\ud84d\udc56')
def test_islower(self):
string_tests.MixinStrUnicodeUserStringTest.test_islower(self)
@@ -436,32 +436,32 @@ class UnicodeTest(
def test_contains(self):
# Testing Unicode contains method
- self.assert_('a' in 'abdb')
- self.assert_('a' in 'bdab')
- self.assert_('a' in 'bdaba')
- self.assert_('a' in 'bdba')
- self.assert_('a' not in 'bdb')
- self.assert_('a' in 'bdba')
- self.assert_('a' in ('a',1,None))
- self.assert_('a' in (1,None,'a'))
- self.assert_('a' in ('a',1,None))
- self.assert_('a' in (1,None,'a'))
- self.assert_('a' not in ('x',1,'y'))
- self.assert_('a' not in ('x',1,None))
- self.assert_('abcd' not in 'abcxxxx')
- self.assert_('ab' in 'abcd')
- self.assert_('ab' in 'abc')
- self.assert_('ab' in (1,None,'ab'))
- self.assert_('' in 'abc')
- self.assert_('' in '')
- self.assert_('' in 'abc')
- self.assert_('\0' not in 'abc')
- self.assert_('\0' in '\0abc')
- self.assert_('\0' in 'abc\0')
- self.assert_('a' in '\0abc')
- self.assert_('asdf' in 'asdf')
- self.assert_('asdf' not in 'asd')
- self.assert_('asdf' not in '')
+ self.assertTrue('a' in 'abdb')
+ self.assertTrue('a' in 'bdab')
+ self.assertTrue('a' in 'bdaba')
+ self.assertTrue('a' in 'bdba')
+ self.assertTrue('a' not in 'bdb')
+ self.assertTrue('a' in 'bdba')
+ self.assertTrue('a' in ('a',1,None))
+ self.assertTrue('a' in (1,None,'a'))
+ self.assertTrue('a' in ('a',1,None))
+ self.assertTrue('a' in (1,None,'a'))
+ self.assertTrue('a' not in ('x',1,'y'))
+ self.assertTrue('a' not in ('x',1,None))
+ self.assertTrue('abcd' not in 'abcxxxx')
+ self.assertTrue('ab' in 'abcd')
+ self.assertTrue('ab' in 'abc')
+ self.assertTrue('ab' in (1,None,'ab'))
+ self.assertTrue('' in 'abc')
+ self.assertTrue('' in '')
+ self.assertTrue('' in 'abc')
+ self.assertTrue('\0' not in 'abc')
+ self.assertTrue('\0' in '\0abc')
+ self.assertTrue('\0' in 'abc\0')
+ self.assertTrue('a' in '\0abc')
+ self.assertTrue('asdf' in 'asdf')
+ self.assertTrue('asdf' not in 'asd')
+ self.assertTrue('asdf' not in '')
self.assertRaises(TypeError, "abc".__contains__)
diff --git a/Lib/test/test_unicode_file.py b/Lib/test/test_unicode_file.py
index fd561f1cc0..367715a80b 100644
--- a/Lib/test/test_unicode_file.py
+++ b/Lib/test/test_unicode_file.py
@@ -25,19 +25,19 @@ class TestUnicodeFiles(unittest.TestCase):
# Do all the tests we can given only a single filename. The file should
# exist.
def _do_single(self, filename):
- self.failUnless(os.path.exists(filename))
- self.failUnless(os.path.isfile(filename))
- self.failUnless(os.access(filename, os.R_OK))
- self.failUnless(os.path.exists(os.path.abspath(filename)))
- self.failUnless(os.path.isfile(os.path.abspath(filename)))
- self.failUnless(os.access(os.path.abspath(filename), os.R_OK))
+ self.assertTrue(os.path.exists(filename))
+ self.assertTrue(os.path.isfile(filename))
+ self.assertTrue(os.access(filename, os.R_OK))
+ self.assertTrue(os.path.exists(os.path.abspath(filename)))
+ self.assertTrue(os.path.isfile(os.path.abspath(filename)))
+ self.assertTrue(os.access(os.path.abspath(filename), os.R_OK))
os.chmod(filename, 0o777)
os.utime(filename, None)
os.utime(filename, (time.time(), time.time()))
# Copy/rename etc tests using the same filename
self._do_copyish(filename, filename)
# Filename should appear in glob output
- self.failUnless(
+ self.assertTrue(
os.path.abspath(filename)==os.path.abspath(glob.glob(filename)[0]))
# basename should appear in listdir.
path, base = os.path.split(os.path.abspath(filename))
@@ -47,7 +47,7 @@ class TestUnicodeFiles(unittest.TestCase):
base = unicodedata.normalize("NFD", base)
file_list = [unicodedata.normalize("NFD", f) for f in file_list]
- self.failUnless(base in file_list)
+ self.assertTrue(base in file_list)
# Do as many "equivalancy' tests as we can - ie, check that although we
# have different types for the filename, they refer to the same file.
@@ -55,12 +55,12 @@ class TestUnicodeFiles(unittest.TestCase):
# Note we only check "filename1 against filename2" - we don't bother
# checking "filename2 against 1", as we assume we are called again with
# the args reversed.
- self.failUnless(type(filename1)!=type(filename2),
+ self.assertTrue(type(filename1)!=type(filename2),
"No point checking equivalent filenames of the same type")
# stat and lstat should return the same results.
- self.failUnlessEqual(os.stat(filename1),
+ self.assertEqual(os.stat(filename1),
os.stat(filename2))
- self.failUnlessEqual(os.lstat(filename1),
+ self.assertEqual(os.lstat(filename1),
os.lstat(filename2))
# Copy/rename etc tests using equivalent filename
self._do_copyish(filename1, filename2)
@@ -68,19 +68,19 @@ class TestUnicodeFiles(unittest.TestCase):
# Tests that copy, move, etc one file to another.
def _do_copyish(self, filename1, filename2):
# Should be able to rename the file using either name.
- self.failUnless(os.path.isfile(filename1)) # must exist.
+ self.assertTrue(os.path.isfile(filename1)) # must exist.
os.rename(filename1, filename2 + ".new")
- self.failUnless(os.path.isfile(filename1+".new"))
+ self.assertTrue(os.path.isfile(filename1+".new"))
os.rename(filename1 + ".new", filename2)
- self.failUnless(os.path.isfile(filename2))
+ self.assertTrue(os.path.isfile(filename2))
shutil.copy(filename1, filename2 + ".new")
os.unlink(filename1 + ".new") # remove using equiv name.
# And a couple of moves, one using each name.
shutil.move(filename1, filename2 + ".new")
- self.failUnless(not os.path.exists(filename2))
+ self.assertTrue(not os.path.exists(filename2))
shutil.move(filename1 + ".new", filename2)
- self.failUnless(os.path.exists(filename1))
+ self.assertTrue(os.path.exists(filename1))
# Note - due to the implementation of shutil.move,
# it tries a rename first. This only fails on Windows when on
# different file systems - and this test can't ensure that.
@@ -107,7 +107,7 @@ class TestUnicodeFiles(unittest.TestCase):
cwd_result = unicodedata.normalize("NFD", cwd_result)
name_result = unicodedata.normalize("NFD", name_result)
- self.failUnlessEqual(os.path.basename(cwd_result),name_result)
+ self.assertEqual(os.path.basename(cwd_result),name_result)
finally:
os.chdir(cwd)
finally:
@@ -123,7 +123,7 @@ class TestUnicodeFiles(unittest.TestCase):
self._do_single(filename)
finally:
os.unlink(filename)
- self.failUnless(not os.path.exists(filename))
+ self.assertTrue(not os.path.exists(filename))
# and again with os.open.
f = os.open(filename, os.O_CREAT)
os.close(f)
@@ -134,7 +134,7 @@ class TestUnicodeFiles(unittest.TestCase):
def _test_equivalent(self, filename1, filename2):
remove_if_exists(filename1)
- self.failUnless(not os.path.exists(filename2))
+ self.assertTrue(not os.path.exists(filename2))
f = file(filename1, "w")
f.close()
try:
diff --git a/Lib/test/test_unicodedata.py b/Lib/test/test_unicodedata.py
index 285a352160..a658d7bd55 100644
--- a/Lib/test/test_unicodedata.py
+++ b/Lib/test/test_unicodedata.py
@@ -232,7 +232,7 @@ class UnicodeMiscTest(UnicodeDatabaseTest):
if dec != -1:
self.assertEqual(dec, self.db.numeric(c))
count += 1
- self.assert_(count >= 10) # should have tested at least the ASCII digits
+ self.assertTrue(count >= 10) # should have tested at least the ASCII digits
def test_digit_numeric_consistent(self):
# Test that digit and numeric are consistent,
@@ -245,7 +245,7 @@ class UnicodeMiscTest(UnicodeDatabaseTest):
if dec != -1:
self.assertEqual(dec, self.db.numeric(c))
count += 1
- self.assert_(count >= 10) # should have tested at least the ASCII digits
+ self.assertTrue(count >= 10) # should have tested at least the ASCII digits
def test_bug_1704793(self):
self.assertEquals(self.db.lookup("GOTHIC LETTER FAIHU"), '\U00010346')
@@ -253,13 +253,13 @@ class UnicodeMiscTest(UnicodeDatabaseTest):
def test_ucd_510(self):
import unicodedata
# In UCD 5.1.0, a mirrored property changed wrt. UCD 3.2.0
- self.assert_(unicodedata.mirrored("\u0f3a"))
- self.assert_(not unicodedata.ucd_3_2_0.mirrored("\u0f3a"))
+ self.assertTrue(unicodedata.mirrored("\u0f3a"))
+ self.assertTrue(not unicodedata.ucd_3_2_0.mirrored("\u0f3a"))
# Also, we now have two ways of representing
# the upper-case mapping: as delta, or as absolute value
- self.assert_("a".upper()=='A')
- self.assert_("\u1d79".upper()=='\ua77d')
- self.assert_(".".upper()=='.')
+ self.assertTrue("a".upper()=='A')
+ self.assertTrue("\u1d79".upper()=='\ua77d')
+ self.assertTrue(".".upper()=='.')
def test_bug_5828(self):
self.assertEqual("\u1d79".lower(), "\u1d79")
diff --git a/Lib/test/test_urllib.py b/Lib/test/test_urllib.py
index ba742afc14..cae3619138 100644
--- a/Lib/test/test_urllib.py
+++ b/Lib/test/test_urllib.py
@@ -63,7 +63,7 @@ class urlopen_FileTests(unittest.TestCase):
# Make sure object returned by urlopen() has the specified methods
for attr in ("read", "readline", "readlines", "fileno",
"close", "info", "geturl", "getcode", "__iter__"):
- self.assert_(hasattr(self.returned_obj, attr),
+ self.assertTrue(hasattr(self.returned_obj, attr),
"object returned by urlopen() lacks %s attribute" %
attr)
@@ -85,7 +85,7 @@ class urlopen_FileTests(unittest.TestCase):
def test_fileno(self):
file_num = self.returned_obj.fileno()
- self.assert_(isinstance(file_num, int),
+ self.assertTrue(isinstance(file_num, int),
"fileno() did not return an int")
self.assertEqual(os.read(file_num, len(self.text)), self.text,
"Reading on the file descriptor returned by fileno() "
@@ -97,7 +97,7 @@ class urlopen_FileTests(unittest.TestCase):
self.returned_obj.close()
def test_info(self):
- self.assert_(isinstance(self.returned_obj.info(), email.message.Message))
+ self.assertTrue(isinstance(self.returned_obj.info(), email.message.Message))
def test_geturl(self):
self.assertEqual(self.returned_obj.geturl(), self.pathname)
@@ -246,7 +246,7 @@ class urlretrieve_FileTests(unittest.TestCase):
# a headers value is returned.
result = urllib.request.urlretrieve("file:%s" % support.TESTFN)
self.assertEqual(result[0], support.TESTFN)
- self.assert_(isinstance(result[1], email.message.Message),
+ self.assertTrue(isinstance(result[1], email.message.Message),
"did not get a email.message.Message instance as second "
"returned value")
@@ -257,7 +257,7 @@ class urlretrieve_FileTests(unittest.TestCase):
result = urllib.request.urlretrieve(self.constructLocalFileUrl(
support.TESTFN), second_temp)
self.assertEqual(second_temp, result[0])
- self.assert_(os.path.exists(second_temp), "copy of the file was not "
+ self.assertTrue(os.path.exists(second_temp), "copy of the file was not "
"made")
FILE = open(second_temp, 'rb')
try:
@@ -271,9 +271,9 @@ class urlretrieve_FileTests(unittest.TestCase):
def test_reporthook(self):
# Make sure that the reporthook works.
def hooktester(count, block_size, total_size, count_holder=[0]):
- self.assert_(isinstance(count, int))
- self.assert_(isinstance(block_size, int))
- self.assert_(isinstance(total_size, int))
+ self.assertTrue(isinstance(count, int))
+ self.assertTrue(isinstance(block_size, int))
+ self.assertTrue(isinstance(total_size, int))
self.assertEqual(count, count_holder[0])
count_holder[0] = count_holder[0] + 1
second_temp = "%s.2" % support.TESTFN
@@ -727,7 +727,7 @@ class urlencode_Tests(unittest.TestCase):
expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
result = urllib.parse.urlencode(given)
for expected in expect_somewhere:
- self.assert_(expected in result,
+ self.assertTrue(expected in result,
"testing %s: %s not found in %s" %
(test_type, expected, result))
self.assertEqual(result.count('&'), 2,
@@ -736,7 +736,7 @@ class urlencode_Tests(unittest.TestCase):
amp_location = result.index('&')
on_amp_left = result[amp_location - 1]
on_amp_right = result[amp_location + 1]
- self.assert_(on_amp_left.isdigit() and on_amp_right.isdigit(),
+ self.assertTrue(on_amp_left.isdigit() and on_amp_right.isdigit(),
"testing %s: '&' not located in proper place in %s" %
(test_type, result))
self.assertEqual(len(result), (5 * 3) + 2, #5 chars per thing and amps
@@ -774,7 +774,7 @@ class urlencode_Tests(unittest.TestCase):
result = urllib.parse.urlencode(given, True)
for value in given["sequence"]:
expect = "sequence=%s" % value
- self.assert_(expect in result,
+ self.assertTrue(expect in result,
"%s not found in %s" % (expect, result))
self.assertEqual(result.count('&'), 2,
"Expected 2 '&'s, got %s" % result.count('&'))
@@ -915,7 +915,7 @@ class URLopener_Tests(unittest.TestCase):
# def testTimeoutNone(self):
# # global default timeout is ignored
# import socket
-# self.assert_(socket.getdefaulttimeout() is None)
+# self.assertTrue(socket.getdefaulttimeout() is None)
# socket.setdefaulttimeout(30)
# try:
# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
@@ -927,7 +927,7 @@ class URLopener_Tests(unittest.TestCase):
# def testTimeoutDefault(self):
# # global default timeout is used
# import socket
-# self.assert_(socket.getdefaulttimeout() is None)
+# self.assertTrue(socket.getdefaulttimeout() is None)
# socket.setdefaulttimeout(30)
# try:
# ftp = urllib.ftpwrapper("myuser", "mypass", "localhost", 9093, [])
diff --git a/Lib/test/test_urllib2.py b/Lib/test/test_urllib2.py
index 39ec498a99..f996c7195c 100644
--- a/Lib/test/test_urllib2.py
+++ b/Lib/test/test_urllib2.py
@@ -519,15 +519,15 @@ class OpenerDirectorTests(unittest.TestCase):
# *_request
self.assertEqual((handler, name), calls[i])
self.assertEqual(len(args), 1)
- self.assert_(isinstance(args[0], Request))
+ self.assertTrue(isinstance(args[0], Request))
else:
# *_response
self.assertEqual((handler, name), calls[i])
self.assertEqual(len(args), 2)
- self.assert_(isinstance(args[0], Request))
+ self.assertTrue(isinstance(args[0], Request))
# response from opener.open is None, because there's no
# handler that defines http_open to handle it
- self.assert_(args[1] is None or
+ self.assertTrue(args[1] is None or
isinstance(args[1], MockResponse))
@@ -577,7 +577,7 @@ class HandlerTests(unittest.TestCase):
req.timeout = None
r = h.ftp_open(req)
# ftp authentication not yet implemented by FTPHandler
- self.assert_(h.user == h.passwd == "")
+ self.assertTrue(h.user == h.passwd == "")
self.assertEqual(h.host, socket.gethostbyname(host))
self.assertEqual(h.port, port)
self.assertEqual(h.dirs, dirs)
@@ -671,9 +671,9 @@ class HandlerTests(unittest.TestCase):
h.file_open(req)
# XXXX remove OSError when bug fixed
except (urllib.error.URLError, OSError):
- self.assert_(not ftp)
+ self.assertTrue(not ftp)
else:
- self.assert_(o.req is req)
+ self.assertTrue(o.req is req)
self.assertEqual(req.type, "ftp")
def test_http(self):
@@ -754,8 +754,8 @@ class HandlerTests(unittest.TestCase):
r = MockResponse(200, "OK", {}, "")
newreq = h.do_request_(req)
if data is None: # GET
- self.assert_("Content-length" not in req.unredirected_hdrs)
- self.assert_("Content-type" not in req.unredirected_hdrs)
+ self.assertTrue("Content-length" not in req.unredirected_hdrs)
+ self.assertTrue("Content-type" not in req.unredirected_hdrs)
else: # POST
self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
self.assertEqual(req.unredirected_hdrs["Content-type"],
@@ -812,19 +812,19 @@ class HandlerTests(unittest.TestCase):
# all 2xx are passed through
r = MockResponse(200, "OK", {}, "", url)
newr = h.http_response(req, r)
- self.assert_(r is newr)
- self.assert_(not hasattr(o, "proto")) # o.error not called
+ self.assertTrue(r is newr)
+ self.assertTrue(not hasattr(o, "proto")) # o.error not called
r = MockResponse(202, "Accepted", {}, "", url)
newr = h.http_response(req, r)
- self.assert_(r is newr)
- self.assert_(not hasattr(o, "proto")) # o.error not called
+ self.assertTrue(r is newr)
+ self.assertTrue(not hasattr(o, "proto")) # o.error not called
r = MockResponse(206, "Partial content", {}, "", url)
newr = h.http_response(req, r)
- self.assert_(r is newr)
- self.assert_(not hasattr(o, "proto")) # o.error not called
+ self.assertTrue(r is newr)
+ self.assertTrue(not hasattr(o, "proto")) # o.error not called
# anything else calls o.error (and MockOpener returns None, here)
r = MockResponse(502, "Bad gateway", {}, "", url)
- self.assert_(h.http_response(req, r) is None)
+ self.assertTrue(h.http_response(req, r) is None)
self.assertEqual(o.proto, "http") # o.error called
self.assertEqual(o.args, (req, r, 502, "Bad gateway", {}))
@@ -836,12 +836,12 @@ class HandlerTests(unittest.TestCase):
req = Request("http://example.com/")
r = MockResponse(200, "OK", {}, "")
newreq = h.http_request(req)
- self.assert_(cj.ach_req is req is newreq)
+ self.assertTrue(cj.ach_req is req is newreq)
self.assertEquals(req.get_origin_req_host(), "example.com")
- self.assert_(not req.is_unverifiable())
+ self.assertTrue(not req.is_unverifiable())
newr = h.http_response(req, r)
- self.assert_(cj.ec_req is req)
- self.assert_(cj.ec_r is r is newr)
+ self.assertTrue(cj.ec_req is req)
+ self.assertTrue(cj.ec_r is r is newr)
def test_redirect(self):
from_url = "http://example.com/a.html"
@@ -863,12 +863,12 @@ class HandlerTests(unittest.TestCase):
MockHeaders({"location": to_url}))
except urllib.error.HTTPError:
# 307 in response to POST requires user OK
- self.assert_(code == 307 and data is not None)
+ self.assertTrue(code == 307 and data is not None)
self.assertEqual(o.req.get_full_url(), to_url)
try:
self.assertEqual(o.req.get_method(), "GET")
except AttributeError:
- self.assert_(not o.req.has_data())
+ self.assertTrue(not o.req.has_data())
# now it's a GET, there should not be headers regarding content
# (possibly dragged from before being a POST)
@@ -878,8 +878,8 @@ class HandlerTests(unittest.TestCase):
self.assertEqual(o.req.headers["Nonsense"],
"viking=withhold")
- self.assert_("Spam" not in o.req.headers)
- self.assert_("Spam" not in o.req.unredirected_hdrs)
+ self.assertTrue("Spam" not in o.req.headers)
+ self.assertTrue("Spam" not in o.req.unredirected_hdrs)
# loop detection
req = Request(from_url)
@@ -924,7 +924,7 @@ class HandlerTests(unittest.TestCase):
cp = urllib.request.HTTPCookieProcessor(cj)
o = build_test_opener(hh, hdeh, hrh, cp)
o.open("http://www.example.com/")
- self.assert_(not hh.req.has_header("Cookie"))
+ self.assertTrue(not hh.req.has_header("Cookie"))
def test_proxy(self):
o = OpenerDirector()
@@ -1107,7 +1107,7 @@ class MiscTests(unittest.TestCase):
if h.__class__ == handler_class:
break
else:
- self.assert_(False)
+ self.assertTrue(False)
class RequestTests(unittest.TestCase):
@@ -1122,10 +1122,10 @@ class RequestTests(unittest.TestCase):
self.assertEqual("GET", self.get.get_method())
def test_add_data(self):
- self.assert_(not self.get.has_data())
+ self.assertTrue(not self.get.has_data())
self.assertEqual("GET", self.get.get_method())
self.get.add_data("spam")
- self.assert_(self.get.has_data())
+ self.assertTrue(self.get.has_data())
self.assertEqual("POST", self.get.get_method())
def test_get_full_url(self):
@@ -1148,9 +1148,9 @@ class RequestTests(unittest.TestCase):
self.assertEqual("www.python.org", req.get_host())
def test_proxy(self):
- self.assert_(not self.get.has_proxy())
+ self.assertTrue(not self.get.has_proxy())
self.get.set_proxy("www.perl.org", "http")
- self.assert_(self.get.has_proxy())
+ self.assertTrue(self.get.has_proxy())
self.assertEqual("www.python.org", self.get.get_origin_req_host())
self.assertEqual("www.perl.org", self.get.get_host())
diff --git a/Lib/test/test_urllib2_localnet.py b/Lib/test/test_urllib2_localnet.py
index 8641c4b8af..43485c20de 100644
--- a/Lib/test/test_urllib2_localnet.py
+++ b/Lib/test/test_urllib2_localnet.py
@@ -438,10 +438,10 @@ class TestUrlopen(unittest.TestCase):
handler = self.start_server()
open_url = urllib.request.urlopen("http://localhost:%s" % handler.port)
for attr in ("read", "close", "info", "geturl"):
- self.assert_(hasattr(open_url, attr), "object returned from "
+ self.assertTrue(hasattr(open_url, attr), "object returned from "
"urlopen lacks the %s attribute" % attr)
try:
- self.assert_(open_url.read(), "calling 'read' failed")
+ self.assertTrue(open_url.read(), "calling 'read' failed")
finally:
open_url.close()
@@ -451,7 +451,7 @@ class TestUrlopen(unittest.TestCase):
open_url = urllib.request.urlopen(
"http://localhost:%s" % handler.port)
info_obj = open_url.info()
- self.assert_(isinstance(info_obj, email.message.Message),
+ self.assertTrue(isinstance(info_obj, email.message.Message),
"object returned by 'info' is not an instance of "
"email.message.Message")
self.assertEqual(info_obj.get_content_subtype(), "plain")
diff --git a/Lib/test/test_urllib2net.py b/Lib/test/test_urllib2net.py
index dc2d99d0c5..59a73c92d3 100644
--- a/Lib/test/test_urllib2net.py
+++ b/Lib/test/test_urllib2net.py
@@ -82,9 +82,9 @@ class CloseSocketTest(unittest.TestCase):
response = _urlopen_with_retry("http://www.python.org/")
sock = response.fp
- self.assert_(not sock.closed)
+ self.assertTrue(not sock.closed)
response.close()
- self.assert_(sock.closed)
+ self.assertTrue(sock.closed)
class OtherNetworkTests(unittest.TestCase):
def setUp(self):
@@ -172,7 +172,7 @@ class OtherNetworkTests(unittest.TestCase):
if expected_err:
msg = ("Didn't get expected error(s) %s for %s %s, got %s: %s" %
(expected_err, url, req, type(err), err))
- self.assert_(isinstance(err, expected_err), msg)
+ self.assertTrue(isinstance(err, expected_err), msg)
else:
with support.time_out, \
support.socket_peer_reset, \
diff --git a/Lib/test/test_urllibnet.py b/Lib/test/test_urllibnet.py
index e2c8af3127..63e061a9af 100644
--- a/Lib/test/test_urllibnet.py
+++ b/Lib/test/test_urllibnet.py
@@ -62,10 +62,10 @@ class urlopenNetworkTests(unittest.TestCase):
open_url = self.urlopen("http://www.python.org/")
for attr in ("read", "readline", "readlines", "fileno", "close",
"info", "geturl"):
- self.assert_(hasattr(open_url, attr), "object returned from "
+ self.assertTrue(hasattr(open_url, attr), "object returned from "
"urlopen lacks the %s attribute" % attr)
try:
- self.assert_(open_url.read(), "calling 'read' failed")
+ self.assertTrue(open_url.read(), "calling 'read' failed")
finally:
open_url.close()
@@ -73,9 +73,9 @@ class urlopenNetworkTests(unittest.TestCase):
# Test both readline and readlines.
open_url = self.urlopen("http://www.python.org/")
try:
- self.assert_(isinstance(open_url.readline(), bytes),
+ self.assertTrue(isinstance(open_url.readline(), bytes),
"readline did not return bytes")
- self.assert_(isinstance(open_url.readlines(), list),
+ self.assertTrue(isinstance(open_url.readlines(), list),
"readlines did not return a list")
finally:
open_url.close()
@@ -87,7 +87,7 @@ class urlopenNetworkTests(unittest.TestCase):
info_obj = open_url.info()
finally:
open_url.close()
- self.assert_(isinstance(info_obj, email.message.Message),
+ self.assertTrue(isinstance(info_obj, email.message.Message),
"object returned by 'info' is not an instance of "
"email.message.Message")
self.assertEqual(info_obj.get_content_subtype(), "html")
@@ -122,7 +122,7 @@ class urlopenNetworkTests(unittest.TestCase):
fd = open_url.fileno()
FILE = os.fdopen(fd, encoding='utf-8')
try:
- self.assert_(FILE.read(), "reading from file created using fd "
+ self.assertTrue(FILE.read(), "reading from file created using fd "
"returned by fileno failed")
finally:
FILE.close()
@@ -150,11 +150,11 @@ class urlretrieveNetworkTests(unittest.TestCase):
def test_basic(self):
# Test basic functionality.
file_location,info = self.urlretrieve("http://www.python.org/")
- self.assert_(os.path.exists(file_location), "file location returned by"
+ self.assertTrue(os.path.exists(file_location), "file location returned by"
" urlretrieve is not a valid path")
FILE = open(file_location, encoding='utf-8')
try:
- self.assert_(FILE.read(), "reading from the file location returned"
+ self.assertTrue(FILE.read(), "reading from the file location returned"
" by urlretrieve failed")
finally:
FILE.close()
@@ -165,10 +165,10 @@ class urlretrieveNetworkTests(unittest.TestCase):
file_location,info = self.urlretrieve("http://www.python.org/",
support.TESTFN)
self.assertEqual(file_location, support.TESTFN)
- self.assert_(os.path.exists(file_location))
+ self.assertTrue(os.path.exists(file_location))
FILE = open(file_location, encoding='utf-8')
try:
- self.assert_(FILE.read(), "reading from temporary file failed")
+ self.assertTrue(FILE.read(), "reading from temporary file failed")
finally:
FILE.close()
os.unlink(file_location)
@@ -177,7 +177,7 @@ class urlretrieveNetworkTests(unittest.TestCase):
# Make sure header returned as 2nd value from urlretrieve is good.
file_location, header = self.urlretrieve("http://www.python.org/")
os.unlink(file_location)
- self.assert_(isinstance(header, email.message.Message),
+ self.assertTrue(isinstance(header, email.message.Message),
"header is not an instance of email.message.Message")
diff --git a/Lib/test/test_userdict.py b/Lib/test/test_userdict.py
index 5d4a0ff069..9d0a8b118d 100644
--- a/Lib/test/test_userdict.py
+++ b/Lib/test/test_userdict.py
@@ -38,9 +38,9 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
self.assertEqual(collections.UserDict().fromkeys('one two'.split()), d4)
self.assertEqual(collections.UserDict.fromkeys('one two'.split(), 1), d5)
self.assertEqual(collections.UserDict().fromkeys('one two'.split(), 1), d5)
- self.assert_(u1.fromkeys('one two'.split()) is not u1)
- self.assert_(isinstance(u1.fromkeys('one two'.split()), collections.UserDict))
- self.assert_(isinstance(u2.fromkeys('one two'.split()), collections.UserDict))
+ self.assertTrue(u1.fromkeys('one two'.split()) is not u1)
+ self.assertTrue(isinstance(u1.fromkeys('one two'.split()), collections.UserDict))
+ self.assertTrue(isinstance(u2.fromkeys('one two'.split()), collections.UserDict))
# Test __repr__
self.assertEqual(str(u0), str(d0))
@@ -95,7 +95,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
# Test "in".
for i in u2.keys():
- self.assert_(i in u2)
+ self.assertTrue(i in u2)
self.assertEqual(i in u1, i in d1)
self.assertEqual(i in u0, i in d0)
@@ -122,7 +122,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
# Test setdefault
t = collections.UserDict()
self.assertEqual(t.setdefault("x", 42), 42)
- self.assert_("x" in t)
+ self.assertTrue("x" in t)
self.assertEqual(t.setdefault("x", 23), 42)
# Test pop
@@ -152,8 +152,8 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
d = D({1: 2, 3: 4})
self.assertEqual(d[1], 2)
self.assertEqual(d[3], 4)
- self.assert_(2 not in d)
- self.assert_(2 not in d.keys())
+ self.assertTrue(2 not in d)
+ self.assertTrue(2 not in d.keys())
self.assertEqual(d[2], 42)
class E(collections.UserDict):
def __missing__(self, key):
diff --git a/Lib/test/test_uuid.py b/Lib/test/test_uuid.py
index cf9ea84e38..b749abce39 100644
--- a/Lib/test/test_uuid.py
+++ b/Lib/test/test_uuid.py
@@ -293,8 +293,8 @@ class TestUUID(TestCase):
self.assertEqual(universal_local_bit, 0, message)
self.assertNotEqual(node, 0, message)
self.assertNotEqual(node, 0xffffffffffff, message)
- self.assert_(0 <= node, message)
- self.assert_(node < (1 << 48), message)
+ self.assertTrue(0 <= node, message)
+ self.assertTrue(node < (1 << 48), message)
TestUUID.source2node[source] = node
if TestUUID.last_node:
@@ -335,8 +335,8 @@ class TestUUID(TestCase):
def test_random_getnode(self):
node = uuid._random_getnode()
- self.assert_(0 <= node)
- self.assert_(node < (1 <<48))
+ self.assertTrue(0 <= node)
+ self.assertTrue(node < (1 <<48))
def test_unixdll_getnode(self):
import sys
diff --git a/Lib/test/test_warnings.py b/Lib/test/test_warnings.py
index 4bcc210f98..0910055057 100644
--- a/Lib/test/test_warnings.py
+++ b/Lib/test/test_warnings.py
@@ -83,9 +83,9 @@ class FilterTests(object):
self.module.filterwarnings("always", category=UserWarning)
message = "FilterTests.test_always"
self.module.warn(message, UserWarning)
- self.assert_(message, w[-1].message)
+ self.assertTrue(message, w[-1].message)
self.module.warn(message, UserWarning)
- self.assert_(w[-1].message, message)
+ self.assertTrue(w[-1].message, message)
def test_default(self):
with original_warnings.catch_warnings(record=True,
@@ -165,7 +165,7 @@ class FilterTests(object):
text = 'handle normally'
self.module.warn(text)
self.assertEqual(str(w[-1].message), text)
- self.assert_(w[-1].category is UserWarning)
+ self.assertTrue(w[-1].category is UserWarning)
self.module.filterwarnings("ignore", "", Warning, "", 0)
text = 'filtered out'
@@ -178,7 +178,7 @@ class FilterTests(object):
text = 'nonmatching text'
self.module.warn(text)
self.assertEqual(str(w[-1].message), text)
- self.assert_(w[-1].category is UserWarning)
+ self.assertTrue(w[-1].category is UserWarning)
class CFilterTests(BaseTest, FilterTests):
module = c_warnings
@@ -198,7 +198,7 @@ class WarnTests(unittest.TestCase):
text = 'multi %d' %i # Different text on each call.
self.module.warn(text)
self.assertEqual(str(w[-1].message), text)
- self.assert_(w[-1].category is UserWarning)
+ self.assertTrue(w[-1].category is UserWarning)
# Issue 3639
def test_warn_nonstandard_types(self):
@@ -407,7 +407,7 @@ class _WarningsTests(BaseTest):
self.module.resetwarnings()
self.module.filterwarnings("once", category=UserWarning)
self.module.warn_explicit(message, UserWarning, "file", 42)
- self.failUnlessEqual(w[-1].message, message)
+ self.assertEqual(w[-1].message, message)
del w[:]
self.module.warn_explicit(message, UserWarning, "file", 42)
self.assertEquals(len(w), 0)
@@ -415,7 +415,7 @@ class _WarningsTests(BaseTest):
self.module.onceregistry = {}
__warningregistry__ = {}
self.module.warn('onceregistry test')
- self.failUnlessEqual(w[-1].message.args, message.args)
+ self.assertEqual(w[-1].message.args, message.args)
# Removal of onceregistry is okay.
del w[:]
del self.module.onceregistry
@@ -469,7 +469,7 @@ class _WarningsTests(BaseTest):
with support.captured_output('stderr') as stream:
self.module.warn(text)
result = stream.getvalue()
- self.failUnless(text in result)
+ self.assertTrue(text in result)
def test_showwarning_not_callable(self):
with original_warnings.catch_warnings(module=self.module):
@@ -490,19 +490,19 @@ class _WarningsTests(BaseTest):
with support.captured_output('stderr') as stream:
warning_tests.inner(text)
result = stream.getvalue()
- self.failUnlessEqual(result.count('\n'), 2,
+ self.assertEqual(result.count('\n'), 2,
"Too many newlines in %r" % result)
first_line, second_line = result.split('\n', 1)
expected_file = os.path.splitext(warning_tests.__file__)[0] + '.py'
first_line_parts = first_line.rsplit(':', 3)
path, line, warning_class, message = first_line_parts
line = int(line)
- self.failUnlessEqual(expected_file, path)
- self.failUnlessEqual(warning_class, ' ' + UserWarning.__name__)
- self.failUnlessEqual(message, ' ' + text)
+ self.assertEqual(expected_file, path)
+ self.assertEqual(warning_class, ' ' + UserWarning.__name__)
+ self.assertEqual(message, ' ' + text)
expected_line = ' ' + linecache.getline(path, line).strip() + '\n'
assert expected_line
- self.failUnlessEqual(second_line, expected_line)
+ self.assertEqual(second_line, expected_line)
class WarningsDisplayTests(unittest.TestCase):
@@ -519,13 +519,13 @@ class WarningsDisplayTests(unittest.TestCase):
format = "%s:%s: %s: %s\n %s\n"
expect = format % (file_name, line_num, category.__name__, message,
file_line)
- self.failUnlessEqual(expect, self.module.formatwarning(message,
+ self.assertEqual(expect, self.module.formatwarning(message,
category, file_name, line_num))
# Test the 'line' argument.
file_line += " for the win!"
expect = format % (file_name, line_num, category.__name__, message,
file_line)
- self.failUnlessEqual(expect, self.module.formatwarning(message,
+ self.assertEqual(expect, self.module.formatwarning(message,
category, file_name, line_num, file_line))
def test_showwarning(self):
@@ -539,7 +539,7 @@ class WarningsDisplayTests(unittest.TestCase):
line_num)
self.module.showwarning(message, category, file_name, line_num,
file_object)
- self.failUnlessEqual(file_object.getvalue(), expect)
+ self.assertEqual(file_object.getvalue(), expect)
# Test 'line' argument.
expected_file_line += "for the win!"
expect = self.module.formatwarning(message, category, file_name,
@@ -547,7 +547,7 @@ class WarningsDisplayTests(unittest.TestCase):
file_object = StringIO()
self.module.showwarning(message, category, file_name, line_num,
file_object, expected_file_line)
- self.failUnlessEqual(expect, file_object.getvalue())
+ self.assertEqual(expect, file_object.getvalue())
class CWarningsDisplayTests(BaseTest, WarningsDisplayTests):
module = c_warnings
@@ -567,20 +567,20 @@ class CatchWarningTests(BaseTest):
# Ensure both showwarning and filters are restored when recording
with wmod.catch_warnings(module=wmod, record=True):
wmod.filters = wmod.showwarning = object()
- self.assert_(wmod.filters is orig_filters)
- self.assert_(wmod.showwarning is orig_showwarning)
+ self.assertTrue(wmod.filters is orig_filters)
+ self.assertTrue(wmod.showwarning is orig_showwarning)
# Same test, but with recording disabled
with wmod.catch_warnings(module=wmod, record=False):
wmod.filters = wmod.showwarning = object()
- self.assert_(wmod.filters is orig_filters)
- self.assert_(wmod.showwarning is orig_showwarning)
+ self.assertTrue(wmod.filters is orig_filters)
+ self.assertTrue(wmod.showwarning is orig_showwarning)
def test_catch_warnings_recording(self):
wmod = self.module
# Ensure warnings are recorded when requested
with wmod.catch_warnings(module=wmod, record=True) as w:
self.assertEqual(w, [])
- self.assert_(type(w) is list)
+ self.assertTrue(type(w) is list)
wmod.simplefilter("always")
wmod.warn("foo")
self.assertEqual(str(w[-1].message), "foo")
@@ -593,8 +593,8 @@ class CatchWarningTests(BaseTest):
# Ensure warnings are not recorded when not requested
orig_showwarning = wmod.showwarning
with wmod.catch_warnings(module=wmod, record=False) as w:
- self.assert_(w is None)
- self.assert_(wmod.showwarning is orig_showwarning)
+ self.assertTrue(w is None)
+ self.assertTrue(wmod.showwarning is orig_showwarning)
def test_catch_warnings_reentry_guard(self):
wmod = self.module
@@ -615,17 +615,17 @@ class CatchWarningTests(BaseTest):
orig_showwarning = wmod.showwarning
# Ensure default behaviour is not to record warnings
with wmod.catch_warnings(module=wmod) as w:
- self.assert_(w is None)
- self.assert_(wmod.showwarning is orig_showwarning)
- self.assert_(wmod.filters is not orig_filters)
- self.assert_(wmod.filters is orig_filters)
+ self.assertTrue(w is None)
+ self.assertTrue(wmod.showwarning is orig_showwarning)
+ self.assertTrue(wmod.filters is not orig_filters)
+ self.assertTrue(wmod.filters is orig_filters)
if wmod is sys.modules['warnings']:
# Ensure the default module is this one
with wmod.catch_warnings() as w:
- self.assert_(w is None)
- self.assert_(wmod.showwarning is orig_showwarning)
- self.assert_(wmod.filters is not orig_filters)
- self.assert_(wmod.filters is orig_filters)
+ self.assertTrue(w is None)
+ self.assertTrue(wmod.showwarning is orig_showwarning)
+ self.assertTrue(wmod.filters is not orig_filters)
+ self.assertTrue(wmod.filters is orig_filters)
def test_check_warnings(self):
# Explicit tests for the test.support convenience wrapper
diff --git a/Lib/test/test_weakref.py b/Lib/test/test_weakref.py
index 049dba2110..ffa28a6169 100644
--- a/Lib/test/test_weakref.py
+++ b/Lib/test/test_weakref.py
@@ -65,11 +65,11 @@ class ReferencesTestCase(TestBase):
ref1 = weakref.ref(o, self.callback)
ref2 = weakref.ref(o, self.callback)
del o
- self.assert_(ref1() is None,
+ self.assertTrue(ref1() is None,
"expected reference to be invalidated")
- self.assert_(ref2() is None,
+ self.assertTrue(ref2() is None,
"expected reference to be invalidated")
- self.assert_(self.cbcalled == 2,
+ self.assertTrue(self.cbcalled == 2,
"callback not called the right number of times")
def test_multiple_selfref_callbacks(self):
@@ -108,10 +108,10 @@ class ReferencesTestCase(TestBase):
def check_basic_ref(self, factory):
o = factory()
ref = weakref.ref(o)
- self.assert_(ref() is not None,
+ self.assertTrue(ref() is not None,
"weak reference to live object should be live")
o2 = ref()
- self.assert_(o is o2,
+ self.assertTrue(o is o2,
"<ref>() should return original object if live")
def check_basic_callback(self, factory):
@@ -119,9 +119,9 @@ class ReferencesTestCase(TestBase):
o = factory()
ref = weakref.ref(o, self.callback)
del o
- self.assert_(self.cbcalled == 1,
+ self.assertTrue(self.cbcalled == 1,
"callback did not properly set 'cbcalled'")
- self.assert_(ref() is None,
+ self.assertTrue(ref() is None,
"ref2 should be dead after deleting object reference")
def test_ref_reuse(self):
@@ -131,19 +131,19 @@ class ReferencesTestCase(TestBase):
# between these two; it should make no difference
proxy = weakref.proxy(o)
ref2 = weakref.ref(o)
- self.assert_(ref1 is ref2,
+ self.assertTrue(ref1 is ref2,
"reference object w/out callback should be re-used")
o = C()
proxy = weakref.proxy(o)
ref1 = weakref.ref(o)
ref2 = weakref.ref(o)
- self.assert_(ref1 is ref2,
+ self.assertTrue(ref1 is ref2,
"reference object w/out callback should be re-used")
- self.assert_(weakref.getweakrefcount(o) == 2,
+ self.assertTrue(weakref.getweakrefcount(o) == 2,
"wrong weak ref count for object")
del proxy
- self.assert_(weakref.getweakrefcount(o) == 1,
+ self.assertTrue(weakref.getweakrefcount(o) == 1,
"wrong weak ref count for object after deleting proxy")
def test_proxy_reuse(self):
@@ -151,7 +151,7 @@ class ReferencesTestCase(TestBase):
proxy1 = weakref.proxy(o)
ref = weakref.ref(o)
proxy2 = weakref.proxy(o)
- self.assert_(proxy1 is proxy2,
+ self.assertTrue(proxy1 is proxy2,
"proxy object w/out callback should have been re-used")
def test_basic_proxy(self):
@@ -160,14 +160,14 @@ class ReferencesTestCase(TestBase):
L = collections.UserList()
p = weakref.proxy(L)
- self.failIf(p, "proxy for empty UserList should be false")
+ self.assertFalse(p, "proxy for empty UserList should be false")
p.append(12)
self.assertEqual(len(L), 1)
- self.failUnless(p, "proxy for non-empty UserList should be true")
+ self.assertTrue(p, "proxy for non-empty UserList should be true")
p[:] = [2, 3]
self.assertEqual(len(L), 2)
self.assertEqual(len(p), 2)
- self.failUnless(3 in p,
+ self.assertTrue(3 in p,
"proxy didn't support __contains__() properly")
p[1] = 5
self.assertEqual(L[1], 5)
@@ -221,19 +221,19 @@ class ReferencesTestCase(TestBase):
o = Object(1)
p1 = makeref(o, None)
p2 = makeref(o, None)
- self.assert_(p1 is p2, "both callbacks were None in the C API")
+ self.assertTrue(p1 is p2, "both callbacks were None in the C API")
del p1, p2
p1 = makeref(o)
p2 = makeref(o, None)
- self.assert_(p1 is p2, "callbacks were NULL, None in the C API")
+ self.assertTrue(p1 is p2, "callbacks were NULL, None in the C API")
del p1, p2
p1 = makeref(o)
p2 = makeref(o)
- self.assert_(p1 is p2, "both callbacks were NULL in the C API")
+ self.assertTrue(p1 is p2, "both callbacks were NULL in the C API")
del p1, p2
p1 = makeref(o, None)
p2 = makeref(o)
- self.assert_(p1 is p2, "callbacks were None, NULL in the C API")
+ self.assertTrue(p1 is p2, "callbacks were None, NULL in the C API")
def test_callable_proxy(self):
o = Callable()
@@ -241,13 +241,13 @@ class ReferencesTestCase(TestBase):
self.check_proxy(o, ref1)
- self.assert_(type(ref1) is weakref.CallableProxyType,
+ self.assertTrue(type(ref1) is weakref.CallableProxyType,
"proxy is not of callable type")
ref1('twinkies!')
- self.assert_(o.bar == 'twinkies!',
+ self.assertTrue(o.bar == 'twinkies!',
"call through proxy not passed through to original")
ref1(x='Splat.')
- self.assert_(o.bar == 'Splat.',
+ self.assertTrue(o.bar == 'Splat.',
"call through proxy not passed through to original")
# expect due to too few args
@@ -258,24 +258,24 @@ class ReferencesTestCase(TestBase):
def check_proxy(self, o, proxy):
o.foo = 1
- self.assert_(proxy.foo == 1,
+ self.assertTrue(proxy.foo == 1,
"proxy does not reflect attribute addition")
o.foo = 2
- self.assert_(proxy.foo == 2,
+ self.assertTrue(proxy.foo == 2,
"proxy does not reflect attribute modification")
del o.foo
- self.assert_(not hasattr(proxy, 'foo'),
+ self.assertTrue(not hasattr(proxy, 'foo'),
"proxy does not reflect attribute removal")
proxy.foo = 1
- self.assert_(o.foo == 1,
+ self.assertTrue(o.foo == 1,
"object does not reflect attribute addition via proxy")
proxy.foo = 2
- self.assert_(
+ self.assertTrue(
o.foo == 2,
"object does not reflect attribute modification via proxy")
del proxy.foo
- self.assert_(not hasattr(o, 'foo'),
+ self.assertTrue(not hasattr(o, 'foo'),
"object does not reflect attribute removal via proxy")
def test_proxy_deletion(self):
@@ -299,21 +299,21 @@ class ReferencesTestCase(TestBase):
o = C()
ref1 = weakref.ref(o)
ref2 = weakref.ref(o, self.callback)
- self.assert_(weakref.getweakrefcount(o) == 2,
+ self.assertTrue(weakref.getweakrefcount(o) == 2,
"got wrong number of weak reference objects")
proxy1 = weakref.proxy(o)
proxy2 = weakref.proxy(o, self.callback)
- self.assert_(weakref.getweakrefcount(o) == 4,
+ self.assertTrue(weakref.getweakrefcount(o) == 4,
"got wrong number of weak reference objects")
del ref1, ref2, proxy1, proxy2
- self.assert_(weakref.getweakrefcount(o) == 0,
+ self.assertTrue(weakref.getweakrefcount(o) == 0,
"weak reference objects not unlinked from"
" referent when discarded.")
# assumes ints do not support weakrefs
- self.assert_(weakref.getweakrefcount(1) == 0,
+ self.assertTrue(weakref.getweakrefcount(1) == 0,
"got wrong number of weak reference objects for int")
def test_getweakrefs(self):
@@ -321,22 +321,22 @@ class ReferencesTestCase(TestBase):
ref1 = weakref.ref(o, self.callback)
ref2 = weakref.ref(o, self.callback)
del ref1
- self.assert_(weakref.getweakrefs(o) == [ref2],
+ self.assertTrue(weakref.getweakrefs(o) == [ref2],
"list of refs does not match")
o = C()
ref1 = weakref.ref(o, self.callback)
ref2 = weakref.ref(o, self.callback)
del ref2
- self.assert_(weakref.getweakrefs(o) == [ref1],
+ self.assertTrue(weakref.getweakrefs(o) == [ref1],
"list of refs does not match")
del ref1
- self.assert_(weakref.getweakrefs(o) == [],
+ self.assertTrue(weakref.getweakrefs(o) == [],
"list of refs not cleared")
# assumes ints do not support weakrefs
- self.assert_(weakref.getweakrefs(1) == [],
+ self.assertTrue(weakref.getweakrefs(1) == [],
"list of refs does not match for int")
def test_newstyle_number_ops(self):
@@ -344,8 +344,8 @@ class ReferencesTestCase(TestBase):
pass
f = F(2.0)
p = weakref.proxy(f)
- self.assert_(p + 1.0 == 3.0)
- self.assert_(1.0 + p == 3.0) # this used to SEGV
+ self.assertTrue(p + 1.0 == 3.0)
+ self.assertTrue(1.0 + p == 3.0) # this used to SEGV
def test_callbacks_protected(self):
# Callbacks protected from already-set exceptions?
@@ -598,7 +598,7 @@ class ReferencesTestCase(TestBase):
c.wr = weakref.ref(d, callback) # this won't trigger
d.wr = weakref.ref(callback, d.cb) # ditto
external_wr = weakref.ref(callback, safe_callback) # but this will
- self.assert_(external_wr() is callback)
+ self.assertTrue(external_wr() is callback)
# The weakrefs attached to c and d should get cleared, so that
# C.cb is never called. But external_wr isn't part of the cyclic
@@ -681,12 +681,12 @@ class SubclassableWeakrefTestCase(TestBase):
return super().__call__()
o = Object("foo")
mr = MyRef(o, value=24)
- self.assert_(mr() is o)
- self.assert_(mr.called)
+ self.assertTrue(mr() is o)
+ self.assertTrue(mr.called)
self.assertEqual(mr.value, 24)
del o
- self.assert_(mr() is None)
- self.assert_(mr.called)
+ self.assertTrue(mr() is None)
+ self.assertTrue(mr.called)
def test_subclass_refs_dont_replace_standard_refs(self):
class MyRef(weakref.ref):
@@ -694,16 +694,16 @@ class SubclassableWeakrefTestCase(TestBase):
o = Object(42)
r1 = MyRef(o)
r2 = weakref.ref(o)
- self.assert_(r1 is not r2)
+ self.assertTrue(r1 is not r2)
self.assertEqual(weakref.getweakrefs(o), [r2, r1])
self.assertEqual(weakref.getweakrefcount(o), 2)
r3 = MyRef(o)
self.assertEqual(weakref.getweakrefcount(o), 3)
refs = weakref.getweakrefs(o)
self.assertEqual(len(refs), 3)
- self.assert_(r2 is refs[0])
- self.assert_(r1 in refs[1:])
- self.assert_(r3 in refs[1:])
+ self.assertTrue(r2 is refs[0])
+ self.assertTrue(r1 in refs[1:])
+ self.assertTrue(r3 in refs[1:])
def test_subclass_refs_dont_conflate_callbacks(self):
class MyRef(weakref.ref):
@@ -711,10 +711,10 @@ class SubclassableWeakrefTestCase(TestBase):
o = Object(42)
r1 = MyRef(o, id)
r2 = MyRef(o, str)
- self.assert_(r1 is not r2)
+ self.assertTrue(r1 is not r2)
refs = weakref.getweakrefs(o)
- self.assert_(r1 in refs)
- self.assert_(r2 in refs)
+ self.assertTrue(r1 in refs)
+ self.assertTrue(r2 in refs)
def test_subclass_refs_with_slots(self):
class MyRef(weakref.ref):
@@ -731,7 +731,7 @@ class SubclassableWeakrefTestCase(TestBase):
self.assertEqual(r.slot1, "abc")
self.assertEqual(r.slot2, "def")
self.assertEqual(r.meth(), "abcdef")
- self.failIf(hasattr(r, "__dict__"))
+ self.assertFalse(hasattr(r, "__dict__"))
def test_subclass_refs_with_cycle(self):
# Bug #3110
@@ -796,7 +796,7 @@ class MappingTestCase(TestBase):
dict, objects = self.make_weak_valued_dict()
for o in objects:
self.assertEqual(weakref.getweakrefcount(o), 1)
- self.assert_(o is dict[o.arg],
+ self.assertTrue(o is dict[o.arg],
"wrong object returned by weak dict!")
items1 = list(dict.items())
items2 = list(dict.copy().items())
@@ -825,9 +825,9 @@ class MappingTestCase(TestBase):
#
dict, objects = self.make_weak_keyed_dict()
for o in objects:
- self.assert_(weakref.getweakrefcount(o) == 1,
+ self.assertTrue(weakref.getweakrefcount(o) == 1,
"wrong number of weak references to %r!" % o)
- self.assert_(o.arg is dict[o],
+ self.assertTrue(o.arg is dict[o],
"wrong object returned by weak dict!")
items1 = dict.items()
items2 = dict.copy().items()
@@ -836,15 +836,15 @@ class MappingTestCase(TestBase):
del items1, items2
self.assertEqual(len(dict), self.COUNT)
del objects[0]
- self.assert_(len(dict) == (self.COUNT - 1),
+ self.assertTrue(len(dict) == (self.COUNT - 1),
"deleting object did not cause dictionary update")
del objects, o
- self.assert_(len(dict) == 0,
+ self.assertTrue(len(dict) == 0,
"deleting the keys did not clear the dictionary")
o = Object(42)
dict[o] = "What is the meaning of the universe?"
- self.assert_(o in dict)
- self.assert_(34 not in dict)
+ self.assertTrue(o in dict)
+ self.assertTrue(34 not in dict)
def test_weak_keyed_iters(self):
dict, objects = self.make_weak_keyed_dict()
@@ -856,8 +856,8 @@ class MappingTestCase(TestBase):
objects2 = list(objects)
for wr in refs:
ob = wr()
- self.assert_(ob in dict)
- self.assert_(ob in dict)
+ self.assertTrue(ob in dict)
+ self.assertTrue(ob in dict)
self.assertEqual(ob.arg, dict[ob])
objects2.remove(ob)
self.assertEqual(len(objects2), 0)
@@ -867,8 +867,8 @@ class MappingTestCase(TestBase):
self.assertEqual(len(list(dict.keyrefs())), len(objects))
for wr in dict.keyrefs():
ob = wr()
- self.assert_(ob in dict)
- self.assert_(ob in dict)
+ self.assertTrue(ob in dict)
+ self.assertTrue(ob in dict)
self.assertEqual(ob.arg, dict[ob])
objects2.remove(ob)
self.assertEqual(len(objects2), 0)
@@ -968,15 +968,15 @@ class MappingTestCase(TestBase):
k, v = weakdict.popitem()
self.assertEqual(len(weakdict), 1)
if k is key1:
- self.assert_(v is value1)
+ self.assertTrue(v is value1)
else:
- self.assert_(v is value2)
+ self.assertTrue(v is value2)
k, v = weakdict.popitem()
self.assertEqual(len(weakdict), 0)
if k is key1:
- self.assert_(v is value1)
+ self.assertTrue(v is value1)
else:
- self.assert_(v is value2)
+ self.assertTrue(v is value2)
def test_weak_valued_dict_popitem(self):
self.check_popitem(weakref.WeakValueDictionary,
@@ -987,21 +987,21 @@ class MappingTestCase(TestBase):
C(), "value 1", C(), "value 2")
def check_setdefault(self, klass, key, value1, value2):
- self.assert_(value1 is not value2,
+ self.assertTrue(value1 is not value2,
"invalid test"
" -- value parameters must be distinct objects")
weakdict = klass()
o = weakdict.setdefault(key, value1)
- self.assert_(o is value1)
- self.assert_(key in weakdict)
- self.assert_(weakdict.get(key) is value1)
- self.assert_(weakdict[key] is value1)
+ self.assertTrue(o is value1)
+ self.assertTrue(key in weakdict)
+ self.assertTrue(weakdict.get(key) is value1)
+ self.assertTrue(weakdict[key] is value1)
o = weakdict.setdefault(key, value2)
- self.assert_(o is value1)
- self.assert_(key in weakdict)
- self.assert_(weakdict.get(key) is value1)
- self.assert_(weakdict[key] is value1)
+ self.assertTrue(o is value1)
+ self.assertTrue(key in weakdict)
+ self.assertTrue(weakdict.get(key) is value1)
+ self.assertTrue(weakdict[key] is value1)
def test_weak_valued_dict_setdefault(self):
self.check_setdefault(weakref.WeakValueDictionary,
@@ -1020,17 +1020,17 @@ class MappingTestCase(TestBase):
weakdict.update(dict)
self.assertEqual(len(weakdict), len(dict))
for k in weakdict.keys():
- self.assert_(k in dict,
+ self.assertTrue(k in dict,
"mysterious new key appeared in weak dict")
v = dict.get(k)
- self.assert_(v is weakdict[k])
- self.assert_(v is weakdict.get(k))
+ self.assertTrue(v is weakdict[k])
+ self.assertTrue(v is weakdict.get(k))
for k in dict.keys():
- self.assert_(k in weakdict,
+ self.assertTrue(k in weakdict,
"original key disappeared in weak dict")
v = dict[k]
- self.assert_(v is weakdict[k])
- self.assert_(v is weakdict.get(k))
+ self.assertTrue(v is weakdict[k])
+ self.assertTrue(v is weakdict.get(k))
def test_weak_valued_dict_update(self):
self.check_update(weakref.WeakValueDictionary,
@@ -1060,7 +1060,7 @@ class MappingTestCase(TestBase):
self.assertEqual(len(d), 2)
del d['something']
self.assertEqual(len(d), 1)
- self.assert_(list(d.items()) == [('something else', o2)])
+ self.assertTrue(list(d.items()) == [('something else', o2)])
def test_weak_keyed_bad_delitem(self):
d = weakref.WeakKeyDictionary()
diff --git a/Lib/test/test_weakset.py b/Lib/test/test_weakset.py
index 4d54576d15..651efe25b8 100644
--- a/Lib/test/test_weakset.py
+++ b/Lib/test/test_weakset.py
@@ -33,7 +33,7 @@ class TestWeakSet(unittest.TestCase):
for method in dir(set):
if method == 'test_c_api' or method.startswith('_'):
continue
- self.assert_(method in weaksetmethods,
+ self.assertTrue(method in weaksetmethods,
"WeakSet missing method " + method)
def test_new_or_init(self):
@@ -49,9 +49,9 @@ class TestWeakSet(unittest.TestCase):
for c in self.letters:
self.assertEqual(c in self.s, c in self.d)
self.assertRaises(TypeError, self.s.__contains__, [[]])
- self.assert_(self.obj in self.fs)
+ self.assertTrue(self.obj in self.fs)
del self.obj
- self.assert_(ustr('F') not in self.fs)
+ self.assertTrue(ustr('F') not in self.fs)
def test_union(self):
u = self.s.union(self.items2)
@@ -81,8 +81,8 @@ class TestWeakSet(unittest.TestCase):
self.assertEqual(self.s.intersection(C(self.items2)), x)
def test_isdisjoint(self):
- self.assert_(self.s.isdisjoint(WeakSet(self.items2)))
- self.assert_(not self.s.isdisjoint(WeakSet(self.letters)))
+ self.assertTrue(self.s.isdisjoint(WeakSet(self.items2)))
+ self.assertTrue(not self.s.isdisjoint(WeakSet(self.letters)))
def test_and(self):
i = self.s.intersection(self.items2)
@@ -118,19 +118,19 @@ class TestWeakSet(unittest.TestCase):
def test_sub_and_super(self):
pl, ql, rl = map(lambda s: [ustr(c) for c in s], ['ab', 'abcde', 'def'])
p, q, r = map(WeakSet, (pl, ql, rl))
- self.assert_(p < q)
- self.assert_(p <= q)
- self.assert_(q <= q)
- self.assert_(q > p)
- self.assert_(q >= p)
- self.failIf(q < r)
- self.failIf(q <= r)
- self.failIf(q > r)
- self.failIf(q >= r)
- self.assert_(set('a').issubset('abc'))
- self.assert_(set('abc').issuperset('a'))
- self.failIf(set('a').issubset('cbs'))
- self.failIf(set('cbs').issuperset('a'))
+ self.assertTrue(p < q)
+ self.assertTrue(p <= q)
+ self.assertTrue(q <= q)
+ self.assertTrue(q > p)
+ self.assertTrue(q >= p)
+ self.assertFalse(q < r)
+ self.assertFalse(q <= r)
+ self.assertFalse(q > r)
+ self.assertFalse(q >= r)
+ self.assertTrue(set('a').issubset('abc'))
+ self.assertTrue(set('abc').issuperset('a'))
+ self.assertFalse(set('a').issubset('cbs'))
+ self.assertFalse(set('cbs').issuperset('a'))
def test_gc(self):
# Create a nest of cycles to exercise overall ref count check
@@ -148,7 +148,7 @@ class TestWeakSet(unittest.TestCase):
s=H()
f=set()
f.add(s)
- self.assert_(s in f)
+ self.assertTrue(s in f)
f.remove(s)
f.add(s)
f.discard(s)
@@ -183,79 +183,79 @@ class TestWeakSet(unittest.TestCase):
def test_add(self):
x = ustr('Q')
self.s.add(x)
- self.assert_(x in self.s)
+ self.assertTrue(x in self.s)
dup = self.s.copy()
self.s.add(x)
self.assertEqual(self.s, dup)
self.assertRaises(TypeError, self.s.add, [])
self.fs.add(Foo())
- self.assert_(len(self.fs) == 1)
+ self.assertTrue(len(self.fs) == 1)
self.fs.add(self.obj)
- self.assert_(len(self.fs) == 1)
+ self.assertTrue(len(self.fs) == 1)
def test_remove(self):
x = ustr('a')
self.s.remove(x)
- self.assert_(x not in self.s)
+ self.assertTrue(x not in self.s)
self.assertRaises(KeyError, self.s.remove, x)
self.assertRaises(TypeError, self.s.remove, [])
def test_discard(self):
a, q = ustr('a'), ustr('Q')
self.s.discard(a)
- self.assert_(a not in self.s)
+ self.assertTrue(a not in self.s)
self.s.discard(q)
self.assertRaises(TypeError, self.s.discard, [])
def test_pop(self):
for i in range(len(self.s)):
elem = self.s.pop()
- self.assert_(elem not in self.s)
+ self.assertTrue(elem not in self.s)
self.assertRaises(KeyError, self.s.pop)
def test_update(self):
retval = self.s.update(self.items2)
self.assertEqual(retval, None)
for c in (self.items + self.items2):
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
self.assertRaises(TypeError, self.s.update, [[]])
def test_update_set(self):
self.s.update(set(self.items2))
for c in (self.items + self.items2):
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
def test_ior(self):
self.s |= set(self.items2)
for c in (self.items + self.items2):
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
def test_intersection_update(self):
retval = self.s.intersection_update(self.items2)
self.assertEqual(retval, None)
for c in (self.items + self.items2):
if c in self.items2 and c in self.items:
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
else:
- self.assert_(c not in self.s)
+ self.assertTrue(c not in self.s)
self.assertRaises(TypeError, self.s.intersection_update, [[]])
def test_iand(self):
self.s &= set(self.items2)
for c in (self.items + self.items2):
if c in self.items2 and c in self.items:
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
else:
- self.assert_(c not in self.s)
+ self.assertTrue(c not in self.s)
def test_difference_update(self):
retval = self.s.difference_update(self.items2)
self.assertEqual(retval, None)
for c in (self.items + self.items2):
if c in self.items and c not in self.items2:
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
else:
- self.assert_(c not in self.s)
+ self.assertTrue(c not in self.s)
self.assertRaises(TypeError, self.s.difference_update, [[]])
self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]])
@@ -263,27 +263,27 @@ class TestWeakSet(unittest.TestCase):
self.s -= set(self.items2)
for c in (self.items + self.items2):
if c in self.items and c not in self.items2:
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
else:
- self.assert_(c not in self.s)
+ self.assertTrue(c not in self.s)
def test_symmetric_difference_update(self):
retval = self.s.symmetric_difference_update(self.items2)
self.assertEqual(retval, None)
for c in (self.items + self.items2):
if (c in self.items) ^ (c in self.items2):
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
else:
- self.assert_(c not in self.s)
+ self.assertTrue(c not in self.s)
self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]])
def test_ixor(self):
self.s ^= set(self.items2)
for c in (self.items + self.items2):
if (c in self.items) ^ (c in self.items2):
- self.assert_(c in self.s)
+ self.assertTrue(c in self.s)
else:
- self.assert_(c not in self.s)
+ self.assertTrue(c not in self.s)
def test_inplace_on_self(self):
t = self.s.copy()
diff --git a/Lib/test/test_winreg.py b/Lib/test/test_winreg.py
index 3b314dd026..fd288526db 100644
--- a/Lib/test/test_winreg.py
+++ b/Lib/test/test_winreg.py
@@ -53,7 +53,7 @@ class WinregTests(unittest.TestCase):
# Set the default value for this key.
SetValue(root_key, test_key_name, REG_SZ, "Default value")
key = CreateKey(root_key, test_key_name)
- self.assert_(key.handle != 0)
+ self.assertTrue(key.handle != 0)
# Create a sub-key
sub_key = CreateKey(key, subkeystr)
# Give the sub-key some named values
diff --git a/Lib/test/test_wsgiref.py b/Lib/test/test_wsgiref.py
index cfadfbdbdf..438d8ec895 100755
--- a/Lib/test/test_wsgiref.py
+++ b/Lib/test/test_wsgiref.py
@@ -151,7 +151,7 @@ class IntegrationTests(TestCase):
start_response("200 OK", ('Content-Type','text/plain'))
return ["Hello, world!"]
out, err = run_amock(validator(bad_app))
- self.failUnless(out.endswith(
+ self.assertTrue(out.endswith(
b"A server error occurred. Please contact the administrator."
))
self.assertEqual(
@@ -166,7 +166,7 @@ class IntegrationTests(TestCase):
s(b"200 OK", [(b"Content-Type", b"text/plain; charset=utf-8")])
return [b"data"]
out, err = run_amock(validator(bad_app))
- self.failUnless(out.endswith(
+ self.assertTrue(out.endswith(
b"A server error occurred. Please contact the administrator."
))
self.assertEqual(
@@ -181,7 +181,7 @@ class IntegrationTests(TestCase):
])
return [b"data"]
out, err = run_amock(validator(app))
- self.failUnless(err.endswith('"GET / HTTP/1.0" 200 4\n'))
+ self.assertTrue(err.endswith('"GET / HTTP/1.0" 200 4\n'))
ver = sys.version.split()[0].encode('ascii')
self.assertEqual(
b"HTTP/1.0 200 OK\r\n"
@@ -210,16 +210,16 @@ class UtilityTests(TestCase):
env = {}
util.setup_testing_defaults(env)
if isinstance(value,StringIO):
- self.failUnless(isinstance(env[key],StringIO))
+ self.assertTrue(isinstance(env[key],StringIO))
elif isinstance(value,BytesIO):
- self.failUnless(isinstance(env[key],BytesIO))
+ self.assertTrue(isinstance(env[key],BytesIO))
else:
self.assertEqual(env[key],value)
# Check existing value
env = {key:alt}
util.setup_testing_defaults(env)
- self.failUnless(env[key] is alt)
+ self.assertTrue(env[key] is alt)
def checkCrossDefault(self,key,value,**kw):
util.setup_testing_defaults(kw)
@@ -246,15 +246,15 @@ class UtilityTests(TestCase):
compare_generic_iter(make_it,match)
it = make_it()
- self.failIf(it.filelike.closed)
+ self.assertFalse(it.filelike.closed)
for item in it:
pass
- self.failIf(it.filelike.closed)
+ self.assertFalse(it.filelike.closed)
it.close()
- self.failUnless(it.filelike.closed)
+ self.assertTrue(it.filelike.closed)
def testSimpleShifts(self):
@@ -354,14 +354,14 @@ class UtilityTests(TestCase):
"TE Trailers Transfer-Encoding Upgrade"
).split():
for alt in hop, hop.title(), hop.upper(), hop.lower():
- self.failUnless(util.is_hop_by_hop(alt))
+ self.assertTrue(util.is_hop_by_hop(alt))
# Not comprehensive, just a few random header names
for hop in (
"Accept Cache-Control Date Pragma Trailer Via Warning"
).split():
for alt in hop, hop.title(), hop.upper(), hop.lower():
- self.failIf(util.is_hop_by_hop(alt))
+ self.assertFalse(util.is_hop_by_hop(alt))
class HeaderTests(TestCase):
@@ -372,17 +372,17 @@ class HeaderTests(TestCase):
self.assertEqual(Headers(test[:]).keys(), ['x'])
self.assertEqual(Headers(test[:]).values(), ['y'])
self.assertEqual(Headers(test[:]).items(), test)
- self.failIf(Headers(test).items() is test) # must be copy!
+ self.assertFalse(Headers(test).items() is test) # must be copy!
h=Headers([])
del h['foo'] # should not raise an error
h['Foo'] = 'bar'
for m in h.__contains__, h.get, h.get_all, h.__getitem__:
- self.failUnless(m('foo'))
- self.failUnless(m('Foo'))
- self.failUnless(m('FOO'))
- self.failIf(m('bar'))
+ self.assertTrue(m('foo'))
+ self.assertTrue(m('Foo'))
+ self.assertTrue(m('FOO'))
+ self.assertFalse(m('bar'))
self.assertEqual(h['foo'],'bar')
h['foo'] = 'baz'
@@ -438,7 +438,7 @@ class HeaderTests(TestCase):
h.get("content-disposition"))
del h['content-disposition']
- self.assert_(b'content-disposition' not in h)
+ self.assertTrue(b'content-disposition' not in h)
class ErrorHandler(BaseCGIHandler):
@@ -486,7 +486,7 @@ class HandlerTests(TestCase):
if k not in empty:
self.assertEqual(env[k],v)
for k,v in empty.items():
- self.failUnless(k in env)
+ self.assertTrue(k in env)
def testEnviron(self):
h = TestHandler(X="Y")
@@ -499,7 +499,7 @@ class HandlerTests(TestCase):
h = BaseCGIHandler(None,None,None,{})
h.setup_environ()
for key in 'wsgi.url_scheme', 'wsgi.input', 'wsgi.errors':
- self.assert_(key in h.environ)
+ self.assertTrue(key in h.environ)
def testScheme(self):
h=TestHandler(HTTPS="on"); h.setup_environ()
@@ -586,7 +586,7 @@ class HandlerTests(TestCase):
"\r\n%s" % (h.error_status,len(h.error_body),h.error_body)
).encode("iso-8859-1"))
- self.failUnless("AssertionError" in h.stderr.getvalue())
+ self.assertTrue("AssertionError" in h.stderr.getvalue())
def testErrorAfterOutput(self):
MSG = "Some output has been sent"
@@ -599,7 +599,7 @@ class HandlerTests(TestCase):
self.assertEqual(h.stdout.getvalue(),
("Status: 200 OK\r\n"
"\r\n"+MSG).encode("iso-8859-1"))
- self.failUnless("AssertionError" in h.stderr.getvalue())
+ self.assertTrue("AssertionError" in h.stderr.getvalue())
def testHeaderFormats(self):
@@ -638,7 +638,7 @@ class HandlerTests(TestCase):
if proto=="HTTP/0.9":
self.assertEqual(h.stdout.getvalue(),b"")
else:
- self.failUnless(
+ self.assertTrue(
re.match((stdpat%(version,sw)).encode("iso-8859-1"),
h.stdout.getvalue()),
((stdpat%(version,sw)).encode("iso-8859-1"),
diff --git a/Lib/test/test_xdrlib.py b/Lib/test/test_xdrlib.py
index 11a44ff93b..073448ccee 100644
--- a/Lib/test/test_xdrlib.py
+++ b/Lib/test/test_xdrlib.py
@@ -30,15 +30,15 @@ class XDRTest(unittest.TestCase):
self.assertEqual(up.unpack_int(), 42)
self.assertEqual(up.unpack_uint(), 9)
- self.assert_(up.unpack_bool() is True)
+ self.assertTrue(up.unpack_bool() is True)
# remember position
pos = up.get_position()
- self.assert_(up.unpack_bool() is False)
+ self.assertTrue(up.unpack_bool() is False)
# rewind and unpack again
up.set_position(pos)
- self.assert_(up.unpack_bool() is False)
+ self.assertTrue(up.unpack_bool() is False)
self.assertEqual(up.unpack_uhyper(), 45)
self.assertAlmostEqual(up.unpack_float(), 1.9)
diff --git a/Lib/test/test_xmlrpc.py b/Lib/test/test_xmlrpc.py
index d4e8122f44..7bcb6ba37f 100644
--- a/Lib/test/test_xmlrpc.py
+++ b/Lib/test/test_xmlrpc.py
@@ -63,21 +63,21 @@ class XMLRPCTestCase(unittest.TestCase):
def test_cmp_datetime_DateTime(self):
now = datetime.datetime.now()
dt = xmlrpclib.DateTime(now.timetuple())
- self.assert_(dt == now)
- self.assert_(now == dt)
+ self.assertTrue(dt == now)
+ self.assertTrue(now == dt)
then = now + datetime.timedelta(seconds=4)
- self.assert_(then >= dt)
- self.assert_(dt < then)
+ self.assertTrue(then >= dt)
+ self.assertTrue(dt < then)
def test_bug_1164912 (self):
d = xmlrpclib.DateTime()
((new_d,), dummy) = xmlrpclib.loads(xmlrpclib.dumps((d,),
methodresponse=True))
- self.assert_(isinstance(new_d.value, str))
+ self.assertTrue(isinstance(new_d.value, str))
# Check that the output of dumps() is still an 8-bit string
s = xmlrpclib.dumps((new_d,), methodresponse=True)
- self.assert_(isinstance(s, str))
+ self.assertTrue(isinstance(s, str))
def test_newstyle_class(self):
class T(object):
@@ -171,7 +171,7 @@ class FaultTestCase(unittest.TestCase):
# private methods
self.assertRaises(AttributeError,
xmlrpc.server.resolve_dotted_attribute, str, '__add')
- self.assert_(xmlrpc.server.resolve_dotted_attribute(str, 'title'))
+ self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title'))
class DateTimeTestCase(unittest.TestCase):
def test_default(self):
@@ -473,7 +473,7 @@ class SimpleServerTestCase(unittest.TestCase):
self.assertRaises(AttributeError,
xmlrpc.server.resolve_dotted_attribute, str, '__add')
- self.assert_(xmlrpc.server.resolve_dotted_attribute(str, 'title'))
+ self.assertTrue(xmlrpc.server.resolve_dotted_attribute(str, 'title'))
# Get the test to run faster by sending a request with test_simple1.
# This avoids waiting for the socket timeout.
self.test_simple1()
diff --git a/Lib/test/test_xmlrpc_net.py b/Lib/test/test_xmlrpc_net.py
index f6ebbf0192..56b74b2857 100644
--- a/Lib/test/test_xmlrpc_net.py
+++ b/Lib/test/test_xmlrpc_net.py
@@ -33,7 +33,7 @@ class CurrentTimeTest(unittest.TestCase):
delta = dt1 - dt0
# The difference between the system time here and the system
# time on the server should not be too big.
- self.assert_(delta.days <= 1)
+ self.assertTrue(delta.days <= 1)
def test_main():
diff --git a/Lib/test/test_zipfile.py b/Lib/test/test_zipfile.py
index 4b6d82540f..82602c1bbb 100644
--- a/Lib/test/test_zipfile.py
+++ b/Lib/test/test_zipfile.py
@@ -57,9 +57,9 @@ class TestsWithSourceFile(unittest.TestCase):
lines = directory.splitlines()
self.assertEquals(len(lines), 4) # Number of files + header
- self.assert_('File Name' in lines[0])
- self.assert_('Modified' in lines[0])
- self.assert_('Size' in lines[0])
+ self.assertTrue('File Name' in lines[0])
+ self.assertTrue('Modified' in lines[0])
+ self.assertTrue('Size' in lines[0])
fn, date, time, size = lines[1].split()
self.assertEquals(fn, 'another.name')
@@ -69,17 +69,17 @@ class TestsWithSourceFile(unittest.TestCase):
# Check the namelist
names = zipfp.namelist()
self.assertEquals(len(names), 3)
- self.assert_(TESTFN in names)
- self.assert_("another.name" in names)
- self.assert_("strfile" in names)
+ self.assertTrue(TESTFN in names)
+ self.assertTrue("another.name" in names)
+ self.assertTrue("strfile" in names)
# Check infolist
infos = zipfp.infolist()
names = [ i.filename for i in infos ]
self.assertEquals(len(names), 3)
- self.assert_(TESTFN in names)
- self.assert_("another.name" in names)
- self.assert_("strfile" in names)
+ self.assertTrue(TESTFN in names)
+ self.assertTrue("another.name" in names)
+ self.assertTrue("strfile" in names)
for i in infos:
self.assertEquals(i.file_size, len(self.data))
@@ -138,11 +138,11 @@ class TestsWithSourceFile(unittest.TestCase):
data = b""
for info in infos:
data += zipfp.open(info).read()
- self.assert_(data == b"foobar" or data == b"barfoo")
+ self.assertTrue(data == b"foobar" or data == b"barfoo")
data = b""
for info in infos:
data += zipfp.read(info)
- self.assert_(data == b"foobar" or data == b"barfoo")
+ self.assertTrue(data == b"foobar" or data == b"barfoo")
zipfp.close()
def zipRandomOpenTest(self, f, compression):
@@ -439,9 +439,9 @@ class TestZip64InSmallFiles(unittest.TestCase):
lines = directory.splitlines()
self.assertEquals(len(lines), 4) # Number of files + header
- self.assert_('File Name' in lines[0])
- self.assert_('Modified' in lines[0])
- self.assert_('Size' in lines[0])
+ self.assertTrue('File Name' in lines[0])
+ self.assertTrue('Modified' in lines[0])
+ self.assertTrue('Size' in lines[0])
fn, date, time, size = lines[1].split()
self.assertEquals(fn, 'another.name')
@@ -451,17 +451,17 @@ class TestZip64InSmallFiles(unittest.TestCase):
# Check the namelist
names = zipfp.namelist()
self.assertEquals(len(names), 3)
- self.assert_(TESTFN in names)
- self.assert_("another.name" in names)
- self.assert_("strfile" in names)
+ self.assertTrue(TESTFN in names)
+ self.assertTrue("another.name" in names)
+ self.assertTrue("strfile" in names)
# Check infolist
infos = zipfp.infolist()
names = [ i.filename for i in infos ]
self.assertEquals(len(names), 3)
- self.assert_(TESTFN in names)
- self.assert_("another.name" in names)
- self.assert_("strfile" in names)
+ self.assertTrue(TESTFN in names)
+ self.assertTrue("another.name" in names)
+ self.assertTrue("strfile" in names)
for i in infos:
self.assertEquals(i.file_size, len(self.data))
@@ -511,8 +511,8 @@ class PyZipFileTests(unittest.TestCase):
zipfp.writepy(fn)
bn = os.path.basename(fn)
- self.assert_(bn not in zipfp.namelist())
- self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
+ self.assertTrue(bn not in zipfp.namelist())
+ self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
zipfp.close()
@@ -524,8 +524,8 @@ class PyZipFileTests(unittest.TestCase):
zipfp.writepy(fn, "testpackage")
bn = "%s/%s"%("testpackage", os.path.basename(fn))
- self.assert_(bn not in zipfp.namelist())
- self.assert_(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
+ self.assertTrue(bn not in zipfp.namelist())
+ self.assertTrue(bn + 'o' in zipfp.namelist() or bn + 'c' in zipfp.namelist())
zipfp.close()
def testWritePythonPackage(self):
@@ -537,8 +537,8 @@ class PyZipFileTests(unittest.TestCase):
# Check for a couple of modules at different levels of the hieararchy
names = zipfp.namelist()
- self.assert_('email/__init__.pyo' in names or 'email/__init__.pyc' in names)
- self.assert_('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names)
+ self.assertTrue('email/__init__.pyo' in names or 'email/__init__.pyc' in names)
+ self.assertTrue('email/mime/text.pyo' in names or 'email/mime/text.pyc' in names)
def testWritePythonDirectory(self):
os.mkdir(TESTFN2)
@@ -559,9 +559,9 @@ class PyZipFileTests(unittest.TestCase):
zipfp.writepy(TESTFN2)
names = zipfp.namelist()
- self.assert_('mod1.pyc' in names or 'mod1.pyo' in names)
- self.assert_('mod2.pyc' in names or 'mod2.pyo' in names)
- self.assert_('mod2.txt' not in names)
+ self.assertTrue('mod1.pyc' in names or 'mod1.pyo' in names)
+ self.assertTrue('mod2.pyc' in names or 'mod2.pyo' in names)
+ self.assertTrue('mod2.txt' not in names)
finally:
shutil.rmtree(TESTFN2)
@@ -598,7 +598,7 @@ class OtherTests(unittest.TestCase):
except IOError:
self.fail('Could not append data to a non-existent zip file.')
- self.assert_(os.path.exists(TESTFN))
+ self.assertTrue(os.path.exists(TESTFN))
zf = zipfile.ZipFile(TESTFN, 'r')
self.assertEqual(zf.read(filename), content)
@@ -627,19 +627,19 @@ class OtherTests(unittest.TestCase):
with open(TESTFN, "w") as fp:
fp.write("this is not a legal zip file\n")
chk = zipfile.is_zipfile(TESTFN)
- self.assert_(not chk)
+ self.assertTrue(not chk)
# - passing a file object
with open(TESTFN, "rb") as fp:
chk = zipfile.is_zipfile(fp)
- self.assert_(not chk)
+ self.assertTrue(not chk)
# - passing a file-like object
fp = io.BytesIO()
fp.write(b"this is not a legal zip file\n")
chk = zipfile.is_zipfile(fp)
- self.assert_(not chk)
+ self.assertTrue(not chk)
fp.seek(0,0)
chk = zipfile.is_zipfile(fp)
- self.assert_(not chk)
+ self.assertTrue(not chk)
def testIsZipValidFile(self):
# This test checks that the is_zipfile function correctly identifies
@@ -650,21 +650,21 @@ class OtherTests(unittest.TestCase):
zipf.writestr("foo.txt", b"O, for a Muse of Fire!")
zipf.close()
chk = zipfile.is_zipfile(TESTFN)
- self.assert_(chk)
+ self.assertTrue(chk)
# - passing a file object
with open(TESTFN, "rb") as fp:
chk = zipfile.is_zipfile(fp)
- self.assert_(chk)
+ self.assertTrue(chk)
fp.seek(0,0)
zip_contents = fp.read()
# - passing a file-like object
fp = io.BytesIO()
fp.write(zip_contents)
chk = zipfile.is_zipfile(fp)
- self.assert_(chk)
+ self.assertTrue(chk)
fp.seek(0,0)
chk = zipfile.is_zipfile(fp)
- self.assert_(chk)
+ self.assertTrue(chk)
def testNonExistentFileRaisesIOError(self):
# make sure we don't raise an AttributeError when a partially-constructed
diff --git a/Lib/test/test_zipimport.py b/Lib/test/test_zipimport.py
index f41deaf4a1..5d163c77ee 100644
--- a/Lib/test/test_zipimport.py
+++ b/Lib/test/test_zipimport.py
@@ -287,7 +287,7 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
z.close()
zi = zipimport.zipimporter(TEMP_ZIP)
self.assertEquals(data, zi.get_data(name))
- self.assert_('zipimporter object' in repr(zi))
+ self.assertTrue('zipimporter object' in repr(zi))
finally:
z.close()
os.remove(TEMP_ZIP)
@@ -369,7 +369,7 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
s = io.StringIO()
print_tb(tb, 1, s)
- self.failUnless(s.getvalue().endswith(raise_src))
+ self.assertTrue(s.getvalue().endswith(raise_src))
else:
raise AssertionError("This ought to be impossible")
diff --git a/Lib/test/test_zipimport_support.py b/Lib/test/test_zipimport_support.py
index 3f4cd3fca8..94a65fc7b2 100644
--- a/Lib/test/test_zipimport_support.py
+++ b/Lib/test/test_zipimport_support.py
@@ -187,7 +187,7 @@ class ZipSupportTests(ImportHooksBaseTestCase):
print ("Expected line", expected)
print ("Got stdout:")
print (data)
- self.assert_(expected in data)
+ self.assertTrue(expected in data)
zip_name, run_name = _make_test_zip(d, "test_zip",
script_name, '__main__.py')
exit_code, data = _run_python(zip_name)
@@ -196,7 +196,7 @@ class ZipSupportTests(ImportHooksBaseTestCase):
print ("Expected line", expected)
print ("Got stdout:")
print (data)
- self.assert_(expected in data)
+ self.assertTrue(expected in data)
def test_pdb_issue4201(self):
test_src = textwrap.dedent("""\
@@ -211,13 +211,13 @@ class ZipSupportTests(ImportHooksBaseTestCase):
p = _spawn_python(script_name)
p.stdin.write(b'l\n')
data = _kill_python(p).decode()
- self.assert_(script_name in data)
+ self.assertTrue(script_name in data)
zip_name, run_name = _make_test_zip(d, "test_zip",
script_name, '__main__.py')
p = _spawn_python(zip_name)
p.stdin.write(b'l\n')
data = _kill_python(p).decode()
- self.assert_(run_name in data)
+ self.assertTrue(run_name in data)
def test_main():
diff --git a/Lib/test/test_zlib.py b/Lib/test/test_zlib.py
index 71f5ecfbb0..3718ca7533 100644
--- a/Lib/test/test_zlib.py
+++ b/Lib/test/test_zlib.py
@@ -10,7 +10,7 @@ class ChecksumTestCase(unittest.TestCase):
# checksum test cases
def test_crc32start(self):
self.assertEqual(zlib.crc32(b""), zlib.crc32(b"", 0))
- self.assert_(zlib.crc32(b"abc", 0xffffffff))
+ self.assertTrue(zlib.crc32(b"abc", 0xffffffff))
def test_crc32empty(self):
self.assertEqual(zlib.crc32(b"", 0), 0)
@@ -19,7 +19,7 @@ class ChecksumTestCase(unittest.TestCase):
def test_adler32start(self):
self.assertEqual(zlib.adler32(b""), zlib.adler32(b"", 1))
- self.assert_(zlib.adler32(b"abc", 0xffffffff))
+ self.assertTrue(zlib.adler32(b"abc", 0xffffffff))
def test_adler32empty(self):
self.assertEqual(zlib.adler32(b"", 0), 0)
@@ -111,8 +111,8 @@ class CompressObjectTestCase(unittest.TestCase):
y1 = dco.decompress(x1 + x2)
y2 = dco.flush()
self.assertEqual(data, y1 + y2)
- self.assert_(isinstance(dco.unconsumed_tail, bytes))
- self.assert_(isinstance(dco.unused_data, bytes))
+ self.assertTrue(isinstance(dco.unconsumed_tail, bytes))
+ self.assertTrue(isinstance(dco.unused_data, bytes))
def test_compressoptions(self):
# specify lots of options to compressobj()
@@ -157,7 +157,7 @@ class CompressObjectTestCase(unittest.TestCase):
decombuf = zlib.decompress(combuf)
# Test type of return value
- self.assert_(isinstance(decombuf, bytes))
+ self.assertTrue(isinstance(decombuf, bytes))
self.assertEqual(data, decombuf)
@@ -208,7 +208,7 @@ class CompressObjectTestCase(unittest.TestCase):
while cb:
#max_length = 1 + len(cb)//10
chunk = dco.decompress(cb, dcx)
- self.failIf(len(chunk) > dcx,
+ self.assertFalse(len(chunk) > dcx,
'chunk too big (%d>%d)' % (len(chunk), dcx))
bufs.append(chunk)
cb = dco.unconsumed_tail
@@ -233,7 +233,7 @@ class CompressObjectTestCase(unittest.TestCase):
while cb:
max_length = 1 + len(cb)//10
chunk = dco.decompress(cb, max_length)
- self.failIf(len(chunk) > max_length,
+ self.assertFalse(len(chunk) > max_length,
'chunk too big (%d>%d)' % (len(chunk),max_length))
bufs.append(chunk)
cb = dco.unconsumed_tail
@@ -242,7 +242,7 @@ class CompressObjectTestCase(unittest.TestCase):
else:
while chunk:
chunk = dco.decompress('', max_length)
- self.failIf(len(chunk) > max_length,
+ self.assertFalse(len(chunk) > max_length,
'chunk too big (%d>%d)' % (len(chunk),max_length))
bufs.append(chunk)
self.assertEqual(data, b''.join(bufs), 'Wrong data retrieved')
@@ -316,7 +316,7 @@ class CompressObjectTestCase(unittest.TestCase):
# caused a core dump.)
co = zlib.compressobj(zlib.Z_BEST_COMPRESSION)
- self.failUnless(co.flush()) # Returns a zlib header
+ self.assertTrue(co.flush()) # Returns a zlib header
dco = zlib.decompressobj()
self.assertEqual(dco.flush(), b"") # Returns nothing
@@ -356,7 +356,7 @@ class CompressObjectTestCase(unittest.TestCase):
data = HAMLET_SCENE
comp = zlib.compress(data)
# Test type of return value
- self.assert_(isinstance(comp, bytes))
+ self.assertTrue(isinstance(comp, bytes))
d0 = zlib.decompressobj()
bufs0 = []