use assert[Not]In where appropriate

This commit is contained in:
Ezio Melotti 2010-01-23 15:40:09 +00:00
parent 0f77f465ff
commit b58e0bd8bb
39 changed files with 176 additions and 173 deletions

View File

@ -56,9 +56,9 @@ class BasicTestMappingProtocol(unittest.TestCase):
self.assertEqual(len(d), len(self.reference)) self.assertEqual(len(d), len(self.reference))
#__contains__ #__contains__
for k in self.reference: for k in self.reference:
self.assertTrue(k in d) self.assertIn(k, d)
for k in self.other: for k in self.other:
self.assertFalse(k in d) self.assertNotIn(k, d)
#cmp #cmp
self.assertEqual(p, p) self.assertEqual(p, p)
self.assertEqual(d, d) self.assertEqual(d, d)
@ -85,7 +85,7 @@ class BasicTestMappingProtocol(unittest.TestCase):
knownkey, knownvalue = next(iter(self.other.items())) knownkey, knownvalue = next(iter(self.other.items()))
self.assertEqual(d.get(key, knownvalue), value) self.assertEqual(d.get(key, knownvalue), value)
self.assertEqual(d.get(knownkey, knownvalue), knownvalue) self.assertEqual(d.get(knownkey, knownvalue), knownvalue)
self.assertFalse(knownkey in d) self.assertNotIn(knownkey, d)
def test_write(self): def test_write(self):
# Test for write operations on mapping # Test for write operations on mapping
@ -115,16 +115,16 @@ class BasicTestMappingProtocol(unittest.TestCase):
self.assertEqual(d[knownkey], knownvalue) self.assertEqual(d[knownkey], knownvalue)
#pop #pop
self.assertEqual(d.pop(knownkey), knownvalue) self.assertEqual(d.pop(knownkey), knownvalue)
self.assertFalse(knownkey in d) self.assertNotIn(knownkey, d)
self.assertRaises(KeyError, d.pop, knownkey) self.assertRaises(KeyError, d.pop, knownkey)
default = 909 default = 909
d[knownkey] = knownvalue d[knownkey] = knownvalue
self.assertEqual(d.pop(knownkey, default), knownvalue) self.assertEqual(d.pop(knownkey, default), knownvalue)
self.assertFalse(knownkey in d) self.assertNotIn(knownkey, d)
self.assertEqual(d.pop(knownkey, default), default) self.assertEqual(d.pop(knownkey, default), default)
#popitem #popitem
key, value = d.popitem() key, value = d.popitem()
self.assertFalse(key in d) self.assertNotIn(key, d)
self.assertEqual(value, self.reference[key]) self.assertEqual(value, self.reference[key])
p=self._empty_mapping() p=self._empty_mapping()
self.assertRaises(KeyError, p.popitem) self.assertRaises(KeyError, p.popitem)
@ -142,8 +142,8 @@ class BasicTestMappingProtocol(unittest.TestCase):
d = self._empty_mapping() d = self._empty_mapping()
self.assertEqual(list(d.keys()), []) self.assertEqual(list(d.keys()), [])
d = self.reference d = self.reference
self.assertTrue(list(self.inmapping.keys())[0] in d.keys()) self.assertIn(list(self.inmapping.keys())[0], d.keys())
self.assertTrue(list(self.other.keys())[0] not in d.keys()) self.assertNotIn(list(self.other.keys())[0], d.keys())
self.assertRaises(TypeError, d.keys, None) self.assertRaises(TypeError, d.keys, None)
def test_values(self): def test_values(self):
@ -320,9 +320,9 @@ class TestMappingProtocol(BasicTestMappingProtocol):
self.assertEqual(list(d.keys()), []) self.assertEqual(list(d.keys()), [])
d = self._full_mapping({'a': 1, 'b': 2}) d = self._full_mapping({'a': 1, 'b': 2})
k = d.keys() k = d.keys()
self.assertTrue('a' in k) self.assertIn('a', k)
self.assertTrue('b' in k) self.assertIn('b', k)
self.assertTrue('c' not in k) self.assertNotIn('c', k)
def test_values(self): def test_values(self):
BasicTestMappingProtocol.test_values(self) BasicTestMappingProtocol.test_values(self)
@ -337,12 +337,13 @@ class TestMappingProtocol(BasicTestMappingProtocol):
def test_contains(self): def test_contains(self):
d = self._empty_mapping() d = self._empty_mapping()
self.assertNotIn('a', d)
self.assertTrue(not ('a' in d)) self.assertTrue(not ('a' in d))
self.assertTrue('a' not in d) self.assertTrue('a' not in d)
d = self._full_mapping({'a': 1, 'b': 2}) d = self._full_mapping({'a': 1, 'b': 2})
self.assertTrue('a' in d) self.assertIn('a', d)
self.assertTrue('b' in d) self.assertIn('b', d)
self.assertTrue('c' not in d) self.assertNotIn('c', d)
self.assertRaises(TypeError, d.__contains__) self.assertRaises(TypeError, d.__contains__)

View File

@ -770,8 +770,8 @@ class AbstractPickleTests(unittest.TestCase):
# Dump using protocol 1 for comparison. # Dump using protocol 1 for comparison.
s1 = self.dumps(x, 1) s1 = self.dumps(x, 1)
self.assertTrue(__name__.encode("utf-8") in s1) self.assertIn(__name__.encode("utf-8"), s1)
self.assertTrue(b"MyList" in s1) self.assertIn(b"MyList", s1)
self.assertEqual(opcode_in_pickle(opcode, s1), False) self.assertEqual(opcode_in_pickle(opcode, s1), False)
y = self.loads(s1) y = self.loads(s1)
@ -780,8 +780,8 @@ class AbstractPickleTests(unittest.TestCase):
# Dump using protocol 2 for test. # Dump using protocol 2 for test.
s2 = self.dumps(x, 2) s2 = self.dumps(x, 2)
self.assertTrue(__name__.encode("utf-8") not in s2) self.assertNotIn(__name__.encode("utf-8"), s2)
self.assertTrue(b"MyList" not in s2) self.assertNotIn(b"MyList", s2)
self.assertEqual(opcode_in_pickle(opcode, s2), True, repr(s2)) self.assertEqual(opcode_in_pickle(opcode, s2), True, repr(s2))
y = self.loads(s2) y = self.loads(s2)

View File

@ -199,9 +199,9 @@ class CommonTest(unittest.TestCase):
def test_contains(self): def test_contains(self):
u = self.type2test([0, 1, 2]) u = self.type2test([0, 1, 2])
for i in u: for i in u:
self.assert_(i in u) self.assertIn(i, u)
for i in min(u)-1, max(u)+1: for i in min(u)-1, max(u)+1:
self.assert_(i not in u) self.assertNotIn(i, u)
self.assertRaises(TypeError, u.__contains__) self.assertRaises(TypeError, u.__contains__)
@ -213,8 +213,8 @@ class CommonTest(unittest.TestCase):
def __eq__(self, other): def __eq__(self, other):
return True return True
__hash__ = None # Can't meet hash invariant requirements __hash__ = None # Can't meet hash invariant requirements
self.assert_(AllEq() not in self.type2test([])) self.assertNotIn(AllEq(), self.type2test([]))
self.assert_(AllEq() in self.type2test([1])) self.assertIn(AllEq(), self.type2test([1]))
def test_contains_order(self): def test_contains_order(self):
# Sequences must test in-order. If a rich comparison has side # Sequences must test in-order. If a rich comparison has side
@ -227,7 +227,7 @@ class CommonTest(unittest.TestCase):
raise DoNotTestEq raise DoNotTestEq
checkfirst = self.type2test([1, StopCompares()]) checkfirst = self.type2test([1, StopCompares()])
self.assert_(1 in checkfirst) self.assertIn(1, checkfirst)
checklast = self.type2test([StopCompares(), 1]) checklast = self.type2test([StopCompares(), 1])
self.assertRaises(DoNotTestEq, checklast.__contains__, 1) self.assertRaises(DoNotTestEq, checklast.__contains__, 1)

