use assert[Not]In where appropriate

This commit is contained in:
Ezio Melotti 2010-01-23 23:04:36 +00:00
parent 8cd0a66a0f
commit aa98058cc4
86 changed files with 622 additions and 599 deletions

View file

@ -57,10 +57,10 @@ class BasicTestMappingProtocol(unittest.TestCase):
#has_key #has_key
for k in self.reference: for k in self.reference:
self.assertTrue(d.has_key(k)) self.assertTrue(d.has_key(k))
self.assertTrue(k in d) self.assertIn(k, d)
for k in self.other: for k in self.other:
self.assertFalse(d.has_key(k)) self.assertFalse(d.has_key(k))
self.assertFalse(k in d) self.assertNotIn(k, d)
#cmp #cmp
self.assertEqual(cmp(p,p), 0) self.assertEqual(cmp(p,p), 0)
self.assertEqual(cmp(d,d), 0) self.assertEqual(cmp(d,d), 0)
@ -84,7 +84,7 @@ class BasicTestMappingProtocol(unittest.TestCase):
knownkey, knownvalue = self.other.iteritems().next() knownkey, knownvalue = self.other.iteritems().next()
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
@ -114,16 +114,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)
@ -141,8 +141,8 @@ class BasicTestMappingProtocol(unittest.TestCase):
d = self._empty_mapping() d = self._empty_mapping()
self.assertEqual(d.keys(), []) self.assertEqual(d.keys(), [])
d = self.reference d = self.reference
self.assertTrue(self.inmapping.keys()[0] in d.keys()) self.assertIn(self.inmapping.keys()[0], d.keys())
self.assertTrue(self.other.keys()[0] not in d.keys()) self.assertNotIn(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):
@ -318,9 +318,9 @@ class TestMappingProtocol(BasicTestMappingProtocol):
self.assertEqual(d.keys(), []) self.assertEqual(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)
@ -345,12 +345,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

@ -767,8 +767,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__ in s1) self.assertIn(__name__, s1)
self.assertTrue("MyList" in s1) self.assertIn("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)
@ -777,8 +777,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__ not in s2) self.assertNotIn(__name__, s2)
self.assertTrue("MyList" not in s2) self.assertNotIn("MyList", s2)
self.assertEqual(opcode_in_pickle(opcode, s2), True) self.assertEqual(opcode_in_pickle(opcode, s2), True)
y = self.loads(s2) y = self.loads(s2)

View file

@ -201,9 +201,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__)
@ -215,8 +215,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
@ -229,7 +229,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

@ -580,12 +580,12 @@ class StrTest(unittest.TestCase):
edge = '-' * (size // 2) edge = '-' * (size // 2)
s = ''.join([edge, SUBSTR, edge]) s = ''.join([edge, SUBSTR, edge])
del edge del edge
self.assertTrue(SUBSTR in s) self.assertIn(SUBSTR, s)
self.assertFalse(SUBSTR * 2 in s) self.assertNotIn(SUBSTR * 2, s)
self.assertTrue('-' in s) self.assertIn('-', s)
self.assertFalse('a' in s) self.assertNotIn('a', s)
s += 'a' s += 'a'
self.assertTrue('a' in s) self.assertIn('a', s)
@bigmemtest(minsize=_2G + 10, memuse=2) @bigmemtest(minsize=_2G + 10, memuse=2)
def test_compare(self, size): def test_compare(self, size):
@ -659,9 +659,9 @@ class TupleTest(unittest.TestCase):
def test_contains(self, size): def test_contains(self, size):
t = (1, 2, 3, 4, 5) * size t = (1, 2, 3, 4, 5) * size
self.assertEquals(len(t), size * 5) self.assertEquals(len(t), size * 5)
self.assertTrue(5 in 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):
@ -808,9 +808,9 @@ class ListTest(unittest.TestCase):
def test_contains(self, size): def test_contains(self, size):
l = [1, 2, 3, 4, 5] * size l = [1, 2, 3, 4, 5] * size
self.assertEquals(len(l), size * 5) self.assertEquals(len(l), size * 5)
self.assertTrue(5 in 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

@ -43,8 +43,8 @@ class TestBSDDB(unittest.TestCase):
def test_change(self): def test_change(self):
self.f['r'] = 'discovered' self.f['r'] = 'discovered'
self.assertEqual(self.f['r'], 'discovered') self.assertEqual(self.f['r'], 'discovered')
self.assertTrue('r' in self.f.keys()) self.assertIn('r', self.f.keys())
self.assertTrue('discovered' in self.f.values()) self.assertIn('discovered', self.f.values())
def test_close_and_reopen(self): def test_close_and_reopen(self):
if self.fname is None: if self.fname is None:
@ -195,8 +195,8 @@ class TestBSDDB(unittest.TestCase):
def test_contains(self): def test_contains(self):
for k in self.d: for k in self.d:
self.assertTrue(k in self.f) self.assertIn(k, self.f)
self.assertTrue('not here' not in self.f) self.assertNotIn('not here', self.f)
def test_has_key(self): def test_has_key(self):
for k in self.d: for k in self.d:
@ -253,9 +253,9 @@ class TestBSDDB(unittest.TestCase):
if debug: print "K" if debug: print "K"
# test the legacy cursor interface mixed with writes # test the legacy cursor interface mixed with writes
self.assertTrue(self.f.first()[0] in self.d) self.assertIn(self.f.first()[0], self.d)
k = self.f.next()[0] k = self.f.next()[0]
self.assertTrue(k in self.d) self.assertIn(k, self.d)
self.f[k] = "be gone with ye deadlocks" self.f[k] = "be gone with ye deadlocks"
self.assertTrue(self.f[k], "be gone with ye deadlocks") self.assertTrue(self.f[k], "be gone with ye deadlocks")
@ -279,17 +279,17 @@ class TestBSDDB(unittest.TestCase):
def test_popitem(self): def test_popitem(self):
k, v = self.f.popitem() k, v = self.f.popitem()
self.assertTrue(k in self.d) self.assertIn(k, self.d)
self.assertTrue(v in self.d.values()) self.assertIn(v, self.d.values())
self.assertTrue(k not in self.f) self.assertNotIn(k, self.f)
self.assertEqual(len(self.d)-1, len(self.f)) self.assertEqual(len(self.d)-1, len(self.f))
def test_pop(self): def test_pop(self):
k = 'w' k = 'w'
v = self.f.pop(k) v = self.f.pop(k)
self.assertEqual(v, self.d[k]) self.assertEqual(v, self.d[k])
self.assertTrue(k not in self.f) self.assertNotIn(k, self.f)
self.assertTrue(v not in self.f.values()) self.assertNotIn(v, self.f.values())
self.assertEqual(len(self.d)-1, len(self.f)) self.assertEqual(len(self.d)-1, len(self.f))
def test_get(self): def test_get(self):

View file

@ -236,11 +236,11 @@ class BuiltinTest(unittest.TestCase):
# dir() - local scope # dir() - local scope
local_var = 1 local_var = 1
self.assertTrue('local_var' in dir()) self.assertIn('local_var', dir())
# dir(module) # dir(module)
import sys import sys
self.assertTrue('exit' in dir(sys)) self.assertIn('exit', dir(sys))
# dir(module_with_invalid__dict__) # dir(module_with_invalid__dict__)
import types import types
@ -250,8 +250,8 @@ class BuiltinTest(unittest.TestCase):
self.assertRaises(TypeError, dir, f) self.assertRaises(TypeError, dir, f)
# dir(type) # dir(type)
self.assertTrue("strip" in dir(str)) self.assertIn("strip", dir(str))
self.assertTrue("__mro__" not in dir(str)) self.assertNotIn("__mro__", dir(str))
# dir(obj) # dir(obj)
class Foo(object): class Foo(object):
@ -260,13 +260,13 @@ class BuiltinTest(unittest.TestCase):
self.y = 8 self.y = 8
self.z = 9 self.z = 9
f = Foo() f = Foo()
self.assertTrue("y" in dir(f)) self.assertIn("y", dir(f))
# dir(obj_no__dict__) # dir(obj_no__dict__)
class Foo(object): class Foo(object):
__slots__ = [] __slots__ = []
f = Foo() f = Foo()
self.assertTrue("__repr__" in dir(f)) self.assertIn("__repr__", dir(f))
# dir(obj_no__class__with__dict__) # dir(obj_no__class__with__dict__)
# (an ugly trick to cause getattr(f, "__class__") to fail) # (an ugly trick to cause getattr(f, "__class__") to fail)
@ -275,8 +275,8 @@ class BuiltinTest(unittest.TestCase):
def __init__(self): def __init__(self):
self.bar = "wow" self.bar = "wow"
f = Foo() f = Foo()
self.assertTrue("__repr__" not in dir(f)) self.assertNotIn("__repr__", dir(f))
self.assertTrue("bar" in dir(f)) self.assertIn("bar", dir(f))
# dir(obj_using __dir__) # dir(obj_using __dir__)
class Foo(object): class Foo(object):
@ -1046,18 +1046,18 @@ class BuiltinTest(unittest.TestCase):
self.assertEqual(range(a+4, a, -2), [a+4, a+2]) self.assertEqual(range(a+4, a, -2), [a+4, a+2])
seq = range(a, b, c) seq = range(a, b, c)
self.assertTrue(a in seq) self.assertIn(a, seq)
self.assertTrue(b not in seq) self.assertNotIn(b, seq)
self.assertEqual(len(seq), 2) self.assertEqual(len(seq), 2)
seq = range(b, a, -c) seq = range(b, a, -c)
self.assertTrue(b in seq) self.assertIn(b, seq)
self.assertTrue(a not in seq) self.assertNotIn(a, seq)
self.assertEqual(len(seq), 2) self.assertEqual(len(seq), 2)
seq = range(-a, -b, -c) seq = range(-a, -b, -c)
self.assertTrue(-a in seq) self.assertIn(-a, seq)
self.assertTrue(-b not in seq) self.assertNotIn(-b, seq)
self.assertEqual(len(seq), 2) self.assertEqual(len(seq), 2)
self.assertRaises(TypeError, range) self.assertRaises(TypeError, range)

View file

@ -222,27 +222,26 @@ class BaseBytesTest(unittest.TestCase):
def test_contains(self): def test_contains(self):
b = self.type2test(b"abc") b = self.type2test(b"abc")
self.assertTrue(ord('a') in b) self.assertIn(ord('a'), b)
self.assertTrue(int(ord('a')) in 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)
self.assertRaises(TypeError, lambda: float(ord('a')) in b) self.assertRaises(TypeError, lambda: float(ord('a')) in b)
self.assertRaises(TypeError, lambda: u"a" in b) self.assertRaises(TypeError, lambda: u"a" in b)
for f in bytes, bytearray: for f in bytes, bytearray:
self.assertTrue(f(b"") in b) self.assertIn(f(b""), b)
self.assertTrue(f(b"a") in b) self.assertIn(f(b"a"), b)
self.assertTrue(f(b"b") in b) self.assertIn(f(b"b"), b)
self.assertTrue(f(b"c") in b) self.assertIn(f(b"c"), b)
self.assertTrue(f(b"ab") in b) self.assertIn(f(b"ab"), b)
self.assertTrue(f(b"bc") in b) self.assertIn(f(b"bc"), b)
self.assertTrue(f(b"abc") in 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

@ -81,7 +81,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

@ -23,7 +23,7 @@ class CmdLineTest(unittest.TestCase):
def verify_valid_flag(self, cmd_line): def verify_valid_flag(self, cmd_line):
data = self.start_python(cmd_line) data = self.start_python(cmd_line)
self.assertTrue(data == '' or data.endswith('\n')) self.assertTrue(data == '' or data.endswith('\n'))
self.assertTrue('Traceback' not in data) self.assertNotIn('Traceback', data)
def test_optimize(self): def test_optimize(self):
self.verify_valid_flag('-O') self.verify_valid_flag('-O')
@ -39,7 +39,7 @@ class CmdLineTest(unittest.TestCase):
self.verify_valid_flag('-S') self.verify_valid_flag('-S')
def test_usage(self): def test_usage(self):
self.assertTrue('usage' in self.start_python('-h')) self.assertIn('usage', self.start_python('-h'))
def test_version(self): def test_version(self):
version = 'Python %d.%d' % sys.version_info[:2] version = 'Python %d.%d' % sys.version_info[:2]
@ -72,7 +72,7 @@ class CmdLineTest(unittest.TestCase):
p.stdin.write('exit()\n') p.stdin.write('exit()\n')
data = kill_python(p) data = kill_python(p)
self.assertTrue(data.startswith('1 loop')) self.assertTrue(data.startswith('1 loop'))
self.assertTrue('__main__.Timer' in data) self.assertIn('__main__.Timer', data)
def test_run_code(self): def test_run_code(self):
# Test expected operation of the '-c' switch # Test expected operation of the '-c' switch

View file

@ -81,9 +81,9 @@ class CmdLineTest(unittest.TestCase):
print printed_file print printed_file
print printed_package print printed_package
print printed_argv0 print printed_argv0
self.assertTrue(printed_file in data) self.assertIn(printed_file, data)
self.assertTrue(printed_package in data) self.assertIn(printed_package, data)
self.assertTrue(printed_argv0 in data) self.assertIn(printed_argv0, data)
def _check_import_error(self, script_name, expected_msg, def _check_import_error(self, script_name, expected_msg,
*cmd_line_switches): *cmd_line_switches):
@ -93,7 +93,7 @@ class CmdLineTest(unittest.TestCase):
print 'Output from test script %r:' % script_name print 'Output from test script %r:' % script_name
print data print data
print 'Expected output: %r' % expected_msg print 'Expected output: %r' % expected_msg
self.assertTrue(expected_msg in data) self.assertIn(expected_msg, data)
def test_basic_script(self): def test_basic_script(self):
with temp_dir() as script_dir: with temp_dir() as script_dir:

View file

@ -42,9 +42,9 @@ class TestNamedTuple(unittest.TestCase):
namedtuple('_', 'a b c') # Test leading underscores in a typename namedtuple('_', 'a b c') # Test leading underscores in a typename
nt = namedtuple('nt', u'the quick brown fox') # check unicode input nt = namedtuple('nt', u'the quick brown fox') # check unicode input
self.assertTrue("u'" not in repr(nt._fields)) self.assertNotIn("u'", repr(nt._fields))
nt = namedtuple('nt', (u'the', u'quick')) # check unicode input nt = namedtuple('nt', (u'the', u'quick')) # check unicode input
self.assertTrue("u'" not in repr(nt._fields)) self.assertNotIn("u'", repr(nt._fields))
self.assertRaises(TypeError, Point._make, [11]) # catch too few args self.assertRaises(TypeError, Point._make, [11]) # catch too few args
self.assertRaises(TypeError, Point._make, [11, 22, 33]) # catch too many args self.assertRaises(TypeError, Point._make, [11, 22, 33]) # catch too many args
@ -73,8 +73,8 @@ class TestNamedTuple(unittest.TestCase):
self.assertRaises(TypeError, eval, 'Point(XXX=1, y=2)', locals()) # wrong keyword argument 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.assertRaises(TypeError, eval, 'Point(x=1)', locals()) # missing keyword argument
self.assertEqual(repr(p), 'Point(x=11, y=22)') self.assertEqual(repr(p), 'Point(x=11, y=22)')
self.assertTrue('__dict__' not in dir(p)) # verify instance has no dict self.assertNotIn('__dict__', dir(p)) # verify instance has no dict
self.assertTrue('__weakref__' not in dir(p)) self.assertNotIn('__weakref__', dir(p))
self.assertEqual(p, Point._make([11, 22])) # test _make classmethod self.assertEqual(p, Point._make([11, 22])) # test _make classmethod
self.assertEqual(p._fields, ('x', 'y')) # test _fields attribute self.assertEqual(p._fields, ('x', 'y')) # test _fields attribute
self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method self.assertEqual(p._replace(x=1), (1, 22)) # test _replace method
@ -533,10 +533,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()')
@ -595,6 +595,7 @@ class TestCounter(unittest.TestCase):
c = Counter(a=10, b=-2, c=0) c = Counter(a=10, b=-2, c=0)
for elem in c: for elem in c:
self.assertTrue(elem in c) self.assertTrue(elem in c)
self.assertIn(elem, c)
def test_multiset_operations(self): def test_multiset_operations(self):
# Verify that adding a zero counter will strip zeros and negatives # Verify that adding a zero counter will strip zeros and negatives
@ -693,7 +694,7 @@ class TestOrderedDict(unittest.TestCase):
pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)] pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
od = OrderedDict(pairs) od = OrderedDict(pairs)
del od['a'] del od['a']
self.assertTrue('a' not in od) self.assertNotIn('a', od)
with self.assertRaises(KeyError): with self.assertRaises(KeyError):
del od['a'] del od['a']
self.assertEqual(list(od.items()), pairs[:2] + pairs[3:]) self.assertEqual(list(od.items()), pairs[:2] + pairs[3:])

View file

@ -378,56 +378,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_mangling(self): def test_mangling(self):
class A: class A:
@ -437,10 +437,10 @@ if 1:
import __mangled_mod import __mangled_mod
import __package__.module import __package__.module
self.assertTrue("_A__mangled" in A.f.func_code.co_varnames) self.assertIn("_A__mangled", A.f.func_code.co_varnames)
self.assertTrue("__not_mangled__" in A.f.func_code.co_varnames) self.assertIn("__not_mangled__", A.f.func_code.co_varnames)
self.assertTrue("_A__mangled_mod" in A.f.func_code.co_varnames) self.assertIn("_A__mangled_mod", A.f.func_code.co_varnames)
self.assertTrue("__package__" in A.f.func_code.co_varnames) self.assertIn("__package__", A.f.func_code.co_varnames)
def test_compile_ast(self): def test_compile_ast(self):
fname = __file__ fname = __file__

View file

@ -87,7 +87,7 @@ class CompilerTest(unittest.TestCase):
def testDocstrings(self): def testDocstrings(self):
c = compiler.compile('"doc"', '<string>', 'exec') c = compiler.compile('"doc"', '<string>', 'exec')
self.assertTrue('__doc__' in c.co_names) self.assertIn('__doc__', c.co_names)
c = compiler.compile('def f():\n "doc"', '<string>', 'exec') c = compiler.compile('def f():\n "doc"', '<string>', 'exec')
g = {} g = {}
exec c in g exec c in g

View file

@ -20,57 +20,57 @@ class TestContains(unittest.TestCase):
a = base_set(1) a = base_set(1)
b = set(1) b = set(1)
c = seq(1) c = seq(1)
self.assertTrue(1 in b) self.assertIn(1, b)
self.assertTrue(0 not in b) self.assertNotIn(0, b)
self.assertTrue(1 in c) self.assertIn(1, c)
self.assertTrue(0 not in c) self.assertNotIn(0, c)
self.assertRaises(TypeError, lambda: 1 in a) self.assertRaises(TypeError, lambda: 1 in a)
self.assertRaises(TypeError, lambda: 1 not in a) self.assertRaises(TypeError, lambda: 1 not in a)
# test char in string # test char in string
self.assertTrue('c' in 'abc') self.assertIn('c', 'abc')
self.assertTrue('d' not in 'abc') self.assertNotIn('d', 'abc')
self.assertTrue('' in '') self.assertIn('', '')
self.assertTrue('' in 'abc') self.assertIn('', 'abc')
self.assertRaises(TypeError, lambda: None in 'abc') self.assertRaises(TypeError, lambda: None in 'abc')
if have_unicode: if have_unicode:
def test_char_in_unicode(self): def test_char_in_unicode(self):
self.assertTrue('c' in unicode('abc')) self.assertIn('c', unicode('abc'))
self.assertTrue('d' not in unicode('abc')) self.assertNotIn('d', unicode('abc'))
self.assertTrue('' in unicode('')) self.assertIn('', unicode(''))
self.assertTrue(unicode('') in '') self.assertIn(unicode(''), '')
self.assertTrue(unicode('') in unicode('')) self.assertIn(unicode(''), unicode(''))
self.assertTrue('' in unicode('abc')) self.assertIn('', unicode('abc'))
self.assertTrue(unicode('') in 'abc') self.assertIn(unicode(''), 'abc')
self.assertTrue(unicode('') in unicode('abc')) self.assertIn(unicode(''), unicode('abc'))
self.assertRaises(TypeError, lambda: None in unicode('abc')) self.assertRaises(TypeError, lambda: None in unicode('abc'))
# test Unicode char in Unicode # test Unicode char in Unicode
self.assertTrue(unicode('c') in unicode('abc')) self.assertIn(unicode('c'), unicode('abc'))
self.assertTrue(unicode('d') not in unicode('abc')) self.assertNotIn(unicode('d'), unicode('abc'))
# test Unicode char in string # test Unicode char in string
self.assertTrue(unicode('c') in 'abc') self.assertIn(unicode('c'), 'abc')
self.assertTrue(unicode('d') not in 'abc') self.assertNotIn(unicode('d'), 'abc')
def test_builtin_sequence_types(self): def test_builtin_sequence_types(self):
# a collection of tests on builtin sequence types # a collection of tests on builtin sequence types
a = range(10) a = range(10)
for i in a: for i in a:
self.assertTrue(i in a) self.assertIn(i, a)
self.assertTrue(16 not in a) self.assertNotIn(16, a)
self.assertTrue(a not in a) self.assertNotIn(a, a)
a = tuple(a) a = tuple(a)
for i in a: for i in a:
self.assertTrue(i in a) self.assertIn(i, a)
self.assertTrue(16 not in a) self.assertNotIn(16, a)
self.assertTrue(a not in a) self.assertNotIn(a, a)
class Deviant1: class Deviant1:
"""Behaves strangely when compared """Behaves strangely when compared
@ -86,7 +86,7 @@ class TestContains(unittest.TestCase):
self.aList.remove(14) self.aList.remove(14)
return 1 return 1
self.assertTrue(Deviant1() not in Deviant1.aList) self.assertNotIn(Deviant1(), Deviant1.aList)
class Deviant2: class Deviant2:
"""Behaves strangely when compared """Behaves strangely when compared
@ -99,7 +99,7 @@ class TestContains(unittest.TestCase):
raise RuntimeError, "gotcha" raise RuntimeError, "gotcha"
try: try:
self.assertTrue(Deviant2() not in a) self.assertNotIn(Deviant2(), a)
except TypeError: except TypeError:
pass pass

View file

@ -505,7 +505,7 @@ class CookieTests(TestCase):
self.assertEquals(len(c), 2) self.assertEquals(len(c), 2)
c.clear_session_cookies() c.clear_session_cookies()
self.assertEquals(len(c), 1) self.assertEquals(len(c), 1)
self.assertTrue('spam="bar"' in h) self.assertIn('spam="bar"', h)
# XXX RFC 2965 expiry rules (some apply to V0 too) # XXX RFC 2965 expiry rules (some apply to V0 too)
@ -517,39 +517,39 @@ class CookieTests(TestCase):
c = CookieJar(pol) c = CookieJar(pol)
interact_2965(c, "http://www.acme.com/", 'spam="bar"; Version="1"') interact_2965(c, "http://www.acme.com/", 'spam="bar"; Version="1"')
self.assertTrue("/" in c._cookies["www.acme.com"]) self.assertIn("/", c._cookies["www.acme.com"])
c = CookieJar(pol) c = CookieJar(pol)
interact_2965(c, "http://www.acme.com/blah", 'eggs="bar"; Version="1"') interact_2965(c, "http://www.acme.com/blah", 'eggs="bar"; Version="1"')
self.assertTrue("/" in c._cookies["www.acme.com"]) self.assertIn("/", c._cookies["www.acme.com"])
c = CookieJar(pol) c = CookieJar(pol)
interact_2965(c, "http://www.acme.com/blah/rhubarb", interact_2965(c, "http://www.acme.com/blah/rhubarb",
'eggs="bar"; Version="1"') 'eggs="bar"; Version="1"')
self.assertTrue("/blah/" in c._cookies["www.acme.com"]) self.assertIn("/blah/", c._cookies["www.acme.com"])
c = CookieJar(pol) c = CookieJar(pol)
interact_2965(c, "http://www.acme.com/blah/rhubarb/", interact_2965(c, "http://www.acme.com/blah/rhubarb/",
'eggs="bar"; Version="1"') 'eggs="bar"; Version="1"')
self.assertTrue("/blah/rhubarb/" in c._cookies["www.acme.com"]) self.assertIn("/blah/rhubarb/", c._cookies["www.acme.com"])
# Netscape # Netscape
c = CookieJar() c = CookieJar()
interact_netscape(c, "http://www.acme.com/", 'spam="bar"') interact_netscape(c, "http://www.acme.com/", 'spam="bar"')
self.assertTrue("/" in c._cookies["www.acme.com"]) self.assertIn("/", c._cookies["www.acme.com"])
c = CookieJar() c = CookieJar()
interact_netscape(c, "http://www.acme.com/blah", 'eggs="bar"') interact_netscape(c, "http://www.acme.com/blah", 'eggs="bar"')
self.assertTrue("/" in c._cookies["www.acme.com"]) self.assertIn("/", c._cookies["www.acme.com"])
c = CookieJar() c = CookieJar()
interact_netscape(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"') interact_netscape(c, "http://www.acme.com/blah/rhubarb", 'eggs="bar"')
self.assertTrue("/blah" in c._cookies["www.acme.com"]) self.assertIn("/blah", c._cookies["www.acme.com"])
c = CookieJar() c = CookieJar()
interact_netscape(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"') interact_netscape(c, "http://www.acme.com/blah/rhubarb/", 'eggs="bar"')
self.assertTrue("/blah/rhubarb" in c._cookies["www.acme.com"]) self.assertIn("/blah/rhubarb", c._cookies["www.acme.com"])
def test_escape_path(self): def test_escape_path(self):
from cookielib import escape_path from cookielib import escape_path
@ -937,21 +937,21 @@ 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("Domain" not in h, self.assertNotIn("Domain", h,
"absent domain returned with domain present") "absent domain returned with domain present")
c = CookieJar(pol) c = CookieJar(pol)
url = "http://foo.bar.com/" url = "http://foo.bar.com/"
interact_2965(c, url, 'spam=eggs; Version=1; Domain=.bar.com') interact_2965(c, url, 'spam=eggs; Version=1; Domain=.bar.com')
h = interact_2965(c, url) h = interact_2965(c, url)
self.assertTrue('$Domain=".bar.com"' in h, "domain not returned") self.assertIn('$Domain=".bar.com"', h, "domain not returned")
c = CookieJar(pol) c = CookieJar(pol)
url = "http://foo.bar.com/" url = "http://foo.bar.com/"
# note missing initial dot in Domain # note missing initial dot in Domain
interact_2965(c, url, 'spam=eggs; Version=1; Domain=bar.com') interact_2965(c, url, 'spam=eggs; Version=1; Domain=bar.com')
h = interact_2965(c, url) h = interact_2965(c, url)
self.assertTrue('$Domain="bar.com"' in h, "domain not returned") self.assertIn('$Domain="bar.com"', h, "domain not returned")
def test_path_mirror(self): def test_path_mirror(self):
from cookielib import CookieJar, DefaultCookiePolicy from cookielib import CookieJar, DefaultCookiePolicy
@ -962,14 +962,13 @@ 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/"
interact_2965(c, url, 'spam=eggs; Version=1; Path=/') interact_2965(c, url, 'spam=eggs; Version=1; Path=/')
h = interact_2965(c, url) h = interact_2965(c, url)
self.assertTrue('$Path="/"' in h, "path not returned") self.assertIn('$Path="/"', h, "path not returned")
def test_port_mirror(self): def test_port_mirror(self):
from cookielib import CookieJar, DefaultCookiePolicy from cookielib import CookieJar, DefaultCookiePolicy
@ -980,8 +979,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/"
@ -994,14 +992,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")
@ -1179,8 +1177,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")
@ -1190,17 +1188,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 = Request("http://www.acme.com/foo/") req = 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):
from cookielib import CookieJar from cookielib import CookieJar
@ -1424,8 +1422,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.
@ -1579,11 +1577,11 @@ class LWPCookieTests(TestCase):
new_c = save_and_restore(c, True) new_c = save_and_restore(c, True)
self.assertEquals(len(new_c), 6) # none discarded self.assertEquals(len(new_c), 6) # none discarded
self.assertTrue("name='foo1', value='bar'" in repr(new_c)) self.assertIn("name='foo1', value='bar'", repr(new_c))
new_c = save_and_restore(c, False) new_c = save_and_restore(c, False)
self.assertEquals(len(new_c), 4) # 2 of them discarded on save self.assertEquals(len(new_c), 4) # 2 of them discarded on save
self.assertTrue("name='foo1', value='bar'" in repr(new_c)) self.assertIn("name='foo1', value='bar'", repr(new_c))
def test_netscape_misc(self): def test_netscape_misc(self):
# Some additional Netscape cookies tests. # Some additional Netscape cookies tests.
@ -1621,11 +1619,12 @@ class LWPCookieTests(TestCase):
"foo1=bar; PORT; Discard; Version=1;") "foo1=bar; PORT; Discard; Version=1;")
cookie = interact_2965(c, "http://example/", cookie = interact_2965(c, "http://example/",
'foo2=bar; domain=".local"; Version=1') 'foo2=bar; domain=".local"; Version=1')
self.assertTrue("foo1=bar" in cookie) self.assertIn("foo1=bar", cookie)
interact_2965(c, "http://example/", 'foo3=bar; Version=1') interact_2965(c, "http://example/", 'foo3=bar; Version=1')
cookie = interact_2965(c, "http://example/") cookie = interact_2965(c, "http://example/")
self.assertTrue("foo2=bar" in cookie and len(c) == 3) self.assertIn("foo2=bar", cookie)
self.assertEqual(len(c), 3)
def test_intranet_domains_ns(self): def test_intranet_domains_ns(self):
from cookielib import CookieJar, DefaultCookiePolicy from cookielib import CookieJar, DefaultCookiePolicy
@ -1635,10 +1634,10 @@ class LWPCookieTests(TestCase):
cookie = interact_netscape(c, "http://example/", cookie = interact_netscape(c, "http://example/",
'foo2=bar; domain=.local') 'foo2=bar; domain=.local')
self.assertEquals(len(c), 2) self.assertEquals(len(c), 2)
self.assertTrue("foo1=bar" in cookie) self.assertIn("foo1=bar", cookie)
cookie = interact_netscape(c, "http://example/") cookie = interact_netscape(c, "http://example/")
self.assertTrue("foo2=bar" in cookie) self.assertIn("foo2=bar", cookie)
self.assertEquals(len(c), 2) self.assertEquals(len(c), 2)
def test_empty_path(self): def test_empty_path(self):

View file

@ -622,7 +622,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

@ -54,7 +54,7 @@ class CopyRegTestCase(unittest.TestCase):
self.assertTrue(copy_reg._extension_registry[mod, func] == code) self.assertTrue(copy_reg._extension_registry[mod, func] == code)
self.assertTrue(copy_reg._inverted_registry[code] == (mod, func)) self.assertTrue(copy_reg._inverted_registry[code] == (mod, func))
# Shouldn't be in the cache. # Shouldn't be in the cache.
self.assertTrue(code not in copy_reg._extension_cache) self.assertNotIn(code, copy_reg._extension_cache)
# Redundant registration should be OK. # Redundant registration should be OK.
copy_reg.add_extension(mod, func, code) # shouldn't blow up copy_reg.add_extension(mod, func, code) # shouldn't blow up
# Conflicting code. # Conflicting code.
@ -81,7 +81,7 @@ class CopyRegTestCase(unittest.TestCase):
e.restore() e.restore()
# Shouldn't be there anymore. # Shouldn't be there anymore.
self.assertTrue((mod, func) not in copy_reg._extension_registry) self.assertNotIn((mod, func), copy_reg._extension_registry)
# The code *may* be in copy_reg._extension_registry, though, if # The code *may* be in copy_reg._extension_registry, though, if
# we happened to pick on a registered code. So don't check for # we happened to pick on a registered code. So don't check for
# that. # that.

View file

@ -935,7 +935,7 @@ Stonecutters Seafood and Chop House, Lemont, IL, 12/19/02, Week Back
# given that all three lines in sample3 are equal, # given that all three lines in sample3 are equal,
# I think that any character could have been 'guessed' as the # I think that any character could have been 'guessed' as the
# delimiter, depending on dictionary order # delimiter, depending on dictionary order
self.assertTrue(dialect.delimiter in self.sample3) self.assertIn(dialect.delimiter, self.sample3)
dialect = sniffer.sniff(self.sample3, delimiters="?,") dialect = sniffer.sniff(self.sample3, delimiters="?,")
self.assertEqual(dialect.delimiter, "?") self.assertEqual(dialect.delimiter, "?")
dialect = sniffer.sniff(self.sample3, delimiters="/,") dialect = sniffer.sniff(self.sample3, delimiters="/,")

View file

@ -141,11 +141,8 @@ class HarmlessMixedComparison:
self.assertFalse(() == me) self.assertFalse(() == me)
self.assertTrue(() != me) self.assertTrue(() != me)
self.assertTrue(me in [1, 20L, [], me]) self.assertIn(me, [1, 20L, [], me])
self.assertFalse(me not in [1, 20L, [], me]) self.assertIn([], [me, 1, 20L, []])
self.assertTrue([] in [me, 1, 20L, []])
self.assertFalse([] not in [me, 1, 20L, []])
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

@ -21,9 +21,9 @@ class DbmTestCase(unittest.TestCase):
self.d[k] = v self.d[k] = v
self.assertEqual(sorted(self.d.keys()), sorted(k for (k, v) in a)) self.assertEqual(sorted(self.d.keys()), sorted(k for (k, v) in a))
for k, v in a: for k, v in a:
self.assertTrue(k in self.d) self.assertIn(k, self.d)
self.assertEqual(self.d[k], v) self.assertEqual(self.d[k], v)
self.assertTrue('xxx' not in self.d) self.assertNotIn('xxx', self.d)
self.assertRaises(KeyError, lambda: self.d['xxx']) self.assertRaises(KeyError, lambda: self.d['xxx'])
self.d.close() self.d.close()

View file

@ -1628,8 +1628,8 @@ class ContextAPItests(unittest.TestCase):
self.assertEqual(v1, v2) self.assertEqual(v1, v2)
def test_equality_with_other_types(self): def test_equality_with_other_types(self):
self.assertTrue(Decimal(10) in ['a', 1.0, Decimal(10), (1,2), {}]) self.assertIn(Decimal(10), ['a', 1.0, Decimal(10), (1,2), {}])
self.assertTrue(Decimal(10) not in ['a', 1.0, (1,2), {}]) self.assertNotIn(Decimal(10), ['a', 1.0, (1,2), {}])
def test_copy(self): def test_copy(self):
# All copies should be deep # All copies should be deep

View file

@ -31,14 +31,14 @@ class TestDefaultDict(unittest.TestCase):
self.assertEqual(d2["foo"], 1) self.assertEqual(d2["foo"], 1)
self.assertEqual(d2["bar"], 2) self.assertEqual(d2["bar"], 2)
self.assertEqual(d2[42], []) self.assertEqual(d2[42], [])
self.assertTrue("foo" in d2) self.assertIn("foo", d2)
self.assertTrue("foo" in d2.keys()) self.assertIn("foo", d2.keys())
self.assertTrue("bar" in d2) self.assertIn("bar", d2)
self.assertTrue("bar" in d2.keys()) self.assertIn("bar", d2.keys())
self.assertTrue(42 in d2) self.assertIn(42, d2)
self.assertTrue(42 in d2.keys()) self.assertIn(42, d2.keys())
self.assertTrue(12 not in d2) self.assertNotIn(12, d2)
self.assertTrue(12 not in d2.keys()) self.assertNotIn(12, d2.keys())
d2.default_factory = None d2.default_factory = None
self.assertEqual(d2.default_factory, None) self.assertEqual(d2.default_factory, None)
try: try:

View file