View File

@ -520,9 +520,9 @@ class BaseStrTest:
s = _('').join([edge, SUBSTR, edge]) s = _('').join([edge, SUBSTR, edge])
del edge del edge
self.assertIn(SUBSTR, s) self.assertIn(SUBSTR, s)
self.assertFalse(SUBSTR * 2 in s) self.assertNotIn(SUBSTR * 2, s)
self.assertIn(_('-'), s) self.assertIn(_('-'), s)
self.assertFalse(_('a') in s) self.assertNotIn(_('a'), s)
s += _('a') s += _('a')
self.assertIn(_('a'), s) self.assertIn(_('a'), s)
@ -769,8 +769,8 @@ class TupleTest(unittest.TestCase):
t = (1, 2, 3, 4, 5) * size t = (1, 2, 3, 4, 5) * size
self.assertEquals(len(t), size * 5) self.assertEquals(len(t), size * 5)
self.assertIn(5, t) self.assertIn(5, t)
self.assertFalse((1, 2, 3, 4, 5) in t) self.assertNotIn((1, 2, 3, 4, 5), t)
self.assertFalse(0 in t) self.assertNotIn(0, t)
@bigmemtest(minsize=_2G + 10, memuse=8) @bigmemtest(minsize=_2G + 10, memuse=8)
def test_hash(self, size): def test_hash(self, size):
@ -918,8 +918,8 @@ class ListTest(unittest.TestCase):
l = [1, 2, 3, 4, 5] * size l = [1, 2, 3, 4, 5] * size
self.assertEquals(len(l), size * 5) self.assertEquals(len(l), size * 5)
self.assertIn(5, l) self.assertIn(5, l)
self.assertFalse([1, 2, 3, 4, 5] in l) self.assertNotIn([1, 2, 3, 4, 5], l)
self.assertFalse(0 in l) self.assertNotIn(0, l)
@bigmemtest(minsize=_2G + 10, memuse=8) @bigmemtest(minsize=_2G + 10, memuse=8)
def test_hash(self, size): def test_hash(self, size):

View File

@ -231,8 +231,7 @@ class BaseBytesTest(unittest.TestCase):
b = self.type2test(b"abc") b = self.type2test(b"abc")
self.assertIn(ord('a'), b) self.assertIn(ord('a'), b)
self.assertIn(int(ord('a')), b) self.assertIn(int(ord('a')), b)
self.assertFalse(200 in b) self.assertNotIn(200, b)
self.assertFalse(200 in b)
self.assertRaises(ValueError, lambda: 300 in b) self.assertRaises(ValueError, lambda: 300 in b)
self.assertRaises(ValueError, lambda: -1 in b) self.assertRaises(ValueError, lambda: -1 in b)
self.assertRaises(TypeError, lambda: None in b) self.assertRaises(TypeError, lambda: None in b)
@ -246,10 +245,10 @@ class BaseBytesTest(unittest.TestCase):
self.assertIn(f(b"ab"), b) self.assertIn(f(b"ab"), b)
self.assertIn(f(b"bc"), b) self.assertIn(f(b"bc"), b)
self.assertIn(f(b"abc"), b) self.assertIn(f(b"abc"), b)
self.assertFalse(f(b"ac") in b) self.assertNotIn(f(b"ac"), b)
self.assertFalse(f(b"d") in b) self.assertNotIn(f(b"d"), b)
self.assertFalse(f(b"dab") in b) self.assertNotIn(f(b"dab"), b)
self.assertFalse(f(b"abd") in b) self.assertNotIn(f(b"abd"), b)
def test_fromhex(self): def test_fromhex(self):
self.assertRaises(TypeError, self.type2test.fromhex) self.assertRaises(TypeError, self.type2test.fromhex)

View File

@ -76,7 +76,7 @@ class TestCaseBase(unittest.TestCase):
eq(cf.get('Spaces', 'key with spaces'), 'value') eq(cf.get('Spaces', 'key with spaces'), 'value')
eq(cf.get('Spaces', 'another with spaces'), 'splat!') eq(cf.get('Spaces', 'another with spaces'), 'splat!')
self.assertFalse('__name__' in cf.options("Foo Bar"), self.assertNotIn('__name__', cf.options("Foo Bar"),
'__name__ "option" should not be exposed by the API!') '__name__ "option" should not be exposed by the API!')
# Make sure the right things happen for remove_option(); # Make sure the right things happen for remove_option();

View File

@ -540,10 +540,10 @@ class TestCounter(unittest.TestCase):
self.assertEqual(c, dict(a=4, b=0, d=-2, e=-5, f=4)) self.assertEqual(c, dict(a=4, b=0, d=-2, e=-5, f=4))
self.assertEqual(''.join(sorted(c.elements())), 'aaaaffff') self.assertEqual(''.join(sorted(c.elements())), 'aaaaffff')
self.assertEqual(c.pop('f'), 4) self.assertEqual(c.pop('f'), 4)
self.assertEqual('f' in c, False) self.assertNotIn('f', c)
for i in range(3): for i in range(3):
elem, cnt = c.popitem() elem, cnt = c.popitem()
self.assertEqual(elem in c, False) self.assertNotIn(elem, c)
c.clear() c.clear()
self.assertEqual(c, {}) self.assertEqual(c, {})
self.assertEqual(repr(c), 'Counter()') self.assertEqual(repr(c), 'Counter()')

View File