@ -199,9 +199,9 @@ class TestBasic(unittest.TestCase):
self.assertEqual(len(d), n-i) self.assertEqual(len(d), n-i)
j = random.randrange(-len(d), len(d)) j = random.randrange(-len(d), len(d))
val = d[j] val = d[j]
self.assertTrue(val in d) self.assertIn(val, d)
del d[j] del d[j]
self.assertTrue(val not in d) self.assertNotIn(val, d)
self.assertEqual(len(d), 0) self.assertEqual(len(d), 0)
def test_reverse(self): def test_reverse(self):
@ -328,7 +328,7 @@ class TestBasic(unittest.TestCase):
e = eval(repr(d)) e = eval(repr(d))
self.assertEqual(list(d), list(e)) self.assertEqual(list(d), list(e))
d.append(d) d.append(d)
self.assertTrue('...' in repr(d)) self.assertIn('...', repr(d))
def test_print(self): def test_print(self):
d = deque(xrange(200)) d = deque(xrange(200))

View file

@ -527,7 +527,7 @@ class ClassPropertiesAndMethods(unittest.TestCase):
return 42 return 42
self.assertEqual(C.name, 'C') self.assertEqual(C.name, 'C')
self.assertEqual(C.bases, ()) self.assertEqual(C.bases, ())
self.assertTrue('spam' in C.dict) self.assertIn('spam', C.dict)
c = C() c = C()
self.assertEqual(c.spam(), 42) self.assertEqual(c.spam(), 42)
@ -1802,10 +1802,10 @@ order (MRO) for bases """
# depending on whether this test is run standalone or from a framework. # depending on whether this test is run standalone or from a framework.
self.assertTrue(str(c1).find('C object at ') >= 0) self.assertTrue(str(c1).find('C object at ') >= 0)
self.assertEqual(str(c1), repr(c1)) self.assertEqual(str(c1), repr(c1))
self.assertTrue(-1 not in c1) self.assertNotIn(-1, c1)
for i in range(10): for i in range(10):
self.assertTrue(i in 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):
@ -1826,10 +1826,10 @@ order (MRO) for bases """
# depending on whether this test is run standalone or from a framework. # depending on whether this test is run standalone or from a framework.
self.assertTrue(str(d1).find('D object at ') >= 0) self.assertTrue(str(d1).find('D object at ') >= 0)
self.assertEqual(str(d1), repr(d1)) self.assertEqual(str(d1), repr(d1))
self.assertTrue(-1 not in d1) self.assertNotIn(-1, d1)
for i in range(10): for i in range(10):
self.assertTrue(i in d1) self.assertIn(i, d1)
self.assertFalse(10 in d1) self.assertNotIn(10, d1)
# Test overridden behavior for static classes # Test overridden behavior for static classes
class Proxy(object): class Proxy(object):
def __init__(self, x): def __init__(self, x):
@ -1866,10 +1866,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.assertTrue(i in p10) self.assertIn(i, p10)
self.assertFalse(10 in p10) self.assertNotIn(10, p10)
# Test overridden behavior for dynamic classes # Test overridden behavior for dynamic classes
class DProxy(object): class DProxy(object):
def __init__(self, x): def __init__(self, x):
@ -1906,10 +1906,10 @@ order (MRO) for bases """
self.assertEqual(str(p0), "DProxy:0") self.assertEqual(str(p0), "DProxy:0")
self.assertEqual(repr(p0), "DProxy(0)") self.assertEqual(repr(p0), "DProxy(0)")
p10 = DProxy(range(10)) p10 = DProxy(range(10))
self.assertFalse(-1 in p10) self.assertNotIn(-1, p10)
for i in range(10): for i in range(10):
self.assertTrue(i in p10) self.assertIn(i, p10)
self.assertFalse(10 in p10) self.assertNotIn(10, p10)
# Safety test for __cmp__ # Safety test for __cmp__
def unsafecmp(a, b): def unsafecmp(a, b):
@ -2028,10 +2028,10 @@ order (MRO) for bases """
self.assertTrue(isinstance(raw, property)) self.assertTrue(isinstance(raw, property))
attrs = dir(raw) attrs = dir(raw)
self.assertTrue("__doc__" in attrs) self.assertIn("__doc__", attrs)
self.assertTrue("fget" in attrs) self.assertIn("fget", attrs)
self.assertTrue("fset" in attrs) self.assertIn("fset", attrs)
self.assertTrue("fdel" in attrs) self.assertIn("fdel", attrs)
self.assertEqual(raw.__doc__, "I'm the x property.") self.assertEqual(raw.__doc__, "I'm the x property.")
self.assertTrue(raw.fget is C.__dict__['getx']) self.assertTrue(raw.fget is C.__dict__['getx'])
@ -2249,7 +2249,7 @@ order (MRO) for bases """
cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__'] cstuff = ['Cdata', 'Cmethod', '__doc__', '__module__']
self.assertEqual(dir(C), cstuff) self.assertEqual(dir(C), cstuff)
self.assertTrue('im_self' in dir(C.Cmethod)) self.assertIn('im_self', dir(C.Cmethod))
c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__. c = C() # c.__doc__ is an odd thing to see here; ditto c.__module__.
self.assertEqual(dir(c), cstuff) self.assertEqual(dir(c), cstuff)
@ -2257,7 +2257,7 @@ order (MRO) for bases """
c.cdata = 2 c.cdata = 2
c.cmethod = lambda self: 0 c.cmethod = lambda self: 0
self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod']) self.assertEqual(dir(c), cstuff + ['cdata', 'cmethod'])
self.assertTrue('im_self' in dir(c.Cmethod)) self.assertIn('im_self', dir(c.Cmethod))
class A(C): class A(C):
Adata = 1 Adata = 1
@ -2265,10 +2265,10 @@ order (MRO) for bases """
astuff = ['Adata', 'Amethod'] + cstuff astuff = ['Adata', 'Amethod'] + cstuff
self.assertEqual(dir(A), astuff) self.assertEqual(dir(A), astuff)
self.assertTrue('im_self' in dir(A.Amethod)) self.assertIn('im_self', dir(A.Amethod))
a = A() a = A()
self.assertEqual(dir(a), astuff) self.assertEqual(dir(a), astuff)
self.assertTrue('im_self' in dir(a.Amethod)) self.assertIn('im_self', dir(a.Amethod))
a.adata = 42 a.adata = 42
a.amethod = lambda self: 3 a.amethod = lambda self: 3
self.assertEqual(dir(a), astuff + ['adata', 'amethod']) self.assertEqual(dir(a), astuff + ['adata', 'amethod'])
@ -2287,12 +2287,12 @@ order (MRO) for bases """
c = C() c = C()
self.assertEqual(interesting(dir(c)), cstuff) self.assertEqual(interesting(dir(c)), cstuff)
self.assertTrue('im_self' in dir(C.Cmethod)) self.assertIn('im_self', dir(C.Cmethod))
c.cdata = 2 c.cdata = 2
c.cmethod = lambda self: 0 c.cmethod = lambda self: 0
self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod']) self.assertEqual(interesting(dir(c)), cstuff + ['cdata', 'cmethod'])
self.assertTrue('im_self' in dir(c.Cmethod)) self.assertIn('im_self', dir(c.Cmethod))
class A(C): class A(C):
Adata = 1 Adata = 1
@ -2300,13 +2300,13 @@ order (MRO) for bases """
astuff = ['Adata', 'Amethod'] + cstuff astuff = ['Adata', 'Amethod'] + cstuff
self.assertEqual(interesting(dir(A)), astuff) self.assertEqual(interesting(dir(A)), astuff)
self.assertTrue('im_self' in dir(A.Amethod)) self.assertIn('im_self', dir(A.Amethod))
a = A() a = A()
self.assertEqual(interesting(dir(a)), astuff) self.assertEqual(interesting(dir(a)), astuff)
a.adata = 42 a.adata = 42
a.amethod = lambda self: 3 a.amethod = lambda self: 3
self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod']) self.assertEqual(interesting(dir(a)), astuff + ['adata', 'amethod'])
self.assertTrue('im_self' in dir(a.Amethod)) self.assertIn('im_self', dir(a.Amethod))
# Try a module subclass. # Try a module subclass.
import sys import sys
@ -2864,7 +2864,7 @@ order (MRO) for bases """
self.assertEqual(d[cistr('one')], 1) self.assertEqual(d[cistr('one')], 1)
self.assertEqual(d[cistr('tWo')], 2) self.assertEqual(d[cistr('tWo')], 2)
self.assertEqual(d[cistr('THrEE')], 3) self.assertEqual(d[cistr('THrEE')], 3)
self.assertTrue(cistr('ONe') in d) self.assertIn(cistr('ONe'), d)
self.assertEqual(d.get(cistr('thrEE')), 3) self.assertEqual(d.get(cistr('thrEE')), 3)
def test_classic_comparisons(self): def test_classic_comparisons(self):

View file