@ -317,56 +317,56 @@ if 1:
d[1] += 1 d[1] += 1
self.assertEqual(d[1], 2) self.assertEqual(d[1], 2)
del d[1] del d[1]
self.assertEqual(1 in d, False) self.assertNotIn(1, d)
# Tuple of indices # Tuple of indices
d[1, 1] = 1 d[1, 1] = 1
self.assertEqual(d[1, 1], 1) self.assertEqual(d[1, 1], 1)
d[1, 1] += 1 d[1, 1] += 1
self.assertEqual(d[1, 1], 2) self.assertEqual(d[1, 1], 2)
del d[1, 1] del d[1, 1]
self.assertEqual((1, 1) in d, False) self.assertNotIn((1, 1), d)
# Simple slice # Simple slice
d[1:2] = 1 d[1:2] = 1
self.assertEqual(d[1:2], 1) self.assertEqual(d[1:2], 1)
d[1:2] += 1 d[1:2] += 1
self.assertEqual(d[1:2], 2) self.assertEqual(d[1:2], 2)
del d[1:2] del d[1:2]
self.assertEqual(slice(1, 2) in d, False) self.assertNotIn(slice(1, 2), d)
# Tuple of simple slices # Tuple of simple slices
d[1:2, 1:2] = 1 d[1:2, 1:2] = 1
self.assertEqual(d[1:2, 1:2], 1) self.assertEqual(d[1:2, 1:2], 1)
d[1:2, 1:2] += 1 d[1:2, 1:2] += 1
self.assertEqual(d[1:2, 1:2], 2) self.assertEqual(d[1:2, 1:2], 2)
del d[1:2, 1:2] del d[1:2, 1:2]
self.assertEqual((slice(1, 2), slice(1, 2)) in d, False) self.assertNotIn((slice(1, 2), slice(1, 2)), d)
# Extended slice # Extended slice
d[1:2:3] = 1 d[1:2:3] = 1
self.assertEqual(d[1:2:3], 1) self.assertEqual(d[1:2:3], 1)
d[1:2:3] += 1 d[1:2:3] += 1
self.assertEqual(d[1:2:3], 2) self.assertEqual(d[1:2:3], 2)
del d[1:2:3] del d[1:2:3]
self.assertEqual(slice(1, 2, 3) in d, False) self.assertNotIn(slice(1, 2, 3), d)
# Tuple of extended slices # Tuple of extended slices
d[1:2:3, 1:2:3] = 1 d[1:2:3, 1:2:3] = 1
self.assertEqual(d[1:2:3, 1:2:3], 1) self.assertEqual(d[1:2:3, 1:2:3], 1)
d[1:2:3, 1:2:3] += 1 d[1:2:3, 1:2:3] += 1
self.assertEqual(d[1:2:3, 1:2:3], 2) self.assertEqual(d[1:2:3, 1:2:3], 2)
del d[1:2:3, 1:2:3] del d[1:2:3, 1:2:3]
self.assertEqual((slice(1, 2, 3), slice(1, 2, 3)) in d, False) self.assertNotIn((slice(1, 2, 3), slice(1, 2, 3)), d)
# Ellipsis # Ellipsis
d[...] = 1 d[...] = 1
self.assertEqual(d[...], 1) self.assertEqual(d[...], 1)
d[...] += 1 d[...] += 1
self.assertEqual(d[...], 2) self.assertEqual(d[...], 2)
del d[...] del d[...]
self.assertEqual(Ellipsis in d, False) self.assertNotIn(Ellipsis, d)
# Tuple of Ellipses # Tuple of Ellipses
d[..., ...] = 1 d[..., ...] = 1
self.assertEqual(d[..., ...], 1) self.assertEqual(d[..., ...], 1)
d[..., ...] += 1 d[..., ...] += 1
self.assertEqual(d[..., ...], 2) self.assertEqual(d[..., ...], 2)
del d[..., ...] del d[..., ...]
self.assertEqual((Ellipsis, Ellipsis) in d, False) self.assertNotIn((Ellipsis, Ellipsis), d)
def test_annotation_limit(self): def test_annotation_limit(self):
# 16 bits are available for # of annotations, but only 8 bits are # 16 bits are available for # of annotations, but only 8 bits are

View File

@ -627,7 +627,7 @@ class TestCopy(unittest.TestCase):
x, y = C(), C() x, y = C(), C()
# The underlying containers are decoupled # The underlying containers are decoupled
v[x] = y v[x] = y
self.assertFalse(x in u) self.assertNotIn(x, u)
def test_copy_weakkeydict(self): def test_copy_weakkeydict(self):
self._check_copy_weakdict(weakref.WeakKeyDictionary) self._check_copy_weakdict(weakref.WeakKeyDictionary)

View File

@ -140,10 +140,7 @@ class HarmlessMixedComparison:
self.assertTrue(() != me) self.assertTrue(() != me)
self.assertIn(me, [1, 20, [], me]) self.assertIn(me, [1, 20, [], me])
self.assertFalse(me not in [1, 20, [], me])
self.assertIn([], [me, 1, 20, []]) self.assertIn([], [me, 1, 20, []])
self.assertFalse([] not in [me, 1, 20, []])
def test_harmful_mixed_comparison(self): def test_harmful_mixed_comparison(self):
me = self.theclass(1, 1, 1) me = self.theclass(1, 1, 1)

View File

@ -93,7 +93,7 @@ class AnyDBMTestCase(unittest.TestCase):
self.init_db() self.init_db()
f = dbm.open(_fname, 'r') f = dbm.open(_fname, 'r')
key = "a".encode("ascii") key = "a".encode("ascii")
assert(key in f) self.assertIn(key, f)
assert(f[key] == b"Python:") assert(f[key] == b"Python:")
f.close() f.close()

View File

@ -1654,7 +1654,7 @@ order (MRO) for bases """
self.assertNotIn(-1, c1) self.assertNotIn(-1, c1)
for i in range(10): for i in range(10):
self.assertIn(i, c1) self.assertIn(i, c1)
self.assertFalse(10 in c1) self.assertNotIn(10, c1)
# Test the default behavior for dynamic classes # Test the default behavior for dynamic classes
class D(object): class D(object):
def __getitem__(self, i): def __getitem__(self, i):
@ -1677,7 +1677,7 @@ order (MRO) for bases """
self.assertNotIn(-1, d1) self.assertNotIn(-1, d1)
for i in range(10): for i in range(10):
self.assertIn(i, d1) self.assertIn(i, d1)
self.assertFalse(10 in d1) self.assertNotIn(10, d1)
# Test overridden behavior # Test overridden behavior
class Proxy(object): class Proxy(object):
def __init__(self, x): def __init__(self, x):
@ -1721,10 +1721,10 @@ order (MRO) for bases """
self.assertEqual(str(p0), "Proxy:0") self.assertEqual(str(p0), "Proxy:0")
self.assertEqual(repr(p0), "Proxy(0)") self.assertEqual(repr(p0), "Proxy(0)")
p10 = Proxy(range(10)) p10 = Proxy(range(10))
self.assertFalse(-1 in p10) self.assertNotIn(-1, p10)
for i in range(10): for i in range(10):
self.assertIn(i, p10) self.assertIn(i, p10)
self.assertFalse(10 in p10) self.assertNotIn(10, p10)
def test_weakrefs(self): def test_weakrefs(self):
# Testing weak references... # Testing weak references...

View File

@ -34,9 +34,7 @@ class DictTest(unittest.TestCase):
self.assertEqual(set(d.keys()), set()) self.assertEqual(set(d.keys()), set())
d = {'a': 1, 'b': 2} d = {'a': 1, 'b': 2}
k = d.keys() k = d.keys()
self.assertTrue('a' in d)
self.assertIn('a', d) self.assertIn('a', d)
self.assertTrue('b' in d)
self.assertIn('b', d) self.assertIn('b', d)
self.assertRaises(TypeError, d.keys, None) self.assertRaises(TypeError, d.keys, None)
self.assertEqual(repr(dict(a=1).keys()), "dict_keys(['a'])") self.assertEqual(repr(dict(a=1).keys()), "dict_keys(['a'])")
@ -60,15 +58,12 @@ class DictTest(unittest.TestCase):
def test_contains(self): def test_contains(self):
d = {} d = {}
self.assertNotIn('a', d)
self.assertTrue(not ('a' in d)) self.assertTrue(not ('a' in d))
self.assertTrue('a' not in d) self.assertTrue('a' not in d)
self.assertNotIn('a', d)
d = {'a': 1, 'b': 2} d = {'a': 1, 'b': 2}
self.assertTrue('a' in d)
self.assertIn('a', d) self.assertIn('a', d)
self.assertTrue('b' in d)
self.assertIn('b', d) self.assertIn('b', d)
self.assertTrue('c' not in d)
self.assertNotIn('c', d) self.assertNotIn('c', d)
self.assertRaises(TypeError, d.__contains__) self.assertRaises(TypeError, d.__contains__)
@ -524,9 +519,7 @@ class DictTest(unittest.TestCase):
d = D({1: 2, 3: 4}) d = D({1: 2, 3: 4})
self.assertEqual(d[1], 2) self.assertEqual(d[1], 2)
self.assertEqual(d[3], 4) self.assertEqual(d[3], 4)
self.assertTrue(2 not in d)
self.assertNotIn(2, d) self.assertNotIn(2, d)
self.assertTrue(2 not in d.keys())
self.assertNotIn(2, d.keys()) self.assertNotIn(2, d.keys())
self.assertEqual(d[2], 42) self.assertEqual(d[2], 42)
class E(dict): class E(dict):

View File

@ -118,8 +118,8 @@ class DisTests(unittest.TestCase):
def test_opmap(self): def test_opmap(self):
self.assertEqual(dis.opmap["STOP_CODE"], 0) self.assertEqual(dis.opmap["STOP_CODE"], 0)
self.assertEqual(dis.opmap["LOAD_CONST"] in dis.hasconst, True) self.assertIn(dis.opmap["LOAD_CONST"], dis.hasconst)
self.assertEqual(dis.opmap["STORE_NAME"] in dis.hasname, True) self.assertIn(dis.opmap["STORE_NAME"], dis.hasname)
def test_opname(self): def test_opname(self):
self.assertEqual(dis.opname[dis.opmap["LOAD_FAST"]], "LOAD_FAST") self.assertEqual(dis.opname[dis.opmap["LOAD_FAST"]], "LOAD_FAST")

View File

@ -18,8 +18,8 @@ def server(evt, numrequests):
serv.set_server_title("DocXMLRPCServer Test Documentation") serv.set_server_title("DocXMLRPCServer Test Documentation")
serv.set_server_name("DocXMLRPCServer Test Docs") serv.set_server_name("DocXMLRPCServer Test Docs")
serv.set_server_documentation( serv.set_server_documentation(
"""This is an XML-RPC server's documentation, but the server can be used by "This is an XML-RPC server's documentation, but the server "
POSTing to /RPC2. Try self.add, too.""") "can be used by POSTing to /RPC2. Try self.add, too.")
# Create and register classes and functions # Create and register classes and functions
class TestClass(object): class TestClass(object):
@ -106,9 +106,9 @@ class DocXMLRPCHTTPGETServer(unittest.TestCase):
self.client.request("GET", "/") self.client.request("GET", "/")
response = self.client.getresponse() response = self.client.getresponse()
self.assertTrue( self.assertIn((b'<dl><dt><a name="-&lt;lambda&gt;"><strong>'
b"""<dl><dt><a name="-&lt;lambda&gt;"><strong>&lt;lambda&gt;</strong></a>(x, y)</dt></dl>""" b'&lt;lambda&gt;</strong></a>(x, y)</dt></dl>'),
in response.read()) response.read())
def test_autolinking(self): def test_autolinking(self):
"""Test that the server correctly automatically wraps references to PEPS """Test that the server correctly automatically wraps references to PEPS
@ -120,9 +120,17 @@ b"""<dl><dt><a name="-&lt;lambda&gt;"><strong>&lt;lambda&gt;</strong></a>(x, y)<
self.client.request("GET", "/") self.client.request("GET", "/")
response = self.client.getresponse().read() response = self.client.getresponse().read()
self.assertTrue( # This is ugly ... how can it be made better? self.assertIn(
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>""" (b'<dl><dt><a name="-add"><strong>add</strong></a>(x, y)</dt><dd>'
in response, response) b'<tt>Add&nbsp;two&nbsp;instances&nbsp;together.&nbsp;This&nbsp;'
b'follows&nbsp;<a href="http://www.python.org/dev/peps/pep-0008/">'
b'PEP008</a>,&nbsp;but&nbsp;has&nbsp;nothing<br>\nto&nbsp;do&nbsp;'
b'with&nbsp;<a href="http://www.rfc-editor.org/rfc/rfc1952.txt">'
b'RFC1952</a>.&nbsp;Case&nbsp;should&nbsp;matter:&nbsp;pEp008&nbsp;'
b'and&nbsp;rFC1952.&nbsp;&nbsp;Things<br>\nthat&nbsp;start&nbsp;'
b'with&nbsp;http&nbsp;and&nbsp;ftp&nbsp;should&nbsp;be&nbsp;'
b'auto-linked,&nbsp;too:<br>\n<a href="http://google.com">'
b'http://google.com</a>.</tt></dd></dl>'), response)
def test_system_methods(self): def test_system_methods(self):
"""Test the precense of three consecutive system.* methods. """Test the precense of three consecutive system.* methods.
@ -133,8 +141,26 @@ b"""<dl><dt><a name="-add"><strong>add</strong></a>(x, y)</dt><dd><tt>Add&nbsp;t
self.client.request("GET", "/") self.client.request("GET", "/")
response = self.client.getresponse().read() response = self.client.getresponse().read()
self.assertTrue( self.assertIn(
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) (b'<dl><dt><a name="-system.methodHelp"><strong>system.methodHelp'
b'</strong></a>(method_name)</dt><dd><tt><a href="#-system.method'
b'Help">system.methodHelp</a>(\'add\')&nbsp;=&gt;&nbsp;"Adds&nbsp;'
b'two&nbsp;integers&nbsp;together"<br>\n&nbsp;<br>\nReturns&nbsp;a'
b'&nbsp;string&nbsp;containing&nbsp;documentation&nbsp;for&nbsp;'
b'the&nbsp;specified&nbsp;method.</tt></dd></dl>\n<dl><dt><a name'
b'="-system.methodSignature"><strong>system.methodSignature</strong>'
b'</a>(method_name)</dt><dd><tt><a href="#-system.methodSignature">'
b'system.methodSignature</a>(\'add\')&nbsp;=&gt;&nbsp;[double,&nbsp;'
b'int,&nbsp;int]<br>\n&nbsp;<br>\nReturns&nbsp;a&nbsp;list&nbsp;'
b'describing&nbsp;the&nbsp;signature&nbsp;of&nbsp;the&nbsp;method.'
b'&nbsp;In&nbsp;the<br>\nabove&nbsp;example,&nbsp;the&nbsp;add&nbsp;'
b'method&nbsp;takes&nbsp;two&nbsp;integers&nbsp;as&nbsp;arguments'
b'<br>\nand&nbsp;returns&nbsp;a&nbsp;double&nbsp;result.<br>\n&nbsp;'
b'<br>\nThis&nbsp;server&nbsp;does&nbsp;NOT&nbsp;support&nbsp;system'
b'.methodSignature.</tt></dd></dl>\n<dl><dt><a name="-test_method">'
b'<strong>test_method</strong></a>(arg)</dt><dd><tt>Test&nbsp;'
b'method\'s&nbsp;docs.&nbsp;This&nbsp;method&nbsp;truly&nbsp;does'
b'&nbsp;very&nbsp;little.</tt></dd></dl>'), response)
def test_autolink_dotted_methods(self): def test_autolink_dotted_methods(self):
"""Test that selfdot values are made strong automatically in the """Test that selfdot values are made strong automatically in the
@ -142,7 +168,7 @@ b"""<dl><dt><a name="-system.methodHelp"><strong>system.methodHelp</strong></a>(
self.client.request("GET", "/") self.client.request("GET", "/")
response = self.client.getresponse() response = self.client.getresponse()
self.assertTrue(b"""Try&nbsp;self.<strong>add</strong>,&nbsp;too.""" in self.assertIn(b"""Try&nbsp;self.<strong>add</strong>,&nbsp;too.""",
response.read()) response.read())
def test_main(): def test_main():

View File

@ -28,7 +28,7 @@ class ErrorcodeTests(unittest.TestCase):
def test_attributes_in_errorcode(self): def test_attributes_in_errorcode(self):
for attribute in errno.__dict__.keys(): for attribute in errno.__dict__.keys():
if attribute.isupper(): if attribute.isupper():
self.assertTrue(getattr(errno, attribute) in errno.errorcode, self.assertIn(getattr(errno, attribute), errno.errorcode,
'no %s attr in errno.errorcode' % attribute) 'no %s attr in errno.errorcode' % attribute)

View File

@ -413,7 +413,7 @@ class ExceptionTests(unittest.TestCase):
except Exception as e: except Exception as e:
self.assertTrue(e) self.assertTrue(e)
del e del e
self.assertFalse('e' in locals()) self.assertNotIn('e', locals())
def testExceptionCleanupState(self): def testExceptionCleanupState(self):
# Make sure exception state is cleaned up as soon as the except # Make sure exception state is cleaned up as soon as the except

View File

@ -214,16 +214,11 @@ class GeneralFloatCases(unittest.TestCase):
floats = (INF, -INF, 0.0, 1.0, NAN) floats = (INF, -INF, 0.0, 1.0, NAN)
for f in floats: for f in floats:
self.assertIn(f, [f]) self.assertIn(f, [f])
self.assertTrue(f in [f], "'%r' not in []" % f)
self.assertIn(f, (f,)) self.assertIn(f, (f,))
self.assertTrue(f in (f,), "'%r' not in ()" % f)
self.assertIn(f, {f}) self.assertIn(f, {f})
self.assertTrue(f in {f}, "'%r' not in set()" % f)
self.assertIn(f, {f: None}) self.assertIn(f, {f: None})
self.assertTrue(f in {f: None}, "'%r' not in {}" % f)
self.assertEqual([f].count(f), 1, "[].count('%r') != 1" % f) self.assertEqual([f].count(f), 1, "[].count('%r') != 1" % f)
self.assertIn(f, floats) self.assertIn(f, floats)
self.assertTrue(f in floats, "'%r' not in container" % f)
for f in floats: for f in floats:
# nonidentical containers, same type, same contents # nonidentical containers, same type, same contents
@ -459,9 +454,9 @@ class FormatFunctionsTestCase(unittest.TestCase):
float.__setformat__('float', self.save_formats['float']) float.__setformat__('float', self.save_formats['float'])
def test_getformat(self): def test_getformat(self):
self.assertTrue(float.__getformat__('double') in self.assertIn(float.__getformat__('double'),
['unknown', 'IEEE, big-endian', 'IEEE, little-endian']) ['unknown', 'IEEE, big-endian', 'IEEE, little-endian'])
self.assertTrue(float.__getformat__('float') in self.assertIn(float.__getformat__('float'),
['unknown', 'IEEE, big-endian', 'IEEE, little-endian']) ['unknown', 'IEEE, big-endian', 'IEEE, little-endian'])
self.assertRaises(ValueError, float.__getformat__, 'chicken') self.assertRaises(ValueError, float.__getformat__, 'chicken')
self.assertRaises(TypeError, float.__getformat__, 1) self.assertRaises(TypeError, float.__getformat__, 1)

View File

@ -901,8 +901,7 @@ class CookieTests(TestCase):
url = "http://foo.bar.com/" url = "http://foo.bar.com/"
interact_2965(c, url, "spam=eggs; Version=1") interact_2965(c, url, "spam=eggs; Version=1")
h = interact_2965(c, url) h = interact_2965(c, url)
self.assertTrue("Path" not in h, self.assertNotIn("Path", h, "absent path returned with path present")
"absent path returned with path present")
c = CookieJar(pol) c = CookieJar(pol)
url = "http://foo.bar.com/" url = "http://foo.bar.com/"
@ -917,8 +916,7 @@ class CookieTests(TestCase):
url = "http://foo.bar.com/" url = "http://foo.bar.com/"
interact_2965(c, url, "spam=eggs; Version=1") interact_2965(c, url, "spam=eggs; Version=1")
h = interact_2965(c, url) h = interact_2965(c, url)
self.assertTrue("Port" not in h, self.assertNotIn("Port", h, "absent port returned with port present")
"absent port returned with port present")
c = CookieJar(pol) c = CookieJar(pol)
url = "http://foo.bar.com/" url = "http://foo.bar.com/"
@ -931,14 +929,14 @@ class CookieTests(TestCase):
url = "http://foo.bar.com/" url = "http://foo.bar.com/"
interact_2965(c, url, 'spam=eggs; Version=1; Port="80"') interact_2965(c, url, 'spam=eggs; Version=1; Port="80"')
h = interact_2965(c, url) h = interact_2965(c, url)
self.assertTrue('$Port="80"' in h, self.assertIn('$Port="80"', h,
"port with single value not returned with single value") "port with single value not returned with single value")
c = CookieJar(pol) c = CookieJar(pol)
url = "http://foo.bar.com/" url = "http://foo.bar.com/"
interact_2965(c, url, 'spam=eggs; Version=1; Port="80,8080"') interact_2965(c, url, 'spam=eggs; Version=1; Port="80,8080"')
h = interact_2965(c, url) h = interact_2965(c, url)
self.assertTrue('$Port="80,8080"' in h, self.assertIn('$Port="80,8080"', h,
"port with multiple values not returned with multiple " "port with multiple values not returned with multiple "
"values") "values")
@ -1105,8 +1103,8 @@ class LWPCookieTests(TestCase):
c.add_cookie_header(req) c.add_cookie_header(req)
h = req.get_header("Cookie") h = req.get_header("Cookie")
self.assertTrue("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h)
"CUSTOMER=WILE_E_COYOTE" in h) self.assertIn("CUSTOMER=WILE_E_COYOTE", h)
headers.append('Set-Cookie: SHIPPING=FEDEX; path=/foo') headers.append('Set-Cookie: SHIPPING=FEDEX; path=/foo')
res = FakeResponse(headers, "http://www.acme.com") res = FakeResponse(headers, "http://www.acme.com")
@ -1116,17 +1114,17 @@ class LWPCookieTests(TestCase):
c.add_cookie_header(req) c.add_cookie_header(req)
h = req.get_header("Cookie") h = req.get_header("Cookie")
self.assertTrue("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h)
"CUSTOMER=WILE_E_COYOTE" in h and self.assertIn("CUSTOMER=WILE_E_COYOTE", h)
"SHIPPING=FEDEX" not in h) self.assertNotIn("SHIPPING=FEDEX", h)
req = urllib.request.Request("http://www.acme.com/foo/") req = urllib.request.Request("http://www.acme.com/foo/")
c.add_cookie_header(req) c.add_cookie_header(req)
h = req.get_header("Cookie") h = req.get_header("Cookie")
self.assertTrue(("PART_NUMBER=ROCKET_LAUNCHER_0001" in h and self.assertIn("PART_NUMBER=ROCKET_LAUNCHER_0001", h)
"CUSTOMER=WILE_E_COYOTE" in h and self.assertIn("CUSTOMER=WILE_E_COYOTE", h)
h.startswith("SHIPPING=FEDEX;"))) self.assertTrue(h.startswith("SHIPPING=FEDEX;"))
def test_netscape_example_2(self): def test_netscape_example_2(self):
# Second Example transaction sequence: # Second Example transaction sequence:
@ -1344,8 +1342,8 @@ class LWPCookieTests(TestCase):
# the server. # the server.
cookie = interact_2965(c, "http://www.acme.com/acme/parts/") cookie = interact_2965(c, "http://www.acme.com/acme/parts/")
self.assertTrue("Rocket_Launcher_0001" in cookie and self.assertIn("Rocket_Launcher_0001", cookie)
"Riding_Rocket_0023" not in cookie) self.assertNotIn("Riding_Rocket_0023", cookie)
def test_rejection(self): def test_rejection(self):
# Test rejection of Set-Cookie2 responses based on domain, path, port. # Test rejection of Set-Cookie2 responses based on domain, path, port.

View File

@ -474,7 +474,7 @@ class TestClassesAndFunctions(unittest.TestCase):
self.assertIn(('s', 'static method', A), attrs, 'missing static method') self.assertIn(('s', 'static method', A), attrs, 'missing static method')
self.assertIn(('c', 'class method', A), attrs, 'missing class method') self.assertIn(('c', 'class method', A), attrs, 'missing class method')
self.assertIn(('p', 'property', A), attrs, 'missing property') self.assertIn(('p', 'property', A), attrs, 'missing property')
self.assertTrue(('m', 'method', A) in attrs, self.assertIn(('m', 'method', A), attrs,
'missing plain method: %r' % attrs) 'missing plain method: %r' % attrs)
self.assertIn(('m1', 'method', A), attrs, 'missing plain method') self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
self.assertIn(('datablob', 'data', A), attrs, 'missing data') self.assertIn(('datablob', 'data', A), attrs, 'missing data')

View File

@ -1405,7 +1405,7 @@ class SubclassWithKwargsTest(unittest.TestCase):
Subclass(newarg=1) Subclass(newarg=1)
except TypeError as err: except TypeError as err:
# we expect type errors because of wrong argument count # we expect type errors because of wrong argument count
self.assertFalse("does not take keyword arguments" in err.args[0]) self.assertNotIn("does not take keyword arguments", err.args[0])
libreftest = """ Doctest for examples in the library reference: libitertools.tex libreftest = """ Doctest for examples in the library reference: libitertools.tex

View File

@ -242,7 +242,7 @@ class Test_ISO2022(unittest.TestCase):
self.assertEqual(iso2022jp2.decode('iso2022-jp-2'), uni) self.assertEqual(iso2022jp2.decode('iso2022-jp-2'), uni)
def test_iso2022_jp_g0(self): def test_iso2022_jp_g0(self):
self.assertFalse(b'\x0e' in '\N{SOFT HYPHEN}'.encode('iso-2022-jp-2')) self.assertNotIn(b'\x0e', '\N{SOFT HYPHEN}'.encode('iso-2022-jp-2'))
for encoding in ('iso-2022-jp-2004', 'iso-2022-jp-3'): for encoding in ('iso-2022-jp-2004', 'iso-2022-jp-3'):
e = '\u3406'.encode(encoding) e = '\u3406'.encode(encoding)
self.assertFalse(any(x > 0x80 for x in e)) self.assertFalse(any(x > 0x80 for x in e))

View File

@ -38,7 +38,7 @@ class ExceptionClassTests(unittest.TestCase):
last_exc = getattr(builtins, superclass_name) last_exc = getattr(builtins, superclass_name)
except AttributeError: except AttributeError:
self.fail("base class %s not a built-in" % superclass_name) self.fail("base class %s not a built-in" % superclass_name)
self.assertTrue(superclass_name in exc_set, self.assertIn(superclass_name, exc_set,
'%s not found' % superclass_name) '%s not found' % superclass_name)
exc_set.discard(superclass_name) exc_set.discard(superclass_name)
superclasses = [] # Loop will insert base exception superclasses = [] # Loop will insert base exception

View File

@ -51,9 +51,9 @@ class TestImport(unittest.TestCase):
self.rewrite_file('for') self.rewrite_file('for')
try: __import__(self.module_name) try: __import__(self.module_name)
except SyntaxError: pass except SyntaxError: pass
else: raise RuntimeError('Failed to induce SyntaxError') else: raise RuntimeError('Failed to induce SyntaxError') # self.fail()?
self.assertTrue(self.module_name not in sys.modules and self.assertNotIn(self.module_name, sys.modules)
not hasattr(sys.modules[self.package_name], 'foo')) self.assertFalse(hasattr(sys.modules[self.package_name], 'foo'))
# ...make up a variable name that isn't bound in __builtins__ # ...make up a variable name that isn't bound in __builtins__
var = 'a' var = 'a'

View File

@ -72,7 +72,7 @@ class ProfileTest(unittest.TestCase):
stats = pstats.Stats(prof, stream=s) stats = pstats.Stats(prof, stream=s)
stats.print_stats() stats.print_stats()
res = s.getvalue() res = s.getvalue()
self.assertTrue(self.expected_max_output in res, self.assertIn(self.expected_max_output, res,
"Profiling {0!r} didn't report max:\n{1}".format(stmt, res)) "Profiling {0!r} didn't report max:\n{1}".format(stmt, res))

View File

@ -41,7 +41,6 @@ class PyclbrTest(TestCase):
if key not in obj: if key not in obj:
print("***",key, file=sys.stderr) print("***",key, file=sys.stderr)
self.assertIn(key, obj) self.assertIn(key, obj)
self.assertTrue(key in obj, "%r in %r" % (key, obj))
def assertEqualsOrIgnored(self, a, b, ignore): def assertEqualsOrIgnored(self, a, b, ignore):
''' succeed iff a == b or a in ignore or b in ignore ''' ''' succeed iff a == b or a in ignore or b in ignore '''

View File

@ -126,7 +126,7 @@ class RangeTest(unittest.TestCase):
class C2: class C2:
def __int__(self): return 1 def __int__(self): return 1
def __index__(self): return 1 def __index__(self): return 1
self.assertFalse(C2() in range(3)) self.assertNotIn(C2(), range(3))
# ..except if explicitly told so. # ..except if explicitly told so.
self.assertIn(int(C2()), range(3)) self.assertIn(int(C2()), range(3))
@ -140,32 +140,32 @@ class RangeTest(unittest.TestCase):
def test_strided_limits(self): def test_strided_limits(self):
r = range(0, 101, 2) r = range(0, 101, 2)
self.assertIn(0, r) self.assertIn(0, r)
self.assertFalse(1 in r) self.assertNotIn(1, r)
self.assertIn(2, r) self.assertIn(2, r)
self.assertFalse(99 in r) self.assertNotIn(99, r)
self.assertIn(100, r) self.assertIn(100, r)
self.assertFalse(101 in r) self.assertNotIn(101, r)
r = range(0, -20, -1) r = range(0, -20, -1)
self.assertIn(0, r) self.assertIn(0, r)
self.assertIn(-1, r) self.assertIn(-1, r)
self.assertIn(-19, r) self.assertIn(-19, r)
self.assertFalse(-20 in r) self.assertNotIn(-20, r)
r = range(0, -20, -2) r = range(0, -20, -2)
self.assertIn(-18, r) self.assertIn(-18, r)
self.assertFalse(-19 in r) self.assertNotIn(-19, r)
self.assertFalse(-20 in r) self.assertNotIn(-20, r)
def test_empty(self): def test_empty(self):
r = range(0) r = range(0)
self.assertFalse(0 in r) self.assertNotIn(0, r)
self.assertFalse(1 in r) self.assertNotIn(1, r)
r = range(0, -10) r = range(0, -10)
self.assertFalse(0 in r) self.assertNotIn(0, r)
self.assertFalse(-1 in r) self.assertNotIn(-1, r)
self.assertFalse(1 in r) self.assertNotIn(1, r)
def test_range_iterators(self): def test_range_iterators(self):
# exercise 'fast' iterators, that use a rangeiterobject internally. # exercise 'fast' iterators, that use a rangeiterobject internally.

View File

@ -30,7 +30,7 @@ class XmlTestBase(unittest.TestCase):
self.assertEquals(attrs.getNames(), []) self.assertEquals(attrs.getNames(), [])
self.assertEquals(attrs.getQNames(), []) self.assertEquals(attrs.getQNames(), [])
self.assertEquals(len(attrs), 0) self.assertEquals(len(attrs), 0)
self.assertFalse("attr" in attrs) self.assertNotIn("attr", attrs)
self.assertEquals(list(attrs.keys()), []) self.assertEquals(list(attrs.keys()), [])
self.assertEquals(attrs.get("attrs"), None) self.assertEquals(attrs.get("attrs"), None)
self.assertEquals(attrs.get("attrs", 25), 25) self.assertEquals(attrs.get("attrs", 25), 25)
@ -47,7 +47,7 @@ class XmlTestBase(unittest.TestCase):
self.assertEquals(attrs.getNames(), []) self.assertEquals(attrs.getNames(), [])
self.assertEquals(attrs.getQNames(), []) self.assertEquals(attrs.getQNames(), [])
self.assertEquals(len(attrs), 0) self.assertEquals(len(attrs), 0)
self.assertFalse((ns_uri, "attr") in attrs) self.assertNotIn((ns_uri, "attr"), attrs)
self.assertEquals(list(attrs.keys()), []) self.assertEquals(list(attrs.keys()), [])
self.assertEquals(attrs.get((ns_uri, "attr")), None) self.assertEquals(attrs.get((ns_uri, "attr")), None)
self.assertEquals(attrs.get((ns_uri, "attr"), 25), 25) self.assertEquals(attrs.get((ns_uri, "attr"), 25), 25)

View File

@ -63,13 +63,13 @@ class HelperFunctionsTests(unittest.TestCase):
dir_set = site._init_pathinfo() dir_set = site._init_pathinfo()
for entry in [site.makepath(path)[1] for path in sys.path for entry in [site.makepath(path)[1] for path in sys.path
if path and os.path.isdir(path)]: if path and os.path.isdir(path)]:
self.assertTrue(entry in dir_set, self.assertIn(entry, dir_set,
"%s from sys.path not found in set returned " "%s from sys.path not found in set returned "
"by _init_pathinfo(): %s" % (entry, dir_set)) "by _init_pathinfo(): %s" % (entry, dir_set))
def pth_file_tests(self, pth_file): def pth_file_tests(self, pth_file):
"""Contain common code for testing results of reading a .pth file""" """Contain common code for testing results of reading a .pth file"""
self.assertTrue(pth_file.imported in sys.modules, self.assertIn(pth_file.imported, sys.modules,
"%s not in sys.modules" % pth_file.imported) "%s not in sys.modules" % pth_file.imported)
self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path) self.assertIn(site.makepath(pth_file.good_dir_path)[0], sys.path)
self.assertFalse(os.path.exists(pth_file.bad_dir_path)) self.assertFalse(os.path.exists(pth_file.bad_dir_path))

View File

@ -36,8 +36,8 @@ class LocaleTime_Tests(unittest.TestCase):
""" """
strftime_output = time.strftime(directive, self.time_tuple).lower() strftime_output = time.strftime(directive, self.time_tuple).lower()
comparison = testing[self.time_tuple[tuple_position]] comparison = testing[self.time_tuple[tuple_position]]
self.assertTrue(strftime_output in testing, "%s: not found in tuple" % self.assertIn(strftime_output, testing,
error_msg) "%s: not found in tuple" % error_msg)
self.assertTrue(comparison == strftime_output, self.assertTrue(comparison == strftime_output,
"%s: position within tuple incorrect; %s != %s" % "%s: position within tuple incorrect; %s != %s" %
(error_msg, comparison, strftime_output)) (error_msg, comparison, strftime_output))
@ -61,7 +61,7 @@ class LocaleTime_Tests(unittest.TestCase):
def test_am_pm(self): def test_am_pm(self):
# Make sure AM/PM representation done properly # Make sure AM/PM representation done properly
strftime_output = time.strftime("%p", self.time_tuple).lower() strftime_output = time.strftime("%p", self.time_tuple).lower()
self.assertTrue(strftime_output in self.LT_ins.am_pm, self.assertIn(strftime_output, self.LT_ins.am_pm,
"AM/PM representation not in tuple") "AM/PM representation not in tuple")
if self.time_tuple[3] < 12: position = 0 if self.time_tuple[3] < 12: position = 0
else: position = 1 else: position = 1
@ -72,7 +72,7 @@ class LocaleTime_Tests(unittest.TestCase):
# Make sure timezone is correct # Make sure timezone is correct
timezone = time.strftime("%Z", self.time_tuple).lower() timezone = time.strftime("%Z", self.time_tuple).lower()
if timezone: if timezone:
self.assertTrue(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 in self.LT_ins.timezone[1],
"timezone %s not found in %s" % "timezone %s not found in %s" %
(timezone, self.LT_ins.timezone)) (timezone, self.LT_ins.timezone))
@ -133,7 +133,7 @@ class TimeRETests(unittest.TestCase):
# Make sure any characters in the format string that might be taken as # Make sure any characters in the format string that might be taken as
# regex syntax is escaped. # regex syntax is escaped.
pattern_string = self.time_re.pattern("\d+") pattern_string = self.time_re.pattern("\d+")
self.assertTrue(r"\\d\+" in pattern_string, self.assertIn(r"\\d\+", pattern_string,
"%s does not have re characters escaped properly" % "%s does not have re characters escaped properly" %
pattern_string) pattern_string)

View File

@ -388,8 +388,7 @@ class SysModuleTest(unittest.TestCase):
self.assertTrue(isinstance(vi.major, int)) self.assertTrue(isinstance(vi.major, int))
self.assertTrue(isinstance(vi.minor, int)) self.assertTrue(isinstance(vi.minor, int))
self.assertTrue(isinstance(vi.micro, int)) self.assertTrue(isinstance(vi.micro, int))
self.assertTrue(vi.releaselevel in self.assertIn(vi.releaselevel, ("alpha", "beta", "candidate", "final"))
("alpha", "beta", "candidate", "final"))
self.assertTrue(isinstance(vi.serial, int)) self.assertTrue(isinstance(vi.serial, int))
self.assertEqual(vi[0], vi.major) self.assertEqual(vi[0], vi.major)
self.assertEqual(vi[1], vi.minor) self.assertEqual(vi[1], vi.minor)

View File

@ -113,7 +113,7 @@ class test__RandomNameSequence(TC):
for i in range(TEST_FILES): for i in range(TEST_FILES):
s = next(r) s = next(r)
self.nameCheck(s, '', '', '') self.nameCheck(s, '', '', '')
self.assertFalse(s in dict) self.assertNotIn(s, dict)
dict[s] = 1 dict[s] = 1
def supports_iter(self): def supports_iter(self):

View File

@ -350,7 +350,7 @@ class ThreadTests(BaseTestCase):
t.start() t.start()
t.join() t.join()
l = enum() l = enum()
self.assertFalse(t in l, self.assertNotIn(t, l,
"#1703448 triggered after %d trials: %s" % (i, l)) "#1703448 triggered after %d trials: %s" % (i, l))
finally: finally:
sys.setswitchinterval(old_interval) sys.setswitchinterval(old_interval)

View File

@ -131,7 +131,7 @@ class SyntaxTracebackCases(unittest.TestCase):
err_line = "raise RuntimeError('{0}')".format(message_ascii) err_line = "raise RuntimeError('{0}')".format(message_ascii)
err_msg = "RuntimeError: {0}".format(message_ascii) err_msg = "RuntimeError: {0}".format(message_ascii)
self.assertTrue(("line %s" % lineno) in stdout[1], self.assertIn(("line %s" % lineno), stdout[1],
"Invalid line number: {0!r} instead of {1}".format( "Invalid line number: {0!r} instead of {1}".format(
stdout[1], lineno)) stdout[1], lineno))
self.assertTrue(stdout[2].endswith(err_line), self.assertTrue(stdout[2].endswith(err_line),
@ -271,7 +271,7 @@ class BaseExceptionReportingTests:
self.assertEquals(len(blocks), 3) self.assertEquals(len(blocks), 3)
self.assertEquals(blocks[1], cause_message) self.assertEquals(blocks[1], cause_message)
self.check_zero_div(blocks[0]) self.check_zero_div(blocks[0])
self.assert_('inner_raise() # Marker' in blocks[2]) self.assertIn('inner_raise() # Marker', blocks[2])
def test_cause_recursive(self): def test_cause_recursive(self):
def inner_raise(): def inner_raise():

View File

@ -3035,7 +3035,7 @@ class Test_Assertions(TestCase):
try: try:
self.assertRaises(KeyError, lambda: None) self.assertRaises(KeyError, lambda: None)
except self.failureException as e: except self.failureException as e:
self.assert_("KeyError not raised" in str(e), str(e)) self.assertIn("KeyError not raised", str(e))
else: else:
self.fail("assertRaises() didn't fail") self.fail("assertRaises() didn't fail")
try: try:
@ -3052,7 +3052,7 @@ class Test_Assertions(TestCase):
with self.assertRaises(KeyError): with self.assertRaises(KeyError):
pass pass
except self.failureException as e: except self.failureException as e:
self.assert_("KeyError not raised" in str(e), str(e)) self.assertIn("KeyError not raised", str(e))
else: else:
self.fail("assertRaises() didn't fail") self.fail("assertRaises() didn't fail")
try: try:

View File

@ -731,7 +731,7 @@ class urlencode_Tests(unittest.TestCase):
expect_somewhere = ["1st=1", "2nd=2", "3rd=3"] expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
result = urllib.parse.urlencode(given) result = urllib.parse.urlencode(given)
for expected in expect_somewhere: for expected in expect_somewhere:
self.assertTrue(expected in result, self.assertIn(expected, result,
"testing %s: %s not found in %s" % "testing %s: %s not found in %s" %
(test_type, expected, result)) (test_type, expected, result))
self.assertEqual(result.count('&'), 2, self.assertEqual(result.count('&'), 2,
@ -778,8 +778,7 @@ class urlencode_Tests(unittest.TestCase):
result = urllib.parse.urlencode(given, True) result = urllib.parse.urlencode(given, True)
for value in given["sequence"]: for value in given["sequence"]:
expect = "sequence=%s" % value expect = "sequence=%s" % value
self.assertTrue(expect in result, self.assertIn(expect, result)
"%s not found in %s" % (expect, result))
self.assertEqual(result.count('&'), 2, self.assertEqual(result.count('&'), 2,
"Expected 2 '&'s, got %s" % result.count('&')) "Expected 2 '&'s, got %s" % result.count('&'))

View File

@ -1027,9 +1027,9 @@ class HandlerTests(unittest.TestCase):
# Verify Proxy-Authorization gets tunneled to request. # Verify Proxy-Authorization gets tunneled to request.
# httpsconn req_headers do not have the Proxy-Authorization header but # httpsconn req_headers do not have the Proxy-Authorization header but
# the req will have. # the req will have.
self.assertFalse(("Proxy-Authorization","FooBar") in self.assertNotIn(("Proxy-Authorization","FooBar"),
https_handler.httpconn.req_headers) https_handler.httpconn.req_headers)
self.assertTrue(("User-Agent","Grail") in self.assertIn(("User-Agent","Grail"),
https_handler.httpconn.req_headers) https_handler.httpconn.req_headers)
self.assertIsNotNone(req._tunnel_host) self.assertIsNotNone(req._tunnel_host)
self.assertEqual(req.get_host(), "proxy.example.com:3128") self.assertEqual(req.get_host(), "proxy.example.com:3128")

View File

@ -169,8 +169,7 @@ class ReferencesTestCase(TestBase):
p[:] = [2, 3] p[:] = [2, 3]
self.assertEqual(len(L), 2) self.assertEqual(len(L), 2)
self.assertEqual(len(p), 2) self.assertEqual(len(p), 2)
self.assertTrue(3 in p, self.assertIn(3, p, "proxy didn't support __contains__() properly")
"proxy didn't support __contains__() properly")
p[1] = 5 p[1] = 5
self.assertEqual(L[1], 5) self.assertEqual(L[1], 5)
self.assertEqual(p[1], 5) self.assertEqual(p[1], 5)
@ -961,13 +960,13 @@ class MappingTestCase(TestBase):
# weakref'ed objects and then return a new key/value pair corresponding # weakref'ed objects and then return a new key/value pair corresponding
# to the destroyed object. # to the destroyed object.
with testcontext() as (k, v): with testcontext() as (k, v):
self.assertFalse(k in dict) self.assertNotIn(k, dict)
with testcontext() as (k, v): with testcontext() as (k, v):
self.assertRaises(KeyError, dict.__delitem__, k) self.assertRaises(KeyError, dict.__delitem__, k)
self.assertFalse(k in dict) self.assertNotIn(k, dict)
with testcontext() as (k, v): with testcontext() as (k, v):
self.assertRaises(KeyError, dict.pop, k) self.assertRaises(KeyError, dict.pop, k)
self.assertFalse(k in dict) self.assertNotIn(k, dict)
with testcontext() as (k, v): with testcontext() as (k, v):
dict[k] = v dict[k] = v
self.assertEqual(dict[k], v) self.assertEqual(dict[k], v)
@ -1118,14 +1117,12 @@ class MappingTestCase(TestBase):
weakdict.update(dict) weakdict.update(dict)
self.assertEqual(len(weakdict), len(dict)) self.assertEqual(len(weakdict), len(dict))
for k in weakdict.keys(): for k in weakdict.keys():
self.assertTrue(k in dict, self.assertIn(k, dict, "mysterious new key appeared in weak dict")
"mysterious new key appeared in weak dict")
v = dict.get(k) v = dict.get(k)
self.assertTrue(v is weakdict[k]) self.assertTrue(v is weakdict[k])
self.assertTrue(v is weakdict.get(k)) self.assertTrue(v is weakdict.get(k))
for k in dict.keys(): for k in dict.keys():
self.assertTrue(k in weakdict, self.assertIn(k, weakdict, "original key disappeared in weak dict")
"original key disappeared in weak dict")
v = dict[k] v = dict[k]
self.assertTrue(v is weakdict[k]) self.assertTrue(v is weakdict[k])
self.assertTrue(v is weakdict.get(k)) self.assertTrue(v is weakdict.get(k))

View File

@ -35,7 +35,7 @@ class TestWeakSet(unittest.TestCase):
for method in dir(set): for method in dir(set):
if method == 'test_c_api' or method.startswith('_'): if method == 'test_c_api' or method.startswith('_'):
continue continue
self.assertTrue(method in weaksetmethods, self.assertIn(method, weaksetmethods,
"WeakSet missing method " + method) "WeakSet missing method " + method)
def test_new_or_init(self): def test_new_or_init(self):
@ -342,10 +342,10 @@ class TestWeakSet(unittest.TestCase):
it = None # should commit all removals it = None # should commit all removals
with testcontext() as u: with testcontext() as u:
self.assertFalse(u in s) self.assertNotIn(u, s)
with testcontext() as u: with testcontext() as u:
self.assertRaises(KeyError, s.remove, u) self.assertRaises(KeyError, s.remove, u)
self.assertFalse(u in s) self.assertNotIn(u, s)
with testcontext() as u: with testcontext() as u:
s.add(u) s.add(u)
self.assertIn(u, s) self.assertIn(u, s)