@ -67,12 +67,13 @@ 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)
d = {'a': 1, 'b': 2} d = {'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__)
@ -430,8 +431,8 @@ 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.assertTrue(2 not in d.keys()) self.assertNotIn(2, d.keys())
self.assertEqual(d[2], 42) self.assertEqual(d[2], 42)
class E(dict): class E(dict):
def __missing__(self, key): def __missing__(self, key):

View file

@ -24,10 +24,10 @@ class DictSetTest(unittest.TestCase):
self.assertNotEqual(keys, set([1, "b"])) self.assertNotEqual(keys, set([1, "b"]))
self.assertNotEqual(keys, set([1])) self.assertNotEqual(keys, set([1]))
self.assertNotEqual(keys, 42) self.assertNotEqual(keys, 42)
self.assert_(1 in keys) self.assertIn(1, keys)
self.assert_("a" in keys) self.assertIn("a", keys)
self.assert_(10 not in keys) self.assertNotIn(10, keys)
self.assert_("Z" not in keys) self.assertNotIn("Z", keys)
self.assertEqual(d.viewkeys(), d.viewkeys()) self.assertEqual(d.viewkeys(), d.viewkeys())
e = {1: 11, "a": "def"} e = {1: 11, "a": "def"}
self.assertEqual(d.viewkeys(), e.viewkeys()) self.assertEqual(d.viewkeys(), e.viewkeys())
@ -44,13 +44,13 @@ class DictSetTest(unittest.TestCase):
self.assertNotEqual(items, set([(1, 10), ("a", "def")])) self.assertNotEqual(items, set([(1, 10), ("a", "def")]))
self.assertNotEqual(items, set([(1, 10)])) self.assertNotEqual(items, set([(1, 10)]))
self.assertNotEqual(items, 42) self.assertNotEqual(items, 42)
self.assert_((1, 10) in items) self.assertIn((1, 10), items)
self.assert_(("a", "ABC") in items) self.assertIn(("a", "ABC"), items)
self.assert_((1, 11) not in items) self.assertNotIn((1, 11), items)
self.assert_(1 not in items) self.assertNotIn(1, items)
self.assert_(() not in items) self.assertNotIn((), items)
self.assert_((1,) not in items) self.assertNotIn((1,), items)
self.assert_((1, 2, 3) not in items) self.assertNotIn((1, 2, 3), items)
self.assertEqual(d.viewitems(), d.viewitems()) self.assertEqual(d.viewitems(), d.viewitems())
e = d.copy() e = d.copy()
self.assertEqual(d.viewitems(), e.viewitems()) self.assertEqual(d.viewitems(), e.viewitems())

View file

@ -103,8 +103,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

@ -19,8 +19,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):
@ -107,9 +107,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('<dl><dt><a name="-&lt;lambda&gt;"><strong>'
"""<dl><dt><a name="-&lt;lambda&gt;"><strong>&lt;lambda&gt;</strong></a>(x, y)</dt></dl>""" '&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
@ -121,9 +121,17 @@ class DocXMLRPCHTTPGETServer(unittest.TestCase):
self.client.request("GET", "/") self.client.request("GET", "/")
response = self.client.getresponse() response = self.client.getresponse()
self.assertTrue( # This is ugly ... how can it be made better? self.assertIn(
"""<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>""" ('<dl><dt><a name="-add"><strong>add</strong></a>(x, y)</dt><dd>'
in response.read()) '<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>'), response.read())
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.
@ -134,9 +142,29 @@ class DocXMLRPCHTTPGETServer(unittest.TestCase):
self.client.request("GET", "/") self.client.request("GET", "/")
response = self.client.getresponse() response = self.client.getresponse()
self.assertTrue( self.assertIn(
"""<dl><dt><a name="-system.listMethods"><strong>system.listMethods</strong></a>()</dt><dd><tt><a href="#-system.listMethods">system.listMethods</a>()&nbsp;=&gt;&nbsp;[\'add\',&nbsp;\'subtract\',&nbsp;\'multiple\']<br>\n&nbsp;<br>\nReturns&nbsp;a&nbsp;list&nbsp;of&nbsp;the&nbsp;methods&nbsp;supported&nbsp;by&nbsp;the&nbsp;server.</tt></dd></dl>\n <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>""" ('<dl><dt><a name="-system.listMethods"><strong>system.listMethods'
in response.read()) '</strong></a>()</dt><dd><tt><a href="#-system.listMethods">system'
'.listMethods</a>()&nbsp;=&gt;&nbsp;[\'add\',&nbsp;\'subtract\','
'&nbsp;\'multiple\']<br>\n&nbsp;<br>\nReturns&nbsp;a&nbsp;list'
'&nbsp;of&nbsp;the&nbsp;methods&nbsp;supported&nbsp;by&nbsp;the'
'&nbsp;server.</tt></dd></dl>\n <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>'),
response.read())
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
@ -144,7 +172,7 @@ class DocXMLRPCHTTPGETServer(unittest.TestCase):
self.client.request("GET", "/") self.client.request("GET", "/")
response = self.client.getresponse() response = self.client.getresponse()
self.assertTrue("""Try&nbsp;self.<strong>add</strong>,&nbsp;too.""" in self.assertIn("""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__.iterkeys(): for attribute in errno.__dict__.iterkeys():
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

@ -428,7 +428,7 @@ class ExceptionTests(unittest.TestCase):
return sys.exc_info() return sys.exc_info()
e, v, tb = g() e, v, tb = g()
self.assertTrue(e is RuntimeError, e) self.assertTrue(e is RuntimeError, e)
self.assertTrue("maximum recursion depth exceeded" in str(v), v) self.assertIn("maximum recursion depth exceeded", str(v))

View file

@ -434,9 +434,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

@ -36,14 +36,14 @@ class FunctionPropertiesTest(FuncAttrsTest):
def test_dir_includes_correct_attrs(self): def test_dir_includes_correct_attrs(self):
self.b.known_attr = 7 self.b.known_attr = 7
self.assertTrue('known_attr' in dir(self.b), self.assertIn('known_attr', dir(self.b),
"set attributes not in dir listing of method") "set attributes not in dir listing of method")
# Test on underlying function object of method # Test on underlying function object of method
self.f.a.im_func.known_attr = 7 self.f.a.im_func.known_attr = 7
self.assertTrue('known_attr' in dir(self.f.a), self.assertIn('known_attr', dir(self.f.a),
"set attribute on unbound method implementation in " "set attribute on unbound method implementation in "
"class not in dir") "class not in dir")
self.assertTrue('known_attr' in dir(self.fi.a), self.assertIn('known_attr', dir(self.fi.a),
"set attribute on unbound method implementations, " "set attribute on unbound method implementations, "
"should show up in next dir") "should show up in next dir")

View file

@ -27,7 +27,7 @@ class TestGdbm(unittest.TestCase):
self.assertTrue(self.g.has_key('a')) self.assertTrue(self.g.has_key('a'))
key = self.g.firstkey() key = self.g.firstkey()
while key: while key:
self.assertTrue(key in key_set) self.assertIn(key, key_set)
key_set.remove(key) key_set.remove(key)
key = self.g.nextkey(key) key = self.g.nextkey(key)
self.assertRaises(KeyError, lambda: self.g['xxx']) self.assertRaises(KeyError, lambda: self.g['xxx'])

View file

@ -96,7 +96,7 @@ class GlobTests(unittest.TestCase):
res = glob.glob(self.tempdir + '*' + os.sep) res = glob.glob(self.tempdir + '*' + os.sep)
self.assertEqual(len(res), 1) self.assertEqual(len(res), 1)
# either of these results are reasonable # either of these results are reasonable
self.assertTrue(res[0] in [self.tempdir, self.tempdir + os.sep]) self.assertIn(res[0], [self.tempdir, self.tempdir + os.sep])
def test_glob_broken_symlinks(self): def test_glob_broken_symlinks(self):
if hasattr(os, 'symlink'): if hasattr(os, 'symlink'):

View file

@ -202,7 +202,7 @@ class ImportTest(unittest.TestCase):
sys.path.insert(0, os.curdir) sys.path.insert(0, os.curdir)
try: try:
mod = __import__(TESTFN) mod = __import__(TESTFN)
self.assertTrue(TESTFN in sys.modules, "expected module in sys.modules") self.assertIn(TESTFN, sys.modules)
self.assertEquals(mod.a, 1, "module has wrong attribute values") self.assertEquals(mod.a, 1, "module has wrong attribute values")
self.assertEquals(mod.b, 2, "module has wrong attribute values") self.assertEquals(mod.b, 2, "module has wrong attribute values")
@ -436,14 +436,14 @@ class RelativeImport(unittest.TestCase):
ns = dict(__package__='foo', __name__='test.notarealmodule') ns = dict(__package__='foo', __name__='test.notarealmodule')
with check_warnings() as w: with check_warnings() as w:
check_absolute() check_absolute()
self.assertTrue('foo' in str(w.message)) self.assertIn('foo', str(w.message))
self.assertEqual(w.category, RuntimeWarning) self.assertEqual(w.category, RuntimeWarning)
self.assertRaises(SystemError, check_relative) self.assertRaises(SystemError, check_relative)
# Check relative fails with __package__ and __name__ wrong # Check relative fails with __package__ and __name__ wrong
ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule') ns = dict(__package__='foo', __name__='notarealpkg.notarealmodule')
with check_warnings() as w: with check_warnings() as w:
check_absolute() check_absolute()
self.assertTrue('foo' in str(w.message)) self.assertIn('foo', str(w.message))
self.assertEqual(w.category, RuntimeWarning) self.assertEqual(w.category, RuntimeWarning)
self.assertRaises(SystemError, check_relative) self.assertRaises(SystemError, check_relative)
# Check both fail with package set to a non-string # Check both fail with package set to a non-string

View file

@ -112,8 +112,8 @@ class TestPredicates(IsTestBase):
x = C() x = C()
x.a = 42 x.a = 42
members = dict(inspect.getmembers(x)) members = dict(inspect.getmembers(x))
self.assertTrue('a' in members) self.assertIn('a', members)
self.assertTrue('b' not in members) self.assertNotIn('b', members)
def test_isabstract(self): def test_isabstract(self):
from abc import ABCMeta, abstractmethod from abc import ABCMeta, abstractmethod
@ -442,23 +442,23 @@ class TestClassesAndFunctions(unittest.TestCase):
datablob = '1' datablob = '1'
attrs = attrs_wo_objs(A) attrs = attrs_wo_objs(A)
self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') self.assertIn(('s', 'static method', A), attrs, 'missing static method')
self.assertTrue(('c', 'class method', A) in attrs, 'missing class method') self.assertIn(('c', 'class method', A), attrs, 'missing class method')
self.assertTrue(('p', 'property', A) in attrs, 'missing property') self.assertIn(('p', 'property', A), attrs, 'missing property')
self.assertTrue(('m', 'method', A) in attrs, 'missing plain method') self.assertIn(('m', 'method', A), attrs, 'missing plain method')
self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method') self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') self.assertIn(('datablob', 'data', A), attrs, 'missing data')
class B(A): class B(A):
def m(self): pass def m(self): pass
attrs = attrs_wo_objs(B) attrs = attrs_wo_objs(B)
self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') self.assertIn(('s', 'static method', A), attrs, 'missing static method')
self.assertTrue(('c', 'class method', A) in attrs, 'missing class method') self.assertIn(('c', 'class method', A), attrs, 'missing class method')
self.assertTrue(('p', 'property', A) in attrs, 'missing property') self.assertIn(('p', 'property', A), attrs, 'missing property')
self.assertTrue(('m', 'method', B) in attrs, 'missing plain method') self.assertIn(('m', 'method', B), attrs, 'missing plain method')
self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method') self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') self.assertIn(('datablob', 'data', A), attrs, 'missing data')
class C(A): class C(A):
@ -466,23 +466,23 @@ class TestClassesAndFunctions(unittest.TestCase):
def c(self): pass def c(self): pass
attrs = attrs_wo_objs(C) attrs = attrs_wo_objs(C)
self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') self.assertIn(('s', 'static method', A), attrs, 'missing static method')
self.assertTrue(('c', 'method', C) in attrs, 'missing plain method') self.assertIn(('c', 'method', C), attrs, 'missing plain method')
self.assertTrue(('p', 'property', A) in attrs, 'missing property') self.assertIn(('p', 'property', A), attrs, 'missing property')
self.assertTrue(('m', 'method', C) in attrs, 'missing plain method') self.assertIn(('m', 'method', C), attrs, 'missing plain method')
self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method') self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') self.assertIn(('datablob', 'data', A), attrs, 'missing data')
class D(B, C): class D(B, C):
def m1(self): pass def m1(self): pass
attrs = attrs_wo_objs(D) attrs = attrs_wo_objs(D)
self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') self.assertIn(('s', 'static method', A), attrs, 'missing static method')
self.assertTrue(('c', 'class method', A) in attrs, 'missing class method') self.assertIn(('c', 'class method', A), attrs, 'missing class method')
self.assertTrue(('p', 'property', A) in attrs, 'missing property') self.assertIn(('p', 'property', A), attrs, 'missing property')
self.assertTrue(('m', 'method', B) in attrs, 'missing plain method') self.assertIn(('m', 'method', B), attrs, 'missing plain method')
self.assertTrue(('m1', 'method', D) in attrs, 'missing plain method') self.assertIn(('m1', 'method', D), attrs, 'missing plain method')
self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') self.assertIn(('datablob', 'data', A), attrs, 'missing data')
# Repeat all that, but w/ new-style classes. # Repeat all that, but w/ new-style classes.
def test_classify_newstyle(self): def test_classify_newstyle(self):
@ -504,24 +504,24 @@ class TestClassesAndFunctions(unittest.TestCase):
datablob = '1' datablob = '1'
attrs = attrs_wo_objs(A) attrs = attrs_wo_objs(A)
self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') self.assertIn(('s', 'static method', A), attrs, 'missing static method')
self.assertTrue(('c', 'class method', A) in attrs, 'missing class method') self.assertIn(('c', 'class method', A), attrs, 'missing class method')
self.assertTrue(('p', 'property', A) in attrs, 'missing property') self.assertIn(('p', 'property', A), attrs, 'missing property')
self.assertTrue(('m', 'method', A) in attrs, 'missing plain method') self.assertIn(('m', 'method', A), attrs, 'missing plain method')
self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method') self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') self.assertIn(('datablob', 'data', A), attrs, 'missing data')
class B(A): class B(A):
def m(self): pass def m(self): pass
attrs = attrs_wo_objs(B) attrs = attrs_wo_objs(B)
self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') self.assertIn(('s', 'static method', A), attrs, 'missing static method')
self.assertTrue(('c', 'class method', A) in attrs, 'missing class method') self.assertIn(('c', 'class method', A), attrs, 'missing class method')
self.assertTrue(('p', 'property', A) in attrs, 'missing property') self.assertIn(('p', 'property', A), attrs, 'missing property')
self.assertTrue(('m', 'method', B) in attrs, 'missing plain method') self.assertIn(('m', 'method', B), attrs, 'missing plain method')
self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method') self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') self.assertIn(('datablob', 'data', A), attrs, 'missing data')
class C(A): class C(A):
@ -530,24 +530,24 @@ class TestClassesAndFunctions(unittest.TestCase):
def c(self): pass def c(self): pass
attrs = attrs_wo_objs(C) attrs = attrs_wo_objs(C)
self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') self.assertIn(('s', 'static method', A), attrs, 'missing static method')
self.assertTrue(('c', 'method', C) in attrs, 'missing plain method') self.assertIn(('c', 'method', C), attrs, 'missing plain method')
self.assertTrue(('p', 'property', A) in attrs, 'missing property') self.assertIn(('p', 'property', A), attrs, 'missing property')
self.assertTrue(('m', 'method', C) in attrs, 'missing plain method') self.assertIn(('m', 'method', C), attrs, 'missing plain method')
self.assertTrue(('m1', 'method', A) in attrs, 'missing plain method') self.assertIn(('m1', 'method', A), attrs, 'missing plain method')
self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') self.assertIn(('datablob', 'data', A), attrs, 'missing data')
class D(B, C): class D(B, C):
def m1(self): pass def m1(self): pass
attrs = attrs_wo_objs(D) attrs = attrs_wo_objs(D)
self.assertTrue(('s', 'static method', A) in attrs, 'missing static method') self.assertIn(('s', 'static method', A), attrs, 'missing static method')
self.assertTrue(('c', 'method', C) in attrs, 'missing plain method') self.assertIn(('c', 'method', C), attrs, 'missing plain method')
self.assertTrue(('p', 'property', A) in attrs, 'missing property') self.assertIn(('p', 'property', A), attrs, 'missing property')
self.assertTrue(('m', 'method', B) in attrs, 'missing plain method') self.assertIn(('m', 'method', B), attrs, 'missing plain method')
self.assertTrue(('m1', 'method', D) in attrs, 'missing plain method') self.assertIn(('m1', 'method', D), attrs, 'missing plain method')
self.assertTrue(('datablob', 'data', A) in attrs, 'missing data') self.assertIn(('datablob', 'data', A), attrs, 'missing data')
def test_main(): def test_main():
run_unittest(TestDecorators, TestRetrievingSourceCode, TestOneliners, run_unittest(TestDecorators, TestRetrievingSourceCode, TestOneliners,

View file

@ -24,7 +24,7 @@ class IoctlTests(unittest.TestCase):
tty = open("/dev/tty", "r") tty = open("/dev/tty", "r")
r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ") r = fcntl.ioctl(tty, termios.TIOCGPGRP, " ")
rpgrp = struct.unpack("i", r)[0] rpgrp = struct.unpack("i", r)[0]
self.assertTrue(rpgrp in ids, "%s not in %s" % (rpgrp, ids)) self.assertIn(rpgrp, ids)
def test_ioctl_mutate(self): def test_ioctl_mutate(self):
import array import array
@ -34,7 +34,7 @@ class IoctlTests(unittest.TestCase):
r = fcntl.ioctl(tty, termios.TIOCGPGRP, buf, 1) r = fcntl.ioctl(tty, termios.TIOCGPGRP, buf, 1)
rpgrp = buf[0] rpgrp = buf[0]
self.assertEquals(r, 0) self.assertEquals(r, 0)
self.assertTrue(rpgrp in ids, "%s not in %s" % (rpgrp, ids)) self.assertIn(rpgrp, ids)
def test_ioctl_signed_unsigned_code_param(self): def test_ioctl_signed_unsigned_code_param(self):
if not pty: if not pty:

View file

@ -566,23 +566,23 @@ class TestCase(unittest.TestCase):
def test_in_and_not_in(self): def test_in_and_not_in(self):
for sc5 in IteratingSequenceClass(5), SequenceClass(5): for sc5 in IteratingSequenceClass(5), SequenceClass(5):
for i in range(5): for i in range(5):
self.assertTrue(i in sc5) self.assertIn(i, sc5)
for i in "abc", -1, 5, 42.42, (3, 4), [], {1: 1}, 3-12j, sc5: for i in "abc", -1, 5, 42.42, (3, 4), [], {1: 1}, 3-12j, sc5:
self.assertTrue(i not in sc5) self.assertNotIn(i, sc5)
self.assertRaises(TypeError, lambda: 3 in 12) self.assertRaises(TypeError, lambda: 3 in 12)
self.assertRaises(TypeError, lambda: 3 not in map) self.assertRaises(TypeError, lambda: 3 not in map)
d = {"one": 1, "two": 2, "three": 3, 1j: 2j} d = {"one": 1, "two": 2, "three": 3, 1j: 2j}
for k in d: for k in d:
self.assertTrue(k in d) self.assertIn(k, d)
self.assertTrue(k not in d.itervalues()) self.assertNotIn(k, d.itervalues())
for v in d.values(): for v in d.values():
self.assertTrue(v in d.itervalues()) self.assertIn(v, d.itervalues())
self.assertTrue(v not in d) self.assertNotIn(v, d)
for k, v in d.iteritems(): for k, v in d.iteritems():
self.assertTrue((k, v) in d.iteritems()) self.assertIn((k, v), d.iteritems())
self.assertTrue((v, k) not in d.iteritems()) self.assertNotIn((v, k), d.iteritems())
f = open(TESTFN, "w") f = open(TESTFN, "w")
try: try:
@ -593,9 +593,9 @@ class TestCase(unittest.TestCase):
try: try:
for chunk in "abc": for chunk in "abc":
f.seek(0, 0) f.seek(0, 0)
self.assertTrue(chunk not in f) self.assertNotIn(chunk, f)
f.seek(0, 0) f.seek(0, 0)
self.assertTrue((chunk + "\n") in f) self.assertIn((chunk + "\n"), f)
finally: finally:
f.close() f.close()
try: try:

View file

@ -1385,7 +1385,7 @@ class SubclassWithKwargsTest(unittest.TestCase):
Subclass(newarg=1) Subclass(newarg=1)
except TypeError, err: except TypeError, 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

@ -256,7 +256,7 @@ class MhlibTests(unittest.TestCase):
eq = self.assertEquals eq = self.assertEquals
mh.makefolder("dummy1") mh.makefolder("dummy1")
self.assertTrue("dummy1" in mh.listfolders()) self.assertIn("dummy1", mh.listfolders())
path = os.path.join(_mhpath, "dummy1") path = os.path.join(_mhpath, "dummy1")
self.assertTrue(os.path.exists(path)) self.assertTrue(os.path.exists(path))
@ -310,7 +310,7 @@ class MhlibTests(unittest.TestCase):
mh.deletefolder('dummy1') mh.deletefolder('dummy1')
mh.deletefolder('dummy2') mh.deletefolder('dummy2')
self.assertTrue('dummy1' not in mh.listfolders()) self.assertNotIn('dummy1', mh.listfolders())
self.assertTrue(not os.path.exists(path)) self.assertTrue(not os.path.exists(path))
def test_read(self): def test_read(self):

View file

@ -31,7 +31,7 @@ class MimeToolsTest(unittest.TestCase):
s = set([""]) s = set([""])
for i in xrange(100): for i in xrange(100):
nb = mimetools.choose_boundary() nb = mimetools.choose_boundary()
self.assertTrue(nb not in s) self.assertNotIn(nb, s)
s.add(nb) s.add(nb)
def test_message(self): def test_message(self):

View file

@ -502,7 +502,7 @@ class MmapTests(unittest.TestCase):
def test_error(self): def test_error(self):
self.assertTrue(issubclass(mmap.error, EnvironmentError)) self.assertTrue(issubclass(mmap.error, EnvironmentError))
self.assertTrue("mmap.error" in str(mmap.error)) self.assertIn("mmap.error", str(mmap.error))
def test_io_methods(self): def test_io_methods(self):
data = "0123456789" data = "0123456789"

View file

@ -222,7 +222,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('\x0e' in u'\N{SOFT HYPHEN}'.encode('iso-2022-jp-2')) self.assertNotIn('\x0e', u'\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 = u'\u3406'.encode(encoding) e = u'\u3406'.encode(encoding)
self.assertFalse(filter(lambda x: x >= '\x80', e)) self.assertFalse(filter(lambda x: x >= '\x80', e))

View file

@ -162,7 +162,7 @@ class _TestProcess(BaseTestCase):
self.assertEquals(p.authkey, current.authkey) self.assertEquals(p.authkey, current.authkey)
self.assertEquals(p.is_alive(), False) self.assertEquals(p.is_alive(), False)
self.assertEquals(p.daemon, True) self.assertEquals(p.daemon, True)
self.assertTrue(p not in self.active_children()) self.assertNotIn(p, self.active_children())
self.assertTrue(type(self.active_children()) is list) self.assertTrue(type(self.active_children()) is list)
self.assertEqual(p.exitcode, None) self.assertEqual(p.exitcode, None)
@ -170,7 +170,7 @@ class _TestProcess(BaseTestCase):
self.assertEquals(p.exitcode, None) self.assertEquals(p.exitcode, None)
self.assertEquals(p.is_alive(), True) self.assertEquals(p.is_alive(), True)
self.assertTrue(p in self.active_children()) self.assertIn(p, self.active_children())
self.assertEquals(q.get(), args[1:]) self.assertEquals(q.get(), args[1:])
self.assertEquals(q.get(), kwargs) self.assertEquals(q.get(), kwargs)
@ -183,7 +183,7 @@ class _TestProcess(BaseTestCase):
self.assertEquals(p.exitcode, 0) self.assertEquals(p.exitcode, 0)
self.assertEquals(p.is_alive(), False) self.assertEquals(p.is_alive(), False)
self.assertTrue(p not in self.active_children()) self.assertNotIn(p, self.active_children())
def _test_terminate(self): def _test_terminate(self):
time.sleep(1000) time.sleep(1000)
@ -197,7 +197,7 @@ class _TestProcess(BaseTestCase):
p.start() p.start()
self.assertEqual(p.is_alive(), True) self.assertEqual(p.is_alive(), True)
self.assertTrue(p in self.active_children()) self.assertIn(p, self.active_children())
self.assertEqual(p.exitcode, None) self.assertEqual(p.exitcode, None)
p.terminate() p.terminate()
@ -207,7 +207,7 @@ class _TestProcess(BaseTestCase):
self.assertTimingAlmostEqual(join.elapsed, 0.0) self.assertTimingAlmostEqual(join.elapsed, 0.0)
self.assertEqual(p.is_alive(), False) self.assertEqual(p.is_alive(), False)
self.assertTrue(p not in self.active_children()) self.assertNotIn(p, self.active_children())
p.join() p.join()
@ -226,13 +226,13 @@ class _TestProcess(BaseTestCase):
self.assertEqual(type(self.active_children()), list) self.assertEqual(type(self.active_children()), list)
p = self.Process(target=time.sleep, args=(DELTA,)) p = self.Process(target=time.sleep, args=(DELTA,))
self.assertTrue(p not in self.active_children()) self.assertNotIn(p, self.active_children())
p.start() p.start()
self.assertTrue(p in self.active_children()) self.assertIn(p, self.active_children())
p.join() p.join()
self.assertTrue(p not in self.active_children()) self.assertNotIn(p, self.active_children())
def _test_recursion(self, wconn, id): def _test_recursion(self, wconn, id):
from multiprocessing import forking from multiprocessing import forking

View file

@ -198,7 +198,7 @@ class StatAttributeTests(unittest.TestCase):
def trunc(x): return x def trunc(x): return x
self.assertEquals(trunc(getattr(result, attr)), self.assertEquals(trunc(getattr(result, attr)),
result[getattr(stat, name)]) result[getattr(stat, name)])
self.assertTrue(attr in members) self.assertIn(attr, members)
try: try:
result[200] result[200]

View file

@ -25,8 +25,8 @@ class TestTranforms(unittest.TestCase):
del x del x
asm = disassemble(unot) asm = disassemble(unot)
for elem in ('UNARY_NOT', 'POP_JUMP_IF_FALSE'): for elem in ('UNARY_NOT', 'POP_JUMP_IF_FALSE'):
self.assertTrue(elem not in asm) self.assertNotIn(elem, asm)
self.assertTrue('POP_JUMP_IF_TRUE' in asm) self.assertIn('POP_JUMP_IF_TRUE', asm)
def test_elim_inversion_of_is_or_in(self): def test_elim_inversion_of_is_or_in(self):
for line, elem in ( for line, elem in (
@ -36,7 +36,7 @@ class TestTranforms(unittest.TestCase):
('not a not in b', '(in)',), ('not a not in b', '(in)',),
): ):
asm = dis_single(line) asm = dis_single(line)
self.assertTrue(elem in asm) self.assertIn(elem, asm)
def test_none_as_constant(self): def test_none_as_constant(self):
# LOAD_GLOBAL None --> LOAD_CONST None # LOAD_GLOBAL None --> LOAD_CONST None
@ -45,14 +45,14 @@ class TestTranforms(unittest.TestCase):
return x return x
asm = disassemble(f) asm = disassemble(f)
for elem in ('LOAD_GLOBAL',): for elem in ('LOAD_GLOBAL',):
self.assertTrue(elem not in asm) self.assertNotIn(elem, asm)
for elem in ('LOAD_CONST', '(None)'): for elem in ('LOAD_CONST', '(None)'):
self.assertTrue(elem in asm) self.assertIn(elem, asm)
def f(): def f():
'Adding a docstring made this test fail in Py2.5.0' 'Adding a docstring made this test fail in Py2.5.0'
return None return None
self.assertTrue('LOAD_CONST' in disassemble(f)) self.assertIn('LOAD_CONST', disassemble(f))
self.assertTrue('LOAD_GLOBAL' not in disassemble(f)) self.assertNotIn('LOAD_GLOBAL', disassemble(f))
def test_while_one(self): def test_while_one(self):
# Skip over: LOAD_CONST trueconst POP_JUMP_IF_FALSE xx # Skip over: LOAD_CONST trueconst POP_JUMP_IF_FALSE xx
@ -62,9 +62,9 @@ class TestTranforms(unittest.TestCase):
return list return list
asm = disassemble(f) asm = disassemble(f)
for elem in ('LOAD_CONST', 'POP_JUMP_IF_FALSE'): for elem in ('LOAD_CONST', 'POP_JUMP_IF_FALSE'):
self.assertTrue(elem not in asm) self.assertNotIn(elem, asm)
for elem in ('JUMP_ABSOLUTE',): for elem in ('JUMP_ABSOLUTE',):
self.assertTrue(elem in asm) self.assertIn(elem, asm)
def test_pack_unpack(self): def test_pack_unpack(self):
for line, elem in ( for line, elem in (
@ -73,9 +73,9 @@ class TestTranforms(unittest.TestCase):
('a, b, c = a, b, c', 'ROT_THREE',), ('a, b, c = a, b, c', 'ROT_THREE',),
): ):
asm = dis_single(line) asm = dis_single(line)
self.assertTrue(elem in asm) self.assertIn(elem, asm)
self.assertTrue('BUILD_TUPLE' not in asm) self.assertNotIn('BUILD_TUPLE', asm)
self.assertTrue('UNPACK_TUPLE' not in asm) self.assertNotIn('UNPACK_TUPLE', asm)
def test_folding_of_tuples_of_constants(self): def test_folding_of_tuples_of_constants(self):
for line, elem in ( for line, elem in (
@ -86,8 +86,8 @@ class TestTranforms(unittest.TestCase):
('((1, 2), 3, 4)', '(((1, 2), 3, 4))'), ('((1, 2), 3, 4)', '(((1, 2), 3, 4))'),
): ):
asm = dis_single(line) asm = dis_single(line)
self.assertTrue(elem in asm) self.assertIn(elem, asm)
self.assertTrue('BUILD_TUPLE' not in asm) self.assertNotIn('BUILD_TUPLE', asm)
# Bug 1053819: Tuple of constants misidentified when presented with: # Bug 1053819: Tuple of constants misidentified when presented with:
# . . . opcode_with_arg 100 unary_opcode BUILD_TUPLE 1 . . . # . . . opcode_with_arg 100 unary_opcode BUILD_TUPLE 1 . . .
@ -125,17 +125,17 @@ class TestTranforms(unittest.TestCase):
('a = 13 | 7', '(15)'), # binary or ('a = 13 | 7', '(15)'), # binary or
): ):
asm = dis_single(line) asm = dis_single(line)
self.assertTrue(elem in asm, asm) self.assertIn(elem, asm, asm)
self.assertTrue('BINARY_' not in asm) self.assertNotIn('BINARY_', asm)
# Verify that unfoldables are skipped # Verify that unfoldables are skipped
asm = dis_single('a=2+"b"') asm = dis_single('a=2+"b"')
self.assertTrue('(2)' in asm) self.assertIn('(2)', asm)
self.assertTrue("('b')" in asm) self.assertIn("('b')", asm)
# Verify that large sequences do not result from folding # Verify that large sequences do not result from folding
asm = dis_single('a="x"*1000') asm = dis_single('a="x"*1000')
self.assertTrue('(1000)' in asm) self.assertIn('(1000)', asm)
def test_folding_of_unaryops_on_constants(self): def test_folding_of_unaryops_on_constants(self):
for line, elem in ( for line, elem in (
@ -144,8 +144,8 @@ class TestTranforms(unittest.TestCase):
('~-2', '(1)'), # unary invert ('~-2', '(1)'), # unary invert
): ):
asm = dis_single(line) asm = dis_single(line)
self.assertTrue(elem in asm, asm) self.assertIn(elem, asm, asm)
self.assertTrue('UNARY_' not in asm) self.assertNotIn('UNARY_', asm)
# Verify that unfoldables are skipped # Verify that unfoldables are skipped
for line, elem in ( for line, elem in (
@ -153,16 +153,16 @@ class TestTranforms(unittest.TestCase):
('~"abc"', "('abc')"), # unary invert ('~"abc"', "('abc')"), # unary invert
): ):
asm = dis_single(line) asm = dis_single(line)
self.assertTrue(elem in asm, asm) self.assertIn(elem, asm, asm)
self.assertTrue('UNARY_' in asm) self.assertIn('UNARY_', asm)
def test_elim_extra_return(self): def test_elim_extra_return(self):
# RETURN LOAD_CONST None RETURN --> RETURN # RETURN LOAD_CONST None RETURN --> RETURN
def f(x): def f(x):
return x return x
asm = disassemble(f) asm = disassemble(f)
self.assertTrue('LOAD_CONST' not in asm) self.assertNotIn('LOAD_CONST', asm)
self.assertTrue('(None)' not in asm) self.assertNotIn('(None)', asm)
self.assertEqual(asm.split().count('RETURN_VALUE'), 1) self.assertEqual(asm.split().count('RETURN_VALUE'), 1)
def test_elim_jump_to_return(self): def test_elim_jump_to_return(self):
@ -170,8 +170,8 @@ class TestTranforms(unittest.TestCase):
def f(cond, true_value, false_value): def f(cond, true_value, false_value):
return true_value if cond else false_value return true_value if cond else false_value
asm = disassemble(f) asm = disassemble(f)
self.assertTrue('JUMP_FORWARD' not in asm) self.assertNotIn('JUMP_FORWARD', asm)
self.assertTrue('JUMP_ABSOLUTE' not in asm) self.assertNotIn('JUMP_ABSOLUTE', asm)
self.assertEqual(asm.split().count('RETURN_VALUE'), 2) self.assertEqual(asm.split().count('RETURN_VALUE'), 2)
def test_elim_jump_after_return1(self): def test_elim_jump_after_return1(self):
@ -186,8 +186,8 @@ class TestTranforms(unittest.TestCase):
return 5 return 5
return 6 return 6
asm = disassemble(f) asm = disassemble(f)
self.assertTrue('JUMP_FORWARD' not in asm) self.assertNotIn('JUMP_FORWARD', asm)
self.assertTrue('JUMP_ABSOLUTE' not in asm) self.assertNotIn('JUMP_ABSOLUTE', asm)
self.assertEqual(asm.split().count('RETURN_VALUE'), 6) self.assertEqual(asm.split().count('RETURN_VALUE'), 6)
def test_elim_jump_after_return2(self): def test_elim_jump_after_return2(self):
@ -196,7 +196,7 @@ class TestTranforms(unittest.TestCase):
while 1: while 1:
if cond1: return 4 if cond1: return 4
asm = disassemble(f) asm = disassemble(f)
self.assertTrue('JUMP_FORWARD' not in asm) self.assertNotIn('JUMP_FORWARD', asm)
# There should be one jump for the while loop. # There should be one jump for the while loop.
self.assertEqual(asm.split().count('JUMP_ABSOLUTE'), 1) self.assertEqual(asm.split().count('JUMP_ABSOLUTE'), 1)
self.assertEqual(asm.split().count('RETURN_VALUE'), 2) self.assertEqual(asm.split().count('RETURN_VALUE'), 2)

View file

@ -41,7 +41,7 @@ class ExceptionClassTests(unittest.TestCase):
last_exc = getattr(__builtin__, superclass_name) last_exc = getattr(__builtin__, 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)
exc_set.discard(superclass_name) exc_set.discard(superclass_name)
superclasses = [] # Loop will insert base exception superclasses = [] # Loop will insert base exception
last_depth = 0 last_depth = 0
@ -75,7 +75,7 @@ class ExceptionClassTests(unittest.TestCase):
self.verify_instance_interface(exc()) self.verify_instance_interface(exc())
except TypeError: except TypeError:
pass pass
self.assertTrue(exc_name in exc_set) self.assertIn(exc_name, exc_set)
exc_set.discard(exc_name) exc_set.discard(exc_name)
last_exc = exc last_exc = exc
last_depth = depth last_depth = depth

View file

@ -246,7 +246,7 @@ if hasattr(poplib, 'POP3_SSL'):
self.client = poplib.POP3_SSL(self.server.host, self.server.port) self.client = poplib.POP3_SSL(self.server.host, self.server.port)
def test__all__(self): def test__all__(self):
self.assertTrue('POP3_SSL' in poplib.__all__) self.assertIn('POP3_SSL', poplib.__all__)
class TestTimeouts(TestCase): class TestTimeouts(TestCase):

View file

@ -264,7 +264,7 @@ class PosixTester(unittest.TestCase):
def test_lsdir(self): def test_lsdir(self):
if hasattr(posix, 'lsdir'): if hasattr(posix, 'lsdir'):
self.assertTrue(test_support.TESTFN in posix.lsdir(os.curdir)) self.assertIn(test_support.TESTFN, posix.lsdir(os.curdir))
def test_access(self): def test_access(self):
if hasattr(posix, 'access'): if hasattr(posix, 'access'):

View file

@ -57,7 +57,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_list_sort_output in res, self.assertIn(self.expected_list_sort_output, res,
"Profiling {0!r} didn't report list.sort:\n{1}".format(stmt, res)) "Profiling {0!r} didn't report list.sort:\n{1}".format(stmt, res))

View file

@ -43,8 +43,8 @@ class PwdTest(unittest.TestCase):
for e in entries: for e in entries:
if not e[0] or e[0] == '+': if not e[0] or e[0] == '+':
continue # skip NIS entries etc. continue # skip NIS entries etc.
self.assertTrue(pwd.getpwnam(e.pw_name) in entriesbyname[e.pw_name]) self.assertIn(pwd.getpwnam(e.pw_name), entriesbyname[e.pw_name])
self.assertTrue(pwd.getpwuid(e.pw_uid) in entriesbyuid[e.pw_uid]) self.assertIn(pwd.getpwuid(e.pw_uid), entriesbyuid[e.pw_uid])
def test_errors(self): def test_errors(self):
self.assertRaises(TypeError, pwd.getpwuid) self.assertRaises(TypeError, pwd.getpwuid)

View file

@ -350,7 +350,7 @@ class TestStdlibRemovals(unittest.TestCase):
try: try:
__import__(module_name, level=0) __import__(module_name, level=0)
except DeprecationWarning as exc: except DeprecationWarning as exc:
self.assertTrue(module_name in exc.args[0], self.assertIn(module_name, exc.args[0],
"%s warning didn't contain module name" "%s warning didn't contain module name"
% module_name) % module_name)
except ImportError: except ImportError:

View file

@ -298,7 +298,7 @@ class TestDescriptions(unittest.TestCase):
# Check that pydocfodder module can be described # Check that pydocfodder module can be described
from test import pydocfodder from test import pydocfodder
doc = pydoc.render_doc(pydocfodder) doc = pydoc.render_doc(pydocfodder)
self.assertTrue("pydocfodder" in doc) self.assertIn("pydocfodder", doc)
def test_classic_class(self): def test_classic_class(self):
class C: "Classic class" class C: "Classic class"
@ -306,7 +306,7 @@ class TestDescriptions(unittest.TestCase):
self.assertEqual(pydoc.describe(C), 'class C') self.assertEqual(pydoc.describe(C), 'class C')
self.assertEqual(pydoc.describe(c), 'instance of C') self.assertEqual(pydoc.describe(c), 'instance of C')
expected = 'instance of C in module %s' % __name__ expected = 'instance of C in module %s' % __name__
self.assertTrue(expected in pydoc.render_doc(c)) self.assertIn(expected, pydoc.render_doc(c))
def test_class(self): def test_class(self):
class C(object): "New-style class" class C(object): "New-style class"
@ -315,7 +315,7 @@ class TestDescriptions(unittest.TestCase):
self.assertEqual(pydoc.describe(C), 'class C') self.assertEqual(pydoc.describe(C), 'class C')
self.assertEqual(pydoc.describe(c), 'C') self.assertEqual(pydoc.describe(c), 'C')
expected = 'C in module %s object' % __name__ expected = 'C in module %s object' % __name__
self.assertTrue(expected in pydoc.render_doc(c)) self.assertIn(expected, pydoc.render_doc(c))
def test_main(): def test_main():

View file

@ -289,7 +289,7 @@ class SystemRandom_TestBasicOps(TestBasicOps):
n += n - 1 # check 1 below the next power of two n += n - 1 # check 1 below the next power of two
k = int(1.00001 + _log(n, 2)) k = int(1.00001 + _log(n, 2))
self.assertTrue(k in [numbits, numbits+1]) self.assertIn(k, [numbits, numbits+1])
self.assertTrue(2**k > n > 2**(k-2)) self.assertTrue(2**k > n > 2**(k-2))
n -= n >> 15 # check a little farther below the next power of two n -= n >> 15 # check a little farther below the next power of two
@ -445,7 +445,7 @@ class MersenneTwister_TestBasicOps(TestBasicOps):
n += n - 1 # check 1 below the next power of two n += n - 1 # check 1 below the next power of two
k = int(1.00001 + _log(n, 2)) k = int(1.00001 + _log(n, 2))
self.assertTrue(k in [numbits, numbits+1]) self.assertIn(k, [numbits, numbits+1])
self.assertTrue(2**k > n > 2**(k-2)) self.assertTrue(2**k > n > 2**(k-2))
n -= n >> 15 # check a little farther below the next power of two n -= n >> 15 # check a little farther below the next power of two

View file

@ -165,14 +165,14 @@ class RunModuleTest(unittest.TestCase):
try: try:
if verbose: print "Running from source:", mod_name if verbose: print "Running from source:", mod_name
d1 = run_module(mod_name) # Read from source d1 = run_module(mod_name) # Read from source
self.assertTrue("x" in d1) self.assertIn("x", d1)
self.assertTrue(d1["x"] == 1) self.assertTrue(d1["x"] == 1)
del d1 # Ensure __loader__ entry doesn't keep file open del d1 # Ensure __loader__ entry doesn't keep file open
__import__(mod_name) __import__(mod_name)
os.remove(mod_fname) os.remove(mod_fname)
if verbose: print "Running from compiled:", mod_name if verbose: print "Running from compiled:", mod_name
d2 = run_module(mod_name) # Read from bytecode d2 = run_module(mod_name) # Read from bytecode
self.assertTrue("x" in d2) self.assertIn("x", d2)
self.assertTrue(d2["x"] == 1) self.assertTrue(d2["x"] == 1)
del d2 # Ensure __loader__ entry doesn't keep file open del d2 # Ensure __loader__ entry doesn't keep file open
finally: finally:
@ -187,14 +187,14 @@ class RunModuleTest(unittest.TestCase):
try: try:
if verbose: print "Running from source:", pkg_name if verbose: print "Running from source:", pkg_name
d1 = run_module(pkg_name) # Read from source d1 = run_module(pkg_name) # Read from source
self.assertTrue("x" in d1) self.assertIn("x", d1)
self.assertTrue(d1["x"] == 1) self.assertTrue(d1["x"] == 1)
del d1 # Ensure __loader__ entry doesn't keep file open del d1 # Ensure __loader__ entry doesn't keep file open
__import__(mod_name) __import__(mod_name)
os.remove(mod_fname) os.remove(mod_fname)
if verbose: print "Running from compiled:", pkg_name if verbose: print "Running from compiled:", pkg_name
d2 = run_module(pkg_name) # Read from bytecode d2 = run_module(pkg_name) # Read from bytecode
self.assertTrue("x" in d2) self.assertIn("x", d2)
self.assertTrue(d2["x"] == 1) self.assertTrue(d2["x"] == 1)
del d2 # Ensure __loader__ entry doesn't keep file open del d2 # Ensure __loader__ entry doesn't keep file open
finally: finally:
@ -239,19 +239,19 @@ from ..uncle.cousin import nephew
pkg_name = mod_name.rpartition('.')[0] pkg_name = mod_name.rpartition('.')[0]
if verbose: print "Running from source:", mod_name if verbose: print "Running from source:", mod_name
d1 = run_module(mod_name, run_name=run_name) # Read from source d1 = run_module(mod_name, run_name=run_name) # Read from source
self.assertTrue("__package__" in d1) self.assertIn("__package__", d1)
self.assertTrue(d1["__package__"] == pkg_name) self.assertTrue(d1["__package__"] == pkg_name)
self.assertTrue("sibling" in d1) self.assertIn("sibling", d1)
self.assertTrue("nephew" in d1) self.assertIn("nephew", d1)
del d1 # Ensure __loader__ entry doesn't keep file open del d1 # Ensure __loader__ entry doesn't keep file open
__import__(mod_name) __import__(mod_name)
os.remove(mod_fname) os.remove(mod_fname)
if verbose: print "Running from compiled:", mod_name if verbose: print "Running from compiled:", mod_name
d2 = run_module(mod_name, run_name=run_name) # Read from bytecode d2 = run_module(mod_name, run_name=run_name) # Read from bytecode
self.assertTrue("__package__" in d2) self.assertIn("__package__", d2)
self.assertTrue(d2["__package__"] == pkg_name) self.assertTrue(d2["__package__"] == pkg_name)
self.assertTrue("sibling" in d2) self.assertIn("sibling", d2)
self.assertTrue("nephew" in d2) self.assertIn("nephew", d2)
del d2 # Ensure __loader__ entry doesn't keep file open del d2 # Ensure __loader__ entry doesn't keep file open
finally: finally:
self._del_pkg(pkg_dir, depth, mod_name) self._del_pkg(pkg_dir, depth, mod_name)

View file

@ -505,8 +505,8 @@ self.assertTrue(X.passed)
return C return C
varnames = f(1).z varnames = f(1).z
self.assertTrue("x" not in varnames) self.assertNotIn("x", varnames)
self.assertTrue("y" in varnames) self.assertIn("y", varnames)
def testLocalsClass_WithTrace(self): def testLocalsClass_WithTrace(self):
# Issue23728: after the trace function returns, the locals() # Issue23728: after the trace function returns, the locals()

View file

@ -64,7 +64,7 @@ class TestJointOps(unittest.TestCase):
self.assertEqual(c in self.s, c in self.d) self.assertEqual(c in self.s, c in self.d)
self.assertRaises(TypeError, self.s.__contains__, [[]]) self.assertRaises(TypeError, self.s.__contains__, [[]])
s = self.thetype([frozenset(self.letters)]) s = self.thetype([frozenset(self.letters)])
self.assertTrue(self.thetype(self.letters) in s) self.assertIn(self.thetype(self.letters), s)
def test_union(self): def test_union(self):
u = self.s.union(self.otherword) u = self.s.union(self.otherword)
@ -271,7 +271,7 @@ class TestJointOps(unittest.TestCase):
s=H() s=H()
f=set() f=set()
f.add(s) f.add(s)
self.assertTrue(s in f) self.assertIn(s, f)
f.remove(s) f.remove(s)
f.add(s) f.add(s)
f.discard(s) f.discard(s)
@ -371,7 +371,7 @@ class TestSet(TestJointOps):
def test_add(self): def test_add(self):
self.s.add('Q') self.s.add('Q')
self.assertTrue('Q' in self.s) self.assertIn('Q', self.s)
dup = self.s.copy() dup = self.s.copy()
self.s.add('Q') self.s.add('Q')
self.assertEqual(self.s, dup) self.assertEqual(self.s, dup)
@ -379,13 +379,13 @@ class TestSet(TestJointOps):
def test_remove(self): def test_remove(self):
self.s.remove('a') self.s.remove('a')
self.assertTrue('a' not in self.s) self.assertNotIn('a', self.s)
self.assertRaises(KeyError, self.s.remove, 'Q') self.assertRaises(KeyError, self.s.remove, 'Q')
self.assertRaises(TypeError, self.s.remove, []) self.assertRaises(TypeError, self.s.remove, [])
s = self.thetype([frozenset(self.word)]) s = self.thetype([frozenset(self.word)])
self.assertTrue(self.thetype(self.word) in s) self.assertIn(self.thetype(self.word), s)
s.remove(self.thetype(self.word)) s.remove(self.thetype(self.word))
self.assertTrue(self.thetype(self.word) not in s) self.assertNotIn(self.thetype(self.word), s)
self.assertRaises(KeyError, self.s.remove, self.thetype(self.word)) self.assertRaises(KeyError, self.s.remove, self.thetype(self.word))
def test_remove_keyerror_unpacking(self): def test_remove_keyerror_unpacking(self):
@ -412,26 +412,26 @@ class TestSet(TestJointOps):
def test_discard(self): def test_discard(self):
self.s.discard('a') self.s.discard('a')
self.assertTrue('a' not in self.s) self.assertNotIn('a', self.s)
self.s.discard('Q') self.s.discard('Q')
self.assertRaises(TypeError, self.s.discard, []) self.assertRaises(TypeError, self.s.discard, [])
s = self.thetype([frozenset(self.word)]) s = self.thetype([frozenset(self.word)])
self.assertTrue(self.thetype(self.word) in s) self.assertIn(self.thetype(self.word), s)
s.discard(self.thetype(self.word)) s.discard(self.thetype(self.word))
self.assertTrue(self.thetype(self.word) not in s) self.assertNotIn(self.thetype(self.word), s)
s.discard(self.thetype(self.word)) s.discard(self.thetype(self.word))
def test_pop(self): def test_pop(self):
for i in xrange(len(self.s)): for i in xrange(len(self.s)):
elem = self.s.pop() elem = self.s.pop()
self.assertTrue(elem not in self.s) self.assertNotIn(elem, self.s)
self.assertRaises(KeyError, self.s.pop) self.assertRaises(KeyError, self.s.pop)
def test_update(self): def test_update(self):
retval = self.s.update(self.otherword) retval = self.s.update(self.otherword)
self.assertEqual(retval, None) self.assertEqual(retval, None)
for c in (self.word + self.otherword): for c in (self.word + self.otherword):
self.assertTrue(c in self.s) self.assertIn(c, self.s)
self.assertRaises(PassThru, self.s.update, check_pass_thru()) self.assertRaises(PassThru, self.s.update, check_pass_thru())
self.assertRaises(TypeError, self.s.update, [[]]) self.assertRaises(TypeError, self.s.update, [[]])
for p, q in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')): for p, q in (('cdc', 'abcd'), ('efgfe', 'abcefg'), ('ccb', 'abc'), ('ef', 'abcef')):
@ -449,16 +449,16 @@ class TestSet(TestJointOps):
def test_ior(self): def test_ior(self):
self.s |= set(self.otherword) self.s |= set(self.otherword)
for c in (self.word + self.otherword): for c in (self.word + self.otherword):
self.assertTrue(c in self.s) self.assertIn(c, self.s)
def test_intersection_update(self): def test_intersection_update(self):
retval = self.s.intersection_update(self.otherword) retval = self.s.intersection_update(self.otherword)
self.assertEqual(retval, None) self.assertEqual(retval, None)
for c in (self.word + self.otherword): for c in (self.word + self.otherword):
if c in self.otherword and c in self.word: if c in self.otherword and c in self.word:
self.assertTrue(c in self.s) self.assertIn(c, self.s)
else: else:
self.assertTrue(c not in self.s) self.assertNotIn(c, self.s)
self.assertRaises(PassThru, self.s.intersection_update, check_pass_thru()) self.assertRaises(PassThru, self.s.intersection_update, check_pass_thru())
self.assertRaises(TypeError, self.s.intersection_update, [[]]) self.assertRaises(TypeError, self.s.intersection_update, [[]])
for p, q in (('cdc', 'c'), ('efgfe', ''), ('ccb', 'bc'), ('ef', '')): for p, q in (('cdc', 'c'), ('efgfe', ''), ('ccb', 'bc'), ('ef', '')):
@ -476,18 +476,18 @@ class TestSet(TestJointOps):
self.s &= set(self.otherword) self.s &= set(self.otherword)
for c in (self.word + self.otherword): for c in (self.word + self.otherword):
if c in self.otherword and c in self.word: if c in self.otherword and c in self.word:
self.assertTrue(c in self.s) self.assertIn(c, self.s)
else: else:
self.assertTrue(c not in self.s) self.assertNotIn(c, self.s)
def test_difference_update(self): def test_difference_update(self):
retval = self.s.difference_update(self.otherword) retval = self.s.difference_update(self.otherword)
self.assertEqual(retval, None) self.assertEqual(retval, None)
for c in (self.word + self.otherword): for c in (self.word + self.otherword):
if c in self.word and c not in self.otherword: if c in self.word and c not in self.otherword:
self.assertTrue(c in self.s) self.assertIn(c, self.s)
else: else:
self.assertTrue(c not in self.s) self.assertNotIn(c, self.s)
self.assertRaises(PassThru, self.s.difference_update, check_pass_thru()) self.assertRaises(PassThru, self.s.difference_update, check_pass_thru())
self.assertRaises(TypeError, self.s.difference_update, [[]]) self.assertRaises(TypeError, self.s.difference_update, [[]])
self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]]) self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]])
@ -513,18 +513,18 @@ class TestSet(TestJointOps):
self.s -= set(self.otherword) self.s -= set(self.otherword)
for c in (self.word + self.otherword): for c in (self.word + self.otherword):
if c in self.word and c not in self.otherword: if c in self.word and c not in self.otherword:
self.assertTrue(c in self.s) self.assertIn(c, self.s)
else: else:
self.assertTrue(c not in self.s) self.assertNotIn(c, self.s)
def test_symmetric_difference_update(self): def test_symmetric_difference_update(self):
retval = self.s.symmetric_difference_update(self.otherword) retval = self.s.symmetric_difference_update(self.otherword)
self.assertEqual(retval, None) self.assertEqual(retval, None)
for c in (self.word + self.otherword): for c in (self.word + self.otherword):
if (c in self.word) ^ (c in self.otherword): if (c in self.word) ^ (c in self.otherword):
self.assertTrue(c in self.s) self.assertIn(c, self.s)
else: else:
self.assertTrue(c not in self.s) self.assertNotIn(c, self.s)
self.assertRaises(PassThru, self.s.symmetric_difference_update, check_pass_thru()) self.assertRaises(PassThru, self.s.symmetric_difference_update, check_pass_thru())
self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]]) self.assertRaises(TypeError, self.s.symmetric_difference_update, [[]])
for p, q in (('cdc', 'abd'), ('efgfe', 'abcefg'), ('ccb', 'a'), ('ef', 'abcef')): for p, q in (('cdc', 'abd'), ('efgfe', 'abcefg'), ('ccb', 'a'), ('ef', 'abcef')):
@ -537,9 +537,9 @@ class TestSet(TestJointOps):
self.s ^= set(self.otherword) self.s ^= set(self.otherword)
for c in (self.word + self.otherword): for c in (self.word + self.otherword):
if (c in self.word) ^ (c in self.otherword): if (c in self.word) ^ (c in self.otherword):
self.assertTrue(c in self.s) self.assertIn(c, self.s)
else: else:
self.assertTrue(c not in self.s) self.assertNotIn(c, self.s)
def test_inplace_on_self(self): def test_inplace_on_self(self):
t = self.s.copy() t = self.s.copy()
@ -767,7 +767,7 @@ class TestBasicOps(unittest.TestCase):
def test_iteration(self): def test_iteration(self):
for v in self.set: for v in self.set:
self.assertTrue(v in self.values) self.assertIn(v, self.values)
setiter = iter(self.set) setiter = iter(self.set)
# note: __length_hint__ is an internal undocumented API, # note: __length_hint__ is an internal undocumented API,
# don't rely on it in your own programs # don't rely on it in your own programs
@ -802,10 +802,10 @@ class TestBasicOpsSingleton(TestBasicOps):
self.repr = "set([3])" self.repr = "set([3])"
def test_in(self): def test_in(self):
self.assertTrue(3 in self.set) self.assertIn(3, self.set)
def test_not_in(self): def test_not_in(self):
self.assertTrue(2 not in self.set) self.assertNotIn(2, self.set)
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -819,10 +819,10 @@ class TestBasicOpsTuple(TestBasicOps):
self.repr = "set([(0, 'zero')])" self.repr = "set([(0, 'zero')])"
def test_in(self): def test_in(self):
self.assertTrue((0, "zero") in self.set) self.assertIn((0, "zero"), self.set)
def test_not_in(self): def test_not_in(self):
self.assertTrue(9 not in self.set) self.assertNotIn(9, self.set)
#------------------------------------------------------------------------------ #------------------------------------------------------------------------------
@ -1114,7 +1114,7 @@ class TestMutate(unittest.TestCase):
popped[self.set.pop()] = None popped[self.set.pop()] = None
self.assertEqual(len(popped), len(self.values)) self.assertEqual(len(popped), len(self.values))
for v in self.values: for v in self.values:
self.assertTrue(v in popped) self.assertIn(v, popped)
def test_update_empty_tuple(self): def test_update_empty_tuple(self):
self.set.update(()) self.set.update(())
@ -1688,7 +1688,7 @@ class TestGraphs(unittest.TestCase):
edge = vertex # Cuboctahedron vertices are edges in Cube edge = vertex # Cuboctahedron vertices are edges in Cube
self.assertEqual(len(edge), 2) # Two cube vertices define an edge self.assertEqual(len(edge), 2) # Two cube vertices define an edge
for cubevert in edge: for cubevert in edge:
self.assertTrue(cubevert in g) self.assertIn(cubevert, g)
#============================================================================== #==============================================================================

View file

@ -76,7 +76,7 @@ class TestBasicOps(unittest.TestCase):
def test_iteration(self): def test_iteration(self):
for v in self.set: for v in self.set:
self.assertTrue(v in self.values) self.assertIn(v, self.values)
def test_pickling(self): def test_pickling(self):
p = pickle.dumps(self.set) p = pickle.dumps(self.set)
@ -406,7 +406,7 @@ class TestMutate(unittest.TestCase):
popped[self.set.pop()] = None popped[self.set.pop()] = None
self.assertEqual(len(popped), len(self.values)) self.assertEqual(len(popped), len(self.values))
for v in self.values: for v in self.values:
self.assertTrue(v in popped) self.assertIn(v, popped)
def test_update_empty_tuple(self): def test_update_empty_tuple(self):
self.set.union_update(()) self.set.union_update(())

View file

@ -68,13 +68,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))
@ -279,7 +279,7 @@ class ImportSideEffectTests(unittest.TestCase):
site.removeduppaths() site.removeduppaths()
seen_paths = set() seen_paths = set()
for path in sys.path: for path in sys.path:
self.assertTrue(path not in seen_paths) self.assertNotIn(path, seen_paths)
seen_paths.add(path) seen_paths.add(path)
def test_add_build_dir(self): def test_add_build_dir(self):

View file

@ -491,7 +491,7 @@ class GeneralModuleTests(unittest.TestCase):
# it reasonable to get the host's addr in addition to 0.0.0.0. # 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. # At least for eCos. This is required for the S/390 to pass.
my_ip_addr = socket.gethostbyname(socket.gethostname()) my_ip_addr = socket.gethostbyname(socket.gethostname())
self.assertTrue(name[0] in ("0.0.0.0", my_ip_addr), '%s invalid' % name[0]) self.assertIn(name[0], ("0.0.0.0", my_ip_addr), '%s invalid' % name[0])
self.assertEqual(name[1], port) self.assertEqual(name[1], port)
def testGetSockOpt(self): def testGetSockOpt(self):

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

@ -50,8 +50,8 @@ class StructSeqTest(unittest.TestCase):
def test_contains(self): def test_contains(self):
t1 = time.gmtime() t1 = time.gmtime()
for item in t1: for item in t1:
self.assertTrue(item in t1) self.assertIn(item, t1)
self.assertTrue(-42 not in t1) self.assertNotIn(-42, t1)
def test_hash(self): def test_hash(self):
t1 = time.gmtime() t1 = time.gmtime()

View file

@ -76,7 +76,7 @@ class ProcessTestCase(unittest.TestCase):
# check_output() function with zero return code # check_output() function with zero return code
output = subprocess.check_output( output = subprocess.check_output(
[sys.executable, "-c", "print 'BDFL'"]) [sys.executable, "-c", "print 'BDFL'"])
self.assertTrue('BDFL' in output) self.assertIn('BDFL', output)
def test_check_output_nonzero(self): def test_check_output_nonzero(self):
# check_call() function with non-zero return code # check_call() function with non-zero return code
@ -93,7 +93,7 @@ class ProcessTestCase(unittest.TestCase):
output = subprocess.check_output( output = subprocess.check_output(
[sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"], [sys.executable, "-c", "import sys; sys.stderr.write('BDFL')"],
stderr=subprocess.STDOUT) stderr=subprocess.STDOUT)
self.assertTrue('BDFL' in output) self.assertIn('BDFL', output)
def test_check_output_stdout_arg(self): def test_check_output_stdout_arg(self):
# check_output() function stderr redirected to stdout # check_output() function stderr redirected to stdout
@ -102,7 +102,7 @@ class ProcessTestCase(unittest.TestCase):
[sys.executable, "-c", "print 'will not be run'"], [sys.executable, "-c", "print 'will not be run'"],
stdout=sys.stdout) stdout=sys.stdout)
except ValueError, e: except ValueError, e:
self.assertTrue('stdout' in e.args[0]) self.assertIn('stdout', e.args[0])
else: else:
self.fail("Expected ValueError when stdout arg supplied.") self.fail("Expected ValueError when stdout arg supplied.")

View file

@ -293,8 +293,8 @@ class SysModuleTest(unittest.TestCase):
d = sys._current_frames() d = sys._current_frames()
main_id = thread.get_ident() main_id = thread.get_ident()
self.assertTrue(main_id in d) self.assertIn(main_id, d)
self.assertTrue(thread_id in d) self.assertIn(thread_id, d)
# Verify that the captured main-thread frame is _this_ frame. # Verify that the captured main-thread frame is _this_ frame.
frame = d.pop(main_id) frame = d.pop(main_id)
@ -316,7 +316,7 @@ class SysModuleTest(unittest.TestCase):
# And the next record must be for g456(). # And the next record must be for g456().
filename, lineno, funcname, sourceline = stack[i+1] filename, lineno, funcname, sourceline = stack[i+1]
self.assertEqual(funcname, "g456") self.assertEqual(funcname, "g456")
self.assertTrue(sourceline in ["leave_g.wait()", "entered_g.set()"]) self.assertIn(sourceline, ["leave_g.wait()", "entered_g.set()"])
# Reap the spawned thread. # Reap the spawned thread.
leave_g.set() leave_g.set()
@ -328,13 +328,13 @@ class SysModuleTest(unittest.TestCase):
# "thread id" 0. # "thread id" 0.
d = sys._current_frames() d = sys._current_frames()
self.assertEqual(len(d), 1) self.assertEqual(len(d), 1)
self.assertTrue(0 in d) self.assertIn(0, d)
self.assertTrue(d[0] is sys._getframe()) self.assertTrue(d[0] is sys._getframe())
def test_attributes(self): def test_attributes(self):
self.assertTrue(isinstance(sys.api_version, int)) self.assertTrue(isinstance(sys.api_version, int))
self.assertTrue(isinstance(sys.argv, list)) self.assertTrue(isinstance(sys.argv, list))
self.assertTrue(sys.byteorder in ("little", "big")) self.assertIn(sys.byteorder, ("little", "big"))
self.assertTrue(isinstance(sys.builtin_module_names, tuple)) self.assertTrue(isinstance(sys.builtin_module_names, tuple))
self.assertTrue(isinstance(sys.copyright, basestring)) self.assertTrue(isinstance(sys.copyright, basestring))
self.assertTrue(isinstance(sys.exec_prefix, basestring)) self.assertTrue(isinstance(sys.exec_prefix, basestring))
@ -359,13 +359,12 @@ class SysModuleTest(unittest.TestCase):
self.assertTrue(isinstance(vi[0], int)) self.assertTrue(isinstance(vi[0], int))
self.assertTrue(isinstance(vi[1], int)) self.assertTrue(isinstance(vi[1], int))
self.assertTrue(isinstance(vi[2], int)) self.assertTrue(isinstance(vi[2], int))
self.assertTrue(vi[3] in ("alpha", "beta", "candidate", "final")) self.assertIn(vi[3], ("alpha", "beta", "candidate", "final"))
self.assertTrue(isinstance(vi[4], int)) self.assertTrue(isinstance(vi[4], int))
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)
@ -374,7 +373,7 @@ class SysModuleTest(unittest.TestCase):
self.assertEqual(vi[4], vi.serial) self.assertEqual(vi[4], vi.serial)
self.assertTrue(vi > (1,0,0)) self.assertTrue(vi > (1,0,0))
self.assertIsInstance(sys.float_repr_style, str) self.assertIsInstance(sys.float_repr_style, str)
self.assertTrue(sys.float_repr_style in ('short', 'legacy')) self.assertIn(sys.float_repr_style, ('short', 'legacy'))
def test_43581(self): def test_43581(self):
# Can't use sys.stdout, as this is a cStringIO object when # Can't use sys.stdout, as this is a cStringIO object when

View file

@ -486,7 +486,7 @@ class MemberReadTest(ReadTest):
def test_find_ustar_longname(self): def test_find_ustar_longname(self):
name = "ustar/" + "12345/" * 39 + "1234567/longname" name = "ustar/" + "12345/" * 39 + "1234567/longname"
self.assertTrue(name in self.tar.getnames()) self.assertIn(name, self.tar.getnames())
def test_find_regtype_oldv7(self): def test_find_regtype_oldv7(self):
tarinfo = self.tar.getmember("misc/regtype-old-v7") tarinfo = self.tar.getmember("misc/regtype-old-v7")

View file

@ -321,7 +321,7 @@ class OptionTests(TestCase):
txt = telnet.read_all() txt = telnet.read_all()
cmd = nego.seen cmd = nego.seen
self.assertTrue(len(cmd) > 0) # we expect at least one command self.assertTrue(len(cmd) > 0) # we expect at least one command
self.assertTrue(cmd[0] in self.cmds) self.assertIn(cmd[0], self.cmds)
self.assertEqual(cmd[1], tl.NOOPT) self.assertEqual(cmd[1], tl.NOOPT)
self.assertEqual(len(''.join(data[:-1])), len(txt + cmd)) self.assertEqual(len(''.join(data[:-1])), len(txt + cmd))
nego.sb_getter = None # break the nego => telnet cycle nego.sb_getter = None # break the nego => telnet cycle

View file

@ -113,7 +113,7 @@ class test__RandomNameSequence(TC):
for i in xrange(TEST_FILES): for i in xrange(TEST_FILES):
s = r.next() s = r.next()
self.nameCheck(s, '', '', '') self.nameCheck(s, '', '', '')
self.assertFalse(s in dict) self.assertNotIn(s, dict)
dict[s] = 1 dict[s] = 1
def test_supports_iter(self): def test_supports_iter(self):
@ -160,14 +160,14 @@ class test__candidate_tempdir_list(TC):
for envname in 'TMPDIR', 'TEMP', 'TMP': for envname in 'TMPDIR', 'TEMP', 'TMP':
dirname = os.getenv(envname) dirname = os.getenv(envname)
if not dirname: raise ValueError if not dirname: raise ValueError
self.assertTrue(dirname in cand) self.assertIn(dirname, cand)
try: try:
dirname = os.getcwd() dirname = os.getcwd()
except (AttributeError, os.error): except (AttributeError, os.error):
dirname = os.curdir dirname = os.curdir
self.assertTrue(dirname in cand) self.assertIn(dirname, cand)
# Not practical to try to verify the presence of OS-specific # Not practical to try to verify the presence of OS-specific
# paths in this list. # paths in this list.

View file

@ -153,7 +153,7 @@ class ThreadTests(BaseTestCase):
tid = thread.start_new_thread(f, (mutex,)) tid = thread.start_new_thread(f, (mutex,))
# Wait for the thread to finish. # Wait for the thread to finish.
mutex.acquire() mutex.acquire()
self.assertTrue(tid in threading._active) self.assertIn(tid, threading._active)
self.assertTrue(isinstance(threading._active[tid], self.assertTrue(isinstance(threading._active[tid],
threading._DummyThread)) threading._DummyThread))
del threading._active[tid] del threading._active[tid]
@ -356,7 +356,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.setcheckinterval(old_interval) sys.setcheckinterval(old_interval)

View file

@ -40,7 +40,7 @@ class ThreadingLocalTest(unittest.TestCase):
local.someothervar = None local.someothervar = None
gc.collect() gc.collect()
deadlist = [weak for weak in weaklist if weak() is None] deadlist = [weak for weak in weaklist if weak() is None]
self.assertTrue(len(deadlist) in (n-1, n), (n, len(deadlist))) self.assertIn(len(deadlist), (n-1, n), (n, len(deadlist)))
def test_derived(self): def test_derived(self):
# Issue 3088: if there is a threads switch inside the __init__ # Issue 3088: if there is a threads switch inside the __init__

View file

@ -39,12 +39,12 @@ class TracebackCases(unittest.TestCase):
SyntaxError) SyntaxError)
self.assertTrue(len(err) == 4) self.assertTrue(len(err) == 4)
self.assertTrue(err[1].strip() == "return x!") self.assertTrue(err[1].strip() == "return x!")
self.assertTrue("^" in err[2]) # third line has caret self.assertIn("^", err[2]) # third line has caret
self.assertTrue(err[1].find("!") == err[2].find("^")) # in the right place self.assertTrue(err[1].find("!") == err[2].find("^")) # in the right place
err = self.get_exception_format(self.syntax_error_with_caret_2, err = self.get_exception_format(self.syntax_error_with_caret_2,
SyntaxError) SyntaxError)
self.assertTrue("^" in err[2]) # third line has caret self.assertIn("^", err[2]) # third line has caret
self.assertTrue(err[2].count('\n') == 1) # and no additional newline self.assertTrue(err[2].count('\n') == 1) # and no additional newline
self.assertTrue(err[1].find("+") == err[2].find("^")) # in the right place self.assertTrue(err[1].find("+") == err[2].find("^")) # in the right place
@ -62,7 +62,7 @@ class TracebackCases(unittest.TestCase):
IndentationError) IndentationError)
self.assertTrue(len(err) == 4) self.assertTrue(len(err) == 4)
self.assertTrue(err[1].strip() == "print 2") self.assertTrue(err[1].strip() == "print 2")
self.assertTrue("^" in err[2]) self.assertIn("^", err[2])
self.assertTrue(err[1].find("2") == err[2].find("^")) self.assertTrue(err[1].find("2") == err[2].find("^"))
def test_bug737473(self): def test_bug737473(self):

View file

@ -612,13 +612,13 @@ class TypesTests(unittest.TestCase):
result = f.__format__(fmt) result = f.__format__(fmt)
self.assertEqual(len(result), 98) self.assertEqual(len(result), 98)
self.assertEqual(result[-7], '.') self.assertEqual(result[-7], '.')
self.assertTrue(result[:12] in ('112340000000', '112339999999')) self.assertIn(result[:12], ('112340000000', '112339999999'))
f = 1.1234e200 f = 1.1234e200
for fmt in 'f', 'F': for fmt in 'f', 'F':
result = f.__format__(fmt) result = f.__format__(fmt)
self.assertEqual(len(result), 208) self.assertEqual(len(result), 208)
self.assertEqual(result[-7], '.') self.assertEqual(result[-7], '.')
self.assertTrue(result[:12] in ('112340000000', '112339999999')) self.assertIn(result[:12], ('112340000000', '112339999999'))
test( 1.0, 'e', '1.000000e+00') test( 1.0, 'e', '1.000000e+00')

View file

@ -316,30 +316,30 @@ class UnicodeTest(
def test_contains(self): def test_contains(self):
# Testing Unicode contains method # Testing Unicode contains method
self.assertTrue('a' in u'abdb') self.assertIn('a', u'abdb')
self.assertTrue('a' in u'bdab') self.assertIn('a', u'bdab')
self.assertTrue('a' in u'bdaba') self.assertIn('a', u'bdaba')
self.assertTrue('a' in u'bdba') self.assertIn('a', u'bdba')
self.assertTrue('a' in u'bdba') self.assertIn('a', u'bdba')
self.assertTrue(u'a' in u'bdba') self.assertIn(u'a', u'bdba')
self.assertTrue(u'a' not in u'bdb') self.assertNotIn(u'a', u'bdb')
self.assertTrue(u'a' not in 'bdb') self.assertNotIn(u'a', 'bdb')
self.assertTrue(u'a' in 'bdba') self.assertIn(u'a', 'bdba')
self.assertTrue(u'a' in ('a',1,None)) self.assertIn(u'a', ('a',1,None))
self.assertTrue(u'a' in (1,None,'a')) self.assertIn(u'a', (1,None,'a'))
self.assertTrue(u'a' in (1,None,u'a')) self.assertIn(u'a', (1,None,u'a'))
self.assertTrue('a' in ('a',1,None)) self.assertIn('a', ('a',1,None))
self.assertTrue('a' in (1,None,'a')) self.assertIn('a', (1,None,'a'))
self.assertTrue('a' in (1,None,u'a')) self.assertIn('a', (1,None,u'a'))
self.assertTrue('a' not in ('x',1,u'y')) self.assertNotIn('a', ('x',1,u'y'))
self.assertTrue('a' not in ('x',1,None)) self.assertNotIn('a', ('x',1,None))
self.assertTrue(u'abcd' not in u'abcxxxx') self.assertNotIn(u'abcd', u'abcxxxx')
self.assertTrue(u'ab' in u'abcd') self.assertIn(u'ab', u'abcd')
self.assertTrue('ab' in u'abc') self.assertIn('ab', u'abc')
self.assertTrue(u'ab' in 'abc') self.assertIn(u'ab', 'abc')
self.assertTrue(u'ab' in (1,None,u'ab')) self.assertIn(u'ab', (1,None,u'ab'))
self.assertTrue(u'' in u'abc') self.assertIn(u'', u'abc')
self.assertTrue('' in u'abc') self.assertIn('', u'abc')
# If the following fails either # If the following fails either
# the contains operator does not propagate UnicodeErrors or # the contains operator does not propagate UnicodeErrors or
@ -347,33 +347,33 @@ class UnicodeTest(
self.assertRaises(UnicodeDecodeError, 'g\xe2teau'.__contains__, u'\xe2') self.assertRaises(UnicodeDecodeError, 'g\xe2teau'.__contains__, u'\xe2')
self.assertRaises(UnicodeDecodeError, u'g\xe2teau'.__contains__, '\xe2') self.assertRaises(UnicodeDecodeError, u'g\xe2teau'.__contains__, '\xe2')
self.assertTrue(u'' in '') self.assertIn(u'', '')
self.assertTrue('' in u'') self.assertIn('', u'')
self.assertTrue(u'' in u'') self.assertIn(u'', u'')
self.assertTrue(u'' in 'abc') self.assertIn(u'', 'abc')
self.assertTrue('' in u'abc') self.assertIn('', u'abc')
self.assertTrue(u'' in u'abc') self.assertIn(u'', u'abc')
self.assertTrue(u'\0' not in 'abc') self.assertNotIn(u'\0', 'abc')
self.assertTrue('\0' not in u'abc') self.assertNotIn('\0', u'abc')
self.assertTrue(u'\0' not in u'abc') self.assertNotIn(u'\0', u'abc')
self.assertTrue(u'\0' in '\0abc') self.assertIn(u'\0', '\0abc')
self.assertTrue('\0' in u'\0abc') self.assertIn('\0', u'\0abc')
self.assertTrue(u'\0' in u'\0abc') self.assertIn(u'\0', u'\0abc')
self.assertTrue(u'\0' in 'abc\0') self.assertIn(u'\0', 'abc\0')
self.assertTrue('\0' in u'abc\0') self.assertIn('\0', u'abc\0')
self.assertTrue(u'\0' in u'abc\0') self.assertIn(u'\0', u'abc\0')
self.assertTrue(u'a' in '\0abc') self.assertIn(u'a', '\0abc')
self.assertTrue('a' in u'\0abc') self.assertIn('a', u'\0abc')
self.assertTrue(u'a' in u'\0abc') self.assertIn(u'a', u'\0abc')
self.assertTrue(u'asdf' in 'asdf') self.assertIn(u'asdf', 'asdf')
self.assertTrue('asdf' in u'asdf') self.assertIn('asdf', u'asdf')
self.assertTrue(u'asdf' in u'asdf') self.assertIn(u'asdf', u'asdf')
self.assertTrue(u'asdf' not in 'asd') self.assertNotIn(u'asdf', 'asd')
self.assertTrue('asdf' not in u'asd') self.assertNotIn('asdf', u'asd')
self.assertTrue(u'asdf' not in u'asd') self.assertNotIn(u'asdf', u'asd')
self.assertTrue(u'asdf' not in '') self.assertNotIn(u'asdf', '')
self.assertTrue('asdf' not in u'') self.assertNotIn('asdf', u'')
self.assertTrue(u'asdf' not in u'') self.assertNotIn(u'asdf', u'')
self.assertRaises(TypeError, u"abc".__contains__) self.assertRaises(TypeError, u"abc".__contains__)
self.assertRaises(TypeError, u"abc".__contains__, object()) self.assertRaises(TypeError, u"abc".__contains__, object())

View file

@ -71,7 +71,7 @@ class TestUnicodeFiles(unittest.TestCase):
base = unicodedata.normalize("NFD", base) base = unicodedata.normalize("NFD", base)
file_list = [unicodedata.normalize("NFD", f) for f in file_list] file_list = [unicodedata.normalize("NFD", f) for f in file_list]
self.assertTrue(base in file_list) self.assertIn(base, file_list)
# Do as many "equivalancy' tests as we can - ie, check that although we # 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. # have different types for the filename, they refer to the same file.

View file

@ -218,7 +218,7 @@ class UnicodeMiscTest(UnicodeDatabaseTest):
self.assertEqual(popen.returncode, 1) self.assertEqual(popen.returncode, 1)
error = "SyntaxError: (unicode error) \N escapes not supported " \ error = "SyntaxError: (unicode error) \N escapes not supported " \
"(can't load unicodedata module)" "(can't load unicodedata module)"
self.assertTrue(error in popen.stderr.read()) self.assertIn(error, popen.stderr.read())
def test_decimal_numeric_consistent(self): def test_decimal_numeric_consistent(self):
# Test that decimal and numeric are consistent, # Test that decimal and numeric are consistent,

View file

@ -636,7 +636,7 @@ class Test_TestLoader(TestCase):
self.assertEqual(list(suite), []) self.assertEqual(list(suite), [])
# audioop should now be loaded, thanks to loadTestsFromName() # audioop should now be loaded, thanks to loadTestsFromName()
self.assertTrue(module_name in sys.modules) self.assertIn(module_name, sys.modules)
finally: finally:
if module_name in sys.modules: if module_name in sys.modules:
del sys.modules[module_name] del sys.modules[module_name]
@ -1024,7 +1024,7 @@ class Test_TestLoader(TestCase):
self.assertEqual(list(suite), [unittest.TestSuite()]) self.assertEqual(list(suite), [unittest.TestSuite()])
# audioop should now be loaded, thanks to loadTestsFromName() # audioop should now be loaded, thanks to loadTestsFromName()
self.assertTrue(module_name in sys.modules) self.assertIn(module_name, sys.modules)
finally: finally:
if module_name in sys.modules: if module_name in sys.modules:
del sys.modules[module_name] del sys.modules[module_name]
@ -3056,7 +3056,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 e, str(e)) self.assertIn("KeyError not raised", e)
else: else:
self.fail("assertRaises() didn't fail") self.fail("assertRaises() didn't fail")
try: try:
@ -3073,7 +3073,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 e, str(e)) self.assertIn("KeyError not raised", e)
else: else:
self.fail("assertRaises() didn't fail") self.fail("assertRaises() didn't fail")
try: try:

View file

@ -487,7 +487,7 @@ class urlencode_Tests(unittest.TestCase):
expect_somewhere = ["1st=1", "2nd=2", "3rd=3"] expect_somewhere = ["1st=1", "2nd=2", "3rd=3"]
result = urllib.urlencode(given) result = urllib.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,
@ -534,8 +534,7 @@ class urlencode_Tests(unittest.TestCase):
result = urllib.urlencode(given, True) result = urllib.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

@ -779,8 +779,8 @@ class HandlerTests(unittest.TestCase):
r = MockResponse(200, "OK", {}, "") r = MockResponse(200, "OK", {}, "")
newreq = h.do_request_(req) newreq = h.do_request_(req)
if data is None: # GET if data is None: # GET
self.assertTrue("Content-length" not in req.unredirected_hdrs) self.assertNotIn("Content-length", req.unredirected_hdrs)
self.assertTrue("Content-type" not in req.unredirected_hdrs) self.assertNotIn("Content-type", req.unredirected_hdrs)
else: # POST else: # POST
self.assertEqual(req.unredirected_hdrs["Content-length"], "0") self.assertEqual(req.unredirected_hdrs["Content-length"], "0")
self.assertEqual(req.unredirected_hdrs["Content-type"], self.assertEqual(req.unredirected_hdrs["Content-type"],
@ -897,13 +897,13 @@ class HandlerTests(unittest.TestCase):
# now it's a GET, there should not be headers regarding content # now it's a GET, there should not be headers regarding content
# (possibly dragged from before being a POST) # (possibly dragged from before being a POST)
headers = [x.lower() for x in o.req.headers] headers = [x.lower() for x in o.req.headers]
self.assertTrue("content-length" not in headers) self.assertNotIn("content-length", headers)
self.assertTrue("content-type" not in headers) self.assertNotIn("content-type", headers)
self.assertEqual(o.req.headers["Nonsense"], self.assertEqual(o.req.headers["Nonsense"],
"viking=withhold") "viking=withhold")
self.assertTrue("Spam" not in o.req.headers) self.assertNotIn("Spam", o.req.headers)
self.assertTrue("Spam" not in o.req.unredirected_hdrs) self.assertNotIn("Spam", o.req.unredirected_hdrs)
# loop detection # loop detection
req = Request(from_url) req = Request(from_url)
@ -1017,9 +1017,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

@ -96,7 +96,7 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
# Test has_key and "in". # Test has_key and "in".
for i in u2.keys(): for i in u2.keys():
self.assertTrue(u2.has_key(i)) self.assertTrue(u2.has_key(i))
self.assertTrue(i in u2) self.assertIn(i, u2)
self.assertEqual(u1.has_key(i), d1.has_key(i)) self.assertEqual(u1.has_key(i), d1.has_key(i))
self.assertEqual(i in u1, i in d1) self.assertEqual(i in u1, i in d1)
self.assertEqual(u0.has_key(i), d0.has_key(i)) self.assertEqual(u0.has_key(i), d0.has_key(i))
@ -161,8 +161,8 @@ class UserDictTest(mapping_tests.TestHashMappingProtocol):
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.assertTrue(2 not in d.keys()) self.assertNotIn(2, d.keys())
self.assertEqual(d[2], 42) self.assertEqual(d[2], 42)
class E(UserDict.UserDict): class E(UserDict.UserDict):
def __missing__(self, key): def __missing__(self, key):
@ -273,8 +273,8 @@ class UserDictMixinTest(mapping_tests.TestMappingProtocol):
self.assertTrue(not s.has_key(20)) self.assertTrue(not s.has_key(20))
# __contains__ # __contains__
self.assertTrue(10 in s) self.assertIn(10, s)
self.assertTrue(20 not in s) self.assertNotIn(20, s)
# __iter__ # __iter__
self.assertEqual([k for k in s], [10, 30]) self.assertEqual([k for k in s], [10, 30])
@ -309,7 +309,7 @@ class UserDictMixinTest(mapping_tests.TestMappingProtocol):
# pop # pop
self.assertEqual(s.pop(10), 'ten') self.assertEqual(s.pop(10), 'ten')
self.assertTrue(10 not in s) self.assertNotIn(10, s)
s[10] = 'ten' s[10] = 'ten'
self.assertEqual(s.pop("x", 1), 1) self.assertEqual(s.pop("x", 1), 1)
s["x"] = 42 s["x"] = 42
@ -317,7 +317,7 @@ class UserDictMixinTest(mapping_tests.TestMappingProtocol):
# popitem # popitem
k, v = s.popitem() k, v = s.popitem()
self.assertTrue(k not in s) self.assertNotIn(k, s)
s[k] = v s[k] = v
# clear # clear

View file

@ -472,7 +472,7 @@ class _WarningsTests(BaseTest):
with test_support.captured_output('stderr') as stream: with test_support.captured_output('stderr') as stream:
self.module.warn(text) self.module.warn(text)
result = stream.getvalue() result = stream.getvalue()
self.assertTrue(text in result) self.assertIn(text, result)
def test_showwarning_not_callable(self): def test_showwarning_not_callable(self):
with original_warnings.catch_warnings(module=self.module): with original_warnings.catch_warnings(module=self.module):

View file

@ -172,8 +172,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)
@ -196,7 +195,7 @@ class ReferencesTestCase(TestBase):
def __unicode__(self): def __unicode__(self):
return u"unicode" return u"unicode"
instance = C() instance = C()
self.assertTrue("__unicode__" in dir(weakref.proxy(instance))) self.assertIn("__unicode__", dir(weakref.proxy(instance)))
self.assertEqual(unicode(weakref.proxy(instance)), u"unicode") self.assertEqual(unicode(weakref.proxy(instance)), u"unicode")
def test_proxy_index(self): def test_proxy_index(self):
@ -718,8 +717,8 @@ class SubclassableWeakrefTestCase(TestBase):
refs = weakref.getweakrefs(o) refs = weakref.getweakrefs(o)
self.assertEqual(len(refs), 3) self.assertEqual(len(refs), 3)
self.assertTrue(r2 is refs[0]) self.assertTrue(r2 is refs[0])
self.assertTrue(r1 in refs[1:]) self.assertIn(r1, refs[1:])
self.assertTrue(r3 in refs[1:]) self.assertIn(r3, refs[1:])
def test_subclass_refs_dont_conflate_callbacks(self): def test_subclass_refs_dont_conflate_callbacks(self):
class MyRef(weakref.ref): class MyRef(weakref.ref):
@ -729,8 +728,8 @@ class SubclassableWeakrefTestCase(TestBase):
r2 = MyRef(o, str) r2 = MyRef(o, str)
self.assertTrue(r1 is not r2) self.assertTrue(r1 is not r2)
refs = weakref.getweakrefs(o) refs = weakref.getweakrefs(o)
self.assertTrue(r1 in refs) self.assertIn(r1, refs)
self.assertTrue(r2 in refs) self.assertIn(r2, refs)
def test_subclass_refs_with_slots(self): def test_subclass_refs_with_slots(self):
class MyRef(weakref.ref): class MyRef(weakref.ref):
@ -868,7 +867,7 @@ class MappingTestCase(TestBase):
for wr in refs: for wr in refs:
ob = wr() ob = wr()
self.assertTrue(dict.has_key(ob)) self.assertTrue(dict.has_key(ob))
self.assertTrue(ob in dict) self.assertIn(ob, dict)
self.assertEqual(ob.arg, dict[ob]) self.assertEqual(ob.arg, dict[ob])
objects2.remove(ob) objects2.remove(ob)
self.assertEqual(len(objects2), 0) self.assertEqual(len(objects2), 0)
@ -879,7 +878,7 @@ class MappingTestCase(TestBase):
for wr in dict.iterkeyrefs(): for wr in dict.iterkeyrefs():
ob = wr() ob = wr()
self.assertTrue(dict.has_key(ob)) self.assertTrue(dict.has_key(ob))
self.assertTrue(ob in dict) self.assertIn(ob, dict)
self.assertEqual(ob.arg, dict[ob]) self.assertEqual(ob.arg, dict[ob])
objects2.remove(ob) objects2.remove(ob)
self.assertEqual(len(objects2), 0) self.assertEqual(len(objects2), 0)

View file

@ -112,7 +112,7 @@ class WinregTests(unittest.TestCase):
data = EnumValue(sub_key, index) data = EnumValue(sub_key, index)
except EnvironmentError: except EnvironmentError:
break break
self.assertEquals(data in test_data, True, self.assertIn(data, test_data,
"Didn't read back the correct test data") "Didn't read back the correct test data")
index = index + 1 index = index + 1
self.assertEquals(index, len(test_data), self.assertEquals(index, len(test_data),

View file

@ -941,7 +941,7 @@ class TransportSubclassTestCase(unittest.TestCase):
conn.putheader("X-Test", "test_custom_user_agent") conn.putheader("X-Test", "test_custom_user_agent")
req = self.issue_request(TestTransport) req = self.issue_request(TestTransport)
self.assertTrue("X-Test: test_custom_user_agent\r\n" in req) self.assertIn("X-Test: test_custom_user_agent\r\n", req)
def test_send_host(self): def test_send_host(self):
class TestTransport(FakeTransport): class TestTransport(FakeTransport):
@ -951,7 +951,7 @@ class TransportSubclassTestCase(unittest.TestCase):
conn.putheader("X-Test", "test_send_host") conn.putheader("X-Test", "test_send_host")
req = self.issue_request(TestTransport) req = self.issue_request(TestTransport)
self.assertTrue("X-Test: test_send_host\r\n" in req) self.assertIn("X-Test: test_send_host\r\n", req)
def test_send_request(self): def test_send_request(self):
class TestTransport(FakeTransport): class TestTransport(FakeTransport):
@ -961,7 +961,7 @@ class TransportSubclassTestCase(unittest.TestCase):
conn.putheader("X-Test", "test_send_request") conn.putheader("X-Test", "test_send_request")
req = self.issue_request(TestTransport) req = self.issue_request(TestTransport)
self.assertTrue("X-Test: test_send_request\r\n" in req) self.assertIn("X-Test: test_send_request\r\n", req)
def test_send_content(self): def test_send_content(self):
class TestTransport(FakeTransport): class TestTransport(FakeTransport):
@ -971,7 +971,7 @@ class TransportSubclassTestCase(unittest.TestCase):
xmlrpclib.Transport.send_content(self, conn, body) xmlrpclib.Transport.send_content(self, conn, body)
req = self.issue_request(TestTransport) req = self.issue_request(TestTransport)
self.assertTrue("X-Test: test_send_content\r\n" in req) self.assertIn("X-Test: test_send_content\r\n", req)
@test_support.reap_threads @test_support.reap_threads
def test_main(): def test_main():

View file

@ -63,18 +63,18 @@ class XrangeTest(unittest.TestCase):
self.assertEqual(list(xrange(a+4, a, -2)), [a+4, a+2]) self.assertEqual(list(xrange(a+4, a, -2)), [a+4, a+2])
seq = list(xrange(a, b, c)) seq = list(xrange(a, b, c))
self.assertTrue(a in seq) self.assertIn(a, seq)
self.assertTrue(b not in seq) self.assertNotIn(b, seq)
self.assertEqual(len(seq), 2) self.assertEqual(len(seq), 2)
seq = list(xrange(b, a, -c)) seq = list(xrange(b, a, -c))
self.assertTrue(b in seq) self.assertIn(b, seq)
self.assertTrue(a not in seq) self.assertNotIn(a, seq)
self.assertEqual(len(seq), 2) self.assertEqual(len(seq), 2)
seq = list(xrange(-a, -b, -c)) seq = list(xrange(-a, -b, -c))
self.assertTrue(-a in seq) self.assertIn(-a, seq)
self.assertTrue(-b not in seq) self.assertNotIn(-b, seq)
self.assertEqual(len(seq), 2) self.assertEqual(len(seq), 2)
self.assertRaises(TypeError, xrange) self.assertRaises(TypeError, xrange)

View file

@ -68,9 +68,9 @@ class TestsWithSourceFile(unittest.TestCase):
lines = directory.splitlines() lines = directory.splitlines()
self.assertEqual(len(lines), 4) # Number of files + header self.assertEqual(len(lines), 4) # Number of files + header
self.assertTrue('File Name' in lines[0]) self.assertIn('File Name', lines[0])
self.assertTrue('Modified' in lines[0]) self.assertIn('Modified', lines[0])
self.assertTrue('Size' in lines[0]) self.assertIn('Size', lines[0])
fn, date, time_, size = lines[1].split() fn, date, time_, size = lines[1].split()
self.assertEqual(fn, 'another.name') self.assertEqual(fn, 'another.name')
@ -81,17 +81,17 @@ class TestsWithSourceFile(unittest.TestCase):
# Check the namelist # Check the namelist
names = zipfp.namelist() names = zipfp.namelist()
self.assertEqual(len(names), 3) self.assertEqual(len(names), 3)
self.assertTrue(TESTFN in names) self.assertIn(TESTFN, names)
self.assertTrue("another.name" in names) self.assertIn("another.name", names)
self.assertTrue("strfile" in names) self.assertIn("strfile", names)
# Check infolist # Check infolist
infos = zipfp.infolist() infos = zipfp.infolist()
names = [i.filename for i in infos] names = [i.filename for i in infos]
self.assertEqual(len(names), 3) self.assertEqual(len(names), 3)
self.assertTrue(TESTFN in names) self.assertIn(TESTFN, names)
self.assertTrue("another.name" in names) self.assertIn("another.name", names)
self.assertTrue("strfile" in names) self.assertIn("strfile", names)
for i in infos: for i in infos:
self.assertEqual(i.file_size, len(self.data)) self.assertEqual(i.file_size, len(self.data))
@ -458,9 +458,9 @@ class TestZip64InSmallFiles(unittest.TestCase):
lines = directory.splitlines() lines = directory.splitlines()
self.assertEqual(len(lines), 4) # Number of files + header self.assertEqual(len(lines), 4) # Number of files + header
self.assertTrue('File Name' in lines[0]) self.assertIn('File Name', lines[0])
self.assertTrue('Modified' in lines[0]) self.assertIn('Modified', lines[0])
self.assertTrue('Size' in lines[0]) self.assertIn('Size', lines[0])
fn, date, time_, size = lines[1].split() fn, date, time_, size = lines[1].split()
self.assertEqual(fn, 'another.name') self.assertEqual(fn, 'another.name')
@ -471,17 +471,17 @@ class TestZip64InSmallFiles(unittest.TestCase):
# Check the namelist # Check the namelist
names = zipfp.namelist() names = zipfp.namelist()
self.assertEqual(len(names), 3) self.assertEqual(len(names), 3)
self.assertTrue(TESTFN in names) self.assertIn(TESTFN, names)
self.assertTrue("another.name" in names) self.assertIn("another.name", names)
self.assertTrue("strfile" in names) self.assertIn("strfile", names)
# Check infolist # Check infolist
infos = zipfp.infolist() infos = zipfp.infolist()
names = [i.filename for i in infos] names = [i.filename for i in infos]
self.assertEqual(len(names), 3) self.assertEqual(len(names), 3)
self.assertTrue(TESTFN in names) self.assertIn(TESTFN, names)
self.assertTrue("another.name" in names) self.assertIn("another.name", names)
self.assertTrue("strfile" in names) self.assertIn("strfile", names)
for i in infos: for i in infos:
self.assertEqual(i.file_size, len(self.data)) self.assertEqual(i.file_size, len(self.data))
@ -527,7 +527,7 @@ class PyZipFileTests(unittest.TestCase):
zipfp.writepy(fn) zipfp.writepy(fn)
bn = os.path.basename(fn) bn = os.path.basename(fn)
self.assertTrue(bn not in zipfp.namelist()) self.assertNotIn(bn, zipfp.namelist())
self.assertTrue(bn + 'o' in zipfp.namelist() or self.assertTrue(bn + 'o' in zipfp.namelist() or
bn + 'c' in zipfp.namelist()) bn + 'c' in zipfp.namelist())
@ -539,7 +539,7 @@ class PyZipFileTests(unittest.TestCase):
zipfp.writepy(fn, "testpackage") zipfp.writepy(fn, "testpackage")
bn = "%s/%s" % ("testpackage", os.path.basename(fn)) bn = "%s/%s" % ("testpackage", os.path.basename(fn))
self.assertTrue(bn not in zipfp.namelist()) self.assertNotIn(bn, zipfp.namelist())
self.assertTrue(bn + 'o' in zipfp.namelist() or self.assertTrue(bn + 'o' in zipfp.namelist() or
bn + 'c' in zipfp.namelist()) bn + 'c' in zipfp.namelist())
@ -576,7 +576,7 @@ class PyZipFileTests(unittest.TestCase):
names = zipfp.namelist() names = zipfp.namelist()
self.assertTrue('mod1.pyc' in names or 'mod1.pyo' 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.pyc' in names or 'mod2.pyo' in names)
self.assertTrue('mod2.txt' not in names) self.assertNotIn('mod2.txt', names)
finally: finally:
shutil.rmtree(TESTFN2) shutil.rmtree(TESTFN2)

View file

@ -297,7 +297,7 @@ class UncompressedZipImportTestCase(ImportHooksBaseTestCase):
z.close() z.close()
zi = zipimport.zipimporter(TEMP_ZIP) zi = zipimport.zipimporter(TEMP_ZIP)
self.assertEquals(data, zi.get_data(name)) self.assertEquals(data, zi.get_data(name))
self.assertTrue('zipimporter object' in repr(zi)) self.assertIn('zipimporter object', repr(zi))
finally: finally:
z.close() z.close()
os.remove(TEMP_ZIP) os.remove(TEMP_ZIP)

View file

@ -189,7 +189,7 @@ class ZipSupportTests(ImportHooksBaseTestCase):
print "Expected line", expected print "Expected line", expected
print "Got stdout:" print "Got stdout:"
print data print data
self.assertTrue(expected in data) self.assertIn(expected, data)
zip_name, run_name = make_zip_script(d, "test_zip", zip_name, run_name = make_zip_script(d, "test_zip",
script_name, '__main__.py') script_name, '__main__.py')
exit_code, data = run_python(zip_name) exit_code, data = run_python(zip_name)
@ -198,7 +198,7 @@ class ZipSupportTests(ImportHooksBaseTestCase):
print "Expected line", expected print "Expected line", expected
print "Got stdout:" print "Got stdout:"
print data print data
self.assertTrue(expected in data) self.assertIn(expected, data)
def test_pdb_issue4201(self): def test_pdb_issue4201(self):
test_src = textwrap.dedent("""\ test_src = textwrap.dedent("""\
@ -213,13 +213,13 @@ class ZipSupportTests(ImportHooksBaseTestCase):
p = spawn_python(script_name) p = spawn_python(script_name)
p.stdin.write('l\n') p.stdin.write('l\n')
data = kill_python(p) data = kill_python(p)
self.assertTrue(script_name in data) self.assertIn(script_name, data)
zip_name, run_name = make_zip_script(d, "test_zip", zip_name, run_name = make_zip_script(d, "test_zip",
script_name, '__main__.py') script_name, '__main__.py')
p = spawn_python(zip_name) p = spawn_python(zip_name)
p.stdin.write('l\n') p.stdin.write('l\n')
data = kill_python(p) data = kill_python(p)
self.assertTrue(run_name in data) self.assertIn(run_name, data)
def test_main(): def test_main():