def test_valid_non_numeric_input_types_for_x(self): # Test possible valid non-numeric types for x, including subclasses # of the allowed built-in types. class CustomStr(str): pass class CustomByteArray(bytearray): pass factories = [str, bytearray, CustomStr, CustomByteArray, buffer] if have_unicode: class CustomUnicode(unicode): pass factories += [unicode, CustomUnicode] for f in factories: with test_support.check_py3k_warnings(quiet=True): x = f('100') msg = 'x has value %s and type %s' % (x, type(x).__name__) try: self.assertEqual(int(x), 100, msg=msg) if isinstance(x, basestring): self.assertEqual(int(x, 2), 4, msg=msg) except TypeError, err: raise AssertionError('For %s got TypeError: %s' % (type(x).__name__, err)) if not isinstance(x, basestring): errmsg = "can't convert non-string" with self.assertRaisesRegexp(TypeError, errmsg, msg=msg): int(x, 2) errmsg = 'invalid literal' with self.assertRaisesRegexp(ValueError, errmsg, msg=msg), \ test_support.check_py3k_warnings(quiet=True): int(f('A' * 0x10))
def test_basic_proxy(self): o = C() self.check_proxy(o, weakref.proxy(o)) L = UserList.UserList() p = weakref.proxy(L) self.assertFalse(p, "proxy for empty UserList should be false") p.append(12) self.assertEqual(len(L), 1) self.assertTrue(p, "proxy for non-empty UserList should be true") with test_support.check_py3k_warnings(): p[:] = [2, 3] self.assertEqual(len(L), 2) self.assertEqual(len(p), 2) self.assertIn(3, p, "proxy didn't support __contains__() properly") p[1] = 5 self.assertEqual(L[1], 5) self.assertEqual(p[1], 5) L2 = UserList.UserList(L) p2 = weakref.proxy(L2) self.assertEqual(p, p2) ## self.assertEqual(repr(L2), repr(p2)) L3 = UserList.UserList(range(10)) p3 = weakref.proxy(L3) with test_support.check_py3k_warnings(): self.assertEqual(L3[:], p3[:]) self.assertEqual(L3[5:], p3[5:]) self.assertEqual(L3[:5], p3[:5]) self.assertEqual(L3[2:5], p3[2:5])
def test_softspace(self): expected = 'file.softspace not supported in 3.x' with file(__file__) as f: with check_py3k_warnings() as w: self.assertWarning(f.softspace, w, expected) def set(): f.softspace = 0 with check_py3k_warnings() as w: self.assertWarning(set(), w, expected)
def test_multiplicative_ops(self): x = 1 * 1 with check_py3k_warnings(('classic int division', DeprecationWarning)): x = 1 / 1 x = 1 / 1.0 x = 1 % 1 with check_py3k_warnings(('classic int division', DeprecationWarning)): x = 1 / 1 * 1 % 1 x = 1 / 1.0 * 1 % 1
def test_et_hash(self): from _testcapi import getargs_et_hash self.assertEqual(getargs_et_hash('abc\xe9'), 'abc\xe9') self.assertEqual(getargs_et_hash(u'abc'), 'abc') self.assertEqual(getargs_et_hash('abc\xe9', 'ascii'), 'abc\xe9') self.assertEqual(getargs_et_hash(u'abc\xe9', 'latin1'), 'abc\xe9') self.assertRaises(UnicodeEncodeError, getargs_et_hash, u'abc\xe9', 'ascii') self.assertRaises(LookupError, getargs_et_hash, u'abc', 'spam') self.assertRaises(TypeError, getargs_et_hash, bytearray('bytearray'), 'latin1') self.assertRaises(TypeError, getargs_et_hash, memoryview('memoryview'), 'latin1') with test_support.check_py3k_warnings(): self.assertEqual(getargs_et_hash(buffer('abc'), 'ascii'), 'abc') self.assertEqual(getargs_et_hash(buffer(u'abc'), 'ascii'), 'abc') self.assertRaises(TypeError, getargs_et_hash, None, 'latin1') self.assertEqual(getargs_et_hash('nul:\0', 'latin1'), 'nul:\0') self.assertEqual(getargs_et_hash(u'nul:\0', 'latin1'), 'nul:\0') buf = bytearray('x'*8) self.assertEqual(getargs_et_hash(u'abc\xe9', 'latin1', buf), 'abc\xe9') self.assertEqual(buf, bytearray('abc\xe9\x00xxx')) buf = bytearray('x'*5) self.assertEqual(getargs_et_hash(u'abc\xe9', 'latin1', buf), 'abc\xe9') self.assertEqual(buf, bytearray('abc\xe9\x00')) buf = bytearray('x'*4) self.assertRaises(TypeError, getargs_et_hash, u'abc\xe9', 'latin1', buf) self.assertEqual(buf, bytearray('x'*4)) buf = bytearray() self.assertRaises(TypeError, getargs_et_hash, u'abc\xe9', 'latin1', buf)
def test_basics(self): c = Counter("abcaba") self.assertEqual(c, Counter({"a": 3, "b": 2, "c": 1})) self.assertEqual(c, Counter(a=3, b=2, c=1)) self.assertIsInstance(c, dict) self.assertIsInstance(c, Mapping) self.assertTrue(issubclass(Counter, dict)) self.assertTrue(issubclass(Counter, Mapping)) self.assertEqual(len(c), 3) self.assertEqual(sum(c.values()), 6) self.assertEqual(sorted(c.values()), [1, 2, 3]) self.assertEqual(sorted(c.keys()), ["a", "b", "c"]) self.assertEqual(sorted(c), ["a", "b", "c"]) self.assertEqual(sorted(c.items()), [("a", 3), ("b", 2), ("c", 1)]) self.assertEqual(c["b"], 2) self.assertEqual(c["z"], 0) with test_support.check_py3k_warnings(): self.assertEqual(c.has_key("c"), True) self.assertEqual(c.has_key("z"), False) self.assertEqual(c.__contains__("c"), True) self.assertEqual(c.__contains__("z"), False) self.assertEqual(c.get("b", 10), 2) self.assertEqual(c.get("z", 10), 10) self.assertEqual(c, dict(a=3, b=2, c=1)) self.assertEqual(repr(c), "Counter({'a': 3, 'b': 2, 'c': 1})") self.assertEqual(c.most_common(), [("a", 3), ("b", 2), ("c", 1)]) for i in range(5): self.assertEqual(c.most_common(i), [("a", 3), ("b", 2), ("c", 1)][:i]) self.assertEqual("".join(sorted(c.elements())), "aaabbc") c["a"] += 1 # increment an existing value c["b"] -= 2 # sub existing value to zero del c["c"] # remove an entry del c["c"] # make sure that del doesn't raise KeyError c["d"] -= 2 # sub from a missing value c["e"] = -5 # directly assign a missing value c["f"] += 4 # add to a missing value self.assertEqual(c, dict(a=4, b=0, d=-2, e=-5, f=4)) self.assertEqual("".join(sorted(c.elements())), "aaaaffff") self.assertEqual(c.pop("f"), 4) self.assertNotIn("f", c) for i in range(3): elem, cnt = c.popitem() self.assertNotIn(elem, c) c.clear() self.assertEqual(c, {}) self.assertEqual(repr(c), "Counter()") self.assertRaises(NotImplementedError, Counter.fromkeys, "abc") self.assertRaises(TypeError, hash, c) c.update(dict(a=5, b=3)) c.update(c=1) c.update(Counter("a" * 50 + "b" * 30)) c.update() # test case with no args c.__init__("a" * 500 + "b" * 300) c.__init__("cdc") c.__init__() self.assertEqual(c, dict(a=555, b=333, c=3, d=1)) self.assertEqual(c.setdefault("d", 5), 1) self.assertEqual(c["d"], 1) self.assertEqual(c.setdefault("e", 5), 5) self.assertEqual(c["e"], 5)
def setUp(self): self.con = sqlite.connect(":memory:") cur = self.con.cursor() cur.execute( """ create table test( t text, i integer, f float, n, b blob ) """ ) with test_support.check_py3k_warnings(): cur.execute( "insert into test(t, i, f, n, b) values (?, ?, ?, ?, ?)", ("foo", 5, 3.14, None, buffer("blob")) ) self.con.create_aggregate("nostep", 1, AggrNoStep) self.con.create_aggregate("nofinalize", 1, AggrNoFinalize) self.con.create_aggregate("excInit", 1, AggrExceptionInInit) self.con.create_aggregate("excStep", 1, AggrExceptionInStep) self.con.create_aggregate("excFinalize", 1, AggrExceptionInFinalize) self.con.create_aggregate("checkType", 2, AggrCheckType) self.con.create_aggregate("mysum", 1, AggrSum)
def test_main(): with test_support.check_py3k_warnings( (".+__(get|set|del)slice__ has been removed", DeprecationWarning), ("classic int division", DeprecationWarning), ("<> not supported", DeprecationWarning), ): test_support.run_unittest(ClassTests)
def test_forbidden_names(self): # So we don't screw up our globals def safe_exec(expr): def f(**kwargs): pass exec expr in {'f' : f} tests = [("True", "assignment to True or False is forbidden in 3.x"), ("False", "assignment to True or False is forbidden in 3.x"), ("nonlocal", "nonlocal is a keyword in 3.x")] with check_py3k_warnings(('', SyntaxWarning)) as w: for keyword, expected in tests: safe_exec("{0} = False".format(keyword)) self.assertWarning(None, w, expected) w.reset() try: safe_exec("obj.{0} = True".format(keyword)) except NameError: pass self.assertWarning(None, w, expected) w.reset() safe_exec("def {0}(): pass".format(keyword)) self.assertWarning(None, w, expected) w.reset() safe_exec("class {0}: pass".format(keyword)) self.assertWarning(None, w, expected) w.reset() safe_exec("def f({0}=43): pass".format(keyword)) self.assertWarning(None, w, expected) w.reset()
def test_execfile(self): namespace = {} with test_support.check_py3k_warnings(): execfile(test_support.TESTFN, namespace) func = namespace['line3'] self.assertEqual(func.func_code.co_firstlineno, 3) self.assertEqual(namespace['line4'], FATX)
def test_auto_overflow(self): special = [0, 1, 2, 3, sys.maxint-1, sys.maxint, sys.maxint+1] sqrt = int(math.sqrt(sys.maxint)) special.extend([sqrt-1, sqrt, sqrt+1]) special.extend([-i for i in special]) def checkit(*args): # Heavy use of nested scopes here! self.assertEqual(got, expected, Frm("for %r expected %r got %r", args, expected, got)) for x in special: longx = long(x) expected = -longx got = -x checkit('-', x) for y in special: longy = long(y) expected = longx + longy got = x + y checkit(x, '+', y) expected = longx - longy got = x - y checkit(x, '-', y) expected = longx * longy got = x * y checkit(x, '*', y) if y: with test_support.check_py3k_warnings(): expected = longx / longy got = x / y checkit(x, '/', y) expected = longx // longy got = x // y checkit(x, '//', y) expected = divmod(longx, longy) got = divmod(longx, longy) checkit(x, 'divmod', y) if abs(y) < 5 and not (x == 0 and y < 0): expected = longx ** longy got = x ** y checkit(x, '**', y) for z in special: if z != 0 : if y >= 0: expected = pow(longx, longy, long(z)) got = pow(x, y, z) checkit('pow', x, y, '%', z) else: self.assertRaises(TypeError, pow,longx, longy, long(z))
def test_main(): with check_py3k_warnings(("exceptions must derive from BaseException", DeprecationWarning), ("catching classes that don't inherit " "from BaseException is not allowed", DeprecationWarning)): run_unittest(OpcodeTest)
def CheckBlob(self): with test_support.check_py3k_warnings(): val = buffer("Guglhupf") self.cur.execute("insert into test(b) values (?)", (val,)) self.cur.execute("select b from test") row = self.cur.fetchone() self.assertEqual(row[0], val)
def test_builtin_map(self): self.assertEqual(map(lambda x: x+1, SequenceClass(5)), range(1, 6)) d = {"one": 1, "two": 2, "three": 3} self.assertEqual(map(lambda k, d=d: (k, d[k]), d), d.items()) dkeys = d.keys() expected = [(i < len(d) and dkeys[i] or None, i, i < len(d) and dkeys[i] or None) for i in range(5)] # Deprecated map(None, ...) with check_py3k_warnings(): self.assertEqual(map(None, SequenceClass(5)), range(5)) self.assertEqual(map(None, d), d.keys()) self.assertEqual(map(None, d, SequenceClass(5), iter(d.iterkeys())), expected) f = open(TESTFN, "w") try: for i in range(10): f.write("xy" * i + "\n") # line i has len 2*i+1 finally: f.close() f = open(TESTFN, "r") try: self.assertEqual(map(len, f), range(1, 21, 2)) finally: f.close() try: unlink(TESTFN) except OSError: pass
def test_atoms(self): ### atom: '(' [testlist] ')' | '[' [testlist] ']' | '{' [dictmaker] '}' | '`' testlist '`' | NAME | NUMBER | STRING ### dictorsetmaker: (test ':' test (',' test ':' test)* [',']) | (test (',' test)* [',']) x = (1) x = (1 or 2 or 3) x = (1 or 2 or 3, 2, 3) x = [] x = [1] x = [1 or 2 or 3] x = [1 or 2 or 3, 2, 3] x = [] x = {} x = {'one': 1} x = {'one': 1,} x = {'one' or 'two': 1 or 2} x = {'one': 1, 'two': 2} x = {'one': 1, 'two': 2,} x = {'one': 1, 'two': 2, 'three': 3, 'four': 4, 'five': 5, 'six': 6} x = {'one'} x = {'one', 1,} x = {'one', 'two', 'three'} x = {2, 3, 4,} with check_py3k_warnings(('backquote not supported', SyntaxWarning)): x = eval('`x`') x = eval('`1 or 2 or 3`') self.assertEqual(eval('`1,2`'), '(1, 2)') x = x x = 'x' x = 123
def testComplexDefinitions(self): def makeReturner(*lst): def returner(): return lst return returner self.assertEqual(makeReturner(1,2,3)(), (1,2,3)) def makeReturner2(**kwargs): def returner(): return kwargs return returner self.assertEqual(makeReturner2(a=11)()['a'], 11) with check_py3k_warnings(("tuple parameter unpacking has been removed", SyntaxWarning)): exec """\ def makeAddPair((a, b)): def addPair((c, d)): return (a + c, b + d) return addPair """ in locals() self.assertEqual(makeAddPair((1, 2))((100, 200)), (101,202))
def test_main(): test_support.requires('network') with test_support.check_py3k_warnings( ("urllib.urlopen.. has been removed", DeprecationWarning)): test_support.run_unittest(URLTimeoutTest, urlopenNetworkTests, urlretrieveNetworkTests)
def test_int_buffer(self): with test_support.check_py3k_warnings(): self.assertEqual(int(buffer('123', 1, 2)), 23) self.assertEqual(int(buffer('123\x00', 1, 2)), 23) self.assertEqual(int(buffer('123 ', 1, 2)), 23) self.assertEqual(int(buffer('123A', 1, 2)), 23) self.assertEqual(int(buffer('1234', 1, 2)), 23)
def testAttributes(self): # verify expected attributes exist f = self.f with test_support.check_py3k_warnings(): softspace = f.softspace f.name # merely shouldn't blow up f.mode # ditto f.closed # ditto with test_support.check_py3k_warnings(): # verify softspace is writable f.softspace = softspace # merely shouldn't blow up # verify the others aren't for attr in 'name', 'mode', 'closed': self.assertRaises((AttributeError, TypeError), setattr, f, attr, 'oops')
def testMethods(self): methods = ['fileno', 'flush', 'isatty', 'next', 'read', 'readinto', 'readline', 'readlines', 'seek', 'tell', 'truncate', 'write', '__iter__'] deprecated_methods = ['xreadlines'] if sys.platform.startswith('atheos'): methods.remove('truncate') # __exit__ should close the file self.f.__exit__(None, None, None) self.assertTrue(self.f.closed) for methodname in methods: method = getattr(self.f, methodname) args = {'readinto': (bytearray(''),), 'seek': (0,), 'write': ('',), }.get(methodname, ()) # should raise on closed file self.assertRaises(ValueError, method, *args) with test_support.check_py3k_warnings(): for methodname in deprecated_methods: method = getattr(self.f, methodname) self.assertRaises(ValueError, method) self.assertRaises(ValueError, self.f.writelines, []) # file is closed, __exit__ shouldn't do anything self.assertEqual(self.f.__exit__(None, None, None), None) # it must also return None if an exception was given try: 1 // 0 except: self.assertEqual(self.f.__exit__(*sys.exc_info()), None)
def CheckFuncReturnBlob(self): cur = self.con.cursor() cur.execute("select returnblob()") val = cur.fetchone()[0] with test_support.check_py3k_warnings(): self.assertEqual(type(val), buffer) self.assertEqual(val, buffer("blob"))
def test_main(): with check_py3k_warnings( ("buffer.. not supported", DeprecationWarning), ("classic long division", DeprecationWarning)): run_unittest(TypesTests) run_unittest(MappingProxyTests) run_unittest(CoroutineTests)
def test_unary_ops(self): x = +1 x = -1 x = ~1 x = ~1 ^ 1 & 1 | 1 & 1 ^ -1 with check_py3k_warnings(('classic int division', DeprecationWarning)): x = -1*1/1 + 1*1 - ---1*1 x = -1*1/1.0 + 1*1 - ---1*1
def test_pickle(self): buf = buffer(b'abc') for proto in range(2): with self.assertRaises(TypeError): pickle.dumps(buf, proto) with test_support.check_py3k_warnings( (".*buffer", DeprecationWarning)): pickle.dumps(buf, 2)
def test_main(): if not test_support.due_to_ironpython_bug("http://tkbgitvstfat01:8080/WorkItemTracking/WorkItem.aspx?artifactMoniker=303467"): test_support.requires('network') with test_support.check_py3k_warnings( ("urllib.urlopen.. has been removed", DeprecationWarning)): test_support.run_unittest(URLTimeoutTest, urlopenNetworkTests, urlretrieveNetworkTests)
def test_contains(self): self.assertRaises(TypeError, operator.contains) self.assertRaises(TypeError, operator.contains, None, None) self.assertTrue(operator.contains(range(4), 2)) self.assertFalse(operator.contains(range(4), 5)) with test_support.check_py3k_warnings(): self.assertTrue(operator.sequenceIncludes(range(4), 2)) self.assertFalse(operator.sequenceIncludes(range(4), 5))
def test_varargs2_ext(self): try: with test_support.check_py3k_warnings(): {}.has_key(*(1, 2)) except TypeError: pass else: raise RuntimeError
def test_methods_members(self): expected = '__members__ and __methods__ not supported in 3.x' class C: __methods__ = ['a'] __members__ = ['b'] c = C() with check_py3k_warnings() as w: self.assertWarning(dir(c), w, expected)
def test_pickle(self): m = memoryview(b'abc') for proto in range(2): with self.assertRaises(TypeError): pickle.dumps(m, proto) with test_support.check_py3k_warnings( (".*memoryview", DeprecationWarning)): pickle.dumps(m, 2)
def test_main(): with check_py3k_warnings( ("backquote not supported", SyntaxWarning), ("tuple parameter unpacking has been removed", SyntaxWarning), ("parenthesized argument names are invalid", SyntaxWarning), ("classic int division", DeprecationWarning), (".+ not supported in 3.x", DeprecationWarning)): run_unittest(TokenTests, GrammarTests)
def CheckBinaryInputForConverter(self): testdata = "abcdefg" * 10 with test_support.check_py3k_warnings(): result = self.con.execute('select ? as "x [bin]"', (buffer(zlib.compress(testdata)),)).fetchone()[0] self.assertEqual(testdata, result)
def test_main(): with test_support.check_py3k_warnings(("backquote not supported", SyntaxWarning)): test_support.run_unittest(AST_Tests, ASTHelpers_Test)
def CheckBinary(self): with test_support.check_py3k_warnings(): b = sqlite.Binary(chr(0) + "'")
def test_sys_exc_clear(self): expected = 'sys.exc_clear() not supported in 3.x; use except clauses' with check_py3k_warnings() as w: self.assertWarning(sys.exc_clear(), w, expected)
def test_c_buffer_deprecated(self): # Compatibility with 2.x with test_support.check_py3k_warnings(): self.test_c_buffer_value(buffer) self.test_c_buffer_raw(buffer)
def test_auto_overflow(self): special = [0, 1, 2, 3, sys.maxint - 1, sys.maxint, sys.maxint + 1] sqrt = int(math.sqrt(sys.maxint)) special.extend([sqrt - 1, sqrt, sqrt + 1]) special.extend([-i for i in special]) def checkit(*args): # Heavy use of nested scopes here! self.assertEqual( got, expected, Frm("for %r expected %r got %r", args, expected, got)) for x in special: longx = long(x) expected = -longx got = -x checkit('-', x) for y in special: longy = long(y) expected = longx + longy got = x + y checkit(x, '+', y) expected = longx - longy got = x - y checkit(x, '-', y) expected = longx * longy got = x * y checkit(x, '*', y) if y: with test_support.check_py3k_warnings(): expected = longx / longy got = x / y checkit(x, '/', y) expected = longx // longy got = x // y checkit(x, '//', y) expected = divmod(longx, longy) got = divmod(longx, longy) checkit(x, 'divmod', y) if abs(y) < 5 and not (x == 0 and y < 0): expected = longx**longy got = x**y checkit(x, '**', y) for z in special: if z != 0: if y >= 0: expected = pow(longx, longy, long(z)) got = pow(x, y, z) checkit('pow', x, y, '%', z) else: self.assertRaises(TypeError, pow, longx, longy, long(z))
import re import sys import types import unittest import inspect import linecache import datetime from UserList import UserList from UserDict import UserDict from test.test_support import run_unittest, check_py3k_warnings with check_py3k_warnings( ("tuple parameter unpacking has been removed", SyntaxWarning), quiet=True): from test import inspect_fodder as mod from test import inspect_fodder2 as mod2 # C module for test_findsource_binary import unicodedata # Functions tested in this suite: # ismodule, isclass, ismethod, isfunction, istraceback, isframe, iscode, # isbuiltin, isroutine, isgenerator, isgeneratorfunction, getmembers, # getdoc, getfile, getmodule, getsourcefile, getcomments, getsource, # getclasstree, getargspec, getargvalues, formatargspec, formatargvalues, # currentframe, stack, trace, isdatadescriptor # NOTE: There are some additional tests relating to interaction with # zipimport in the test_zipimport_support test module. modfile = mod.__file__
def test_type_inequality_comparisons(self): expected = 'type inequality comparisons not supported in 3.x' with check_py3k_warnings() as w: self.assertWarning(int < str, w, expected) w.reset() self.assertWarning(type < object, w, expected)
def test_misc(self): # check the extremes in int<->long conversion hugepos = sys.maxint hugeneg = -hugepos - 1 hugepos_aslong = long(hugepos) hugeneg_aslong = long(hugeneg) self.assertEqual(hugepos, hugepos_aslong, "long(sys.maxint) != sys.maxint") self.assertEqual(hugeneg, hugeneg_aslong, "long(-sys.maxint-1) != -sys.maxint-1") # long -> int should not fail for hugepos_aslong or hugeneg_aslong x = int(hugepos_aslong) try: self.assertEqual( x, hugepos, "converting sys.maxint to long and back to int fails") except OverflowError: self.fail("int(long(sys.maxint)) overflowed!") if not isinstance(x, int): self.fail("int(long(sys.maxint)) should have returned int") x = int(hugeneg_aslong) try: self.assertEqual( x, hugeneg, "converting -sys.maxint-1 to long and back to int fails") except OverflowError: self.fail("int(long(-sys.maxint-1)) overflowed!") if not isinstance(x, int): self.fail("int(long(-sys.maxint-1)) should have returned int") # but long -> int should overflow for hugepos+1 and hugeneg-1 x = hugepos_aslong + 1 try: y = int(x) except OverflowError: self.fail("int(long(sys.maxint) + 1) mustn't overflow") self.assertIsInstance( y, long, "int(long(sys.maxint) + 1) should have returned long") x = hugeneg_aslong - 1 try: y = int(x) except OverflowError: self.fail("int(long(-sys.maxint-1) - 1) mustn't overflow") self.assertIsInstance( y, long, "int(long(-sys.maxint-1) - 1) should have returned long") class long2(long): pass x = long2(1L << 100) y = int(x) self.assertIs( type(y), long, "overflowing int conversion must return long not long subtype") # long -> Py_ssize_t conversion class X(object): def __getslice__(self, i, j): return i, j with test_support.check_py3k_warnings(): self.assertEqual(X()[-5L:7L], (-5, 7)) # use the clamping effect to test the smallest and largest longs # that fit a Py_ssize_t slicemin, slicemax = X()[-2L**100:2L**100] self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax))
def check(s): with check_py3k_warnings((expected, SyntaxWarning)): exec s in {}
def test_backquote(self): expected = 'backquote not supported in 3.x; use repr()' with check_py3k_warnings((expected, SyntaxWarning)): exec "`2`" in {}
def test_nonascii_bytes_literals(self): expected = "non-ascii bytes literals not supported in 3.x" with check_py3k_warnings((expected, SyntaxWarning)): exec "b'\xbd'"
def test_buffer(self): expected = 'buffer() not supported in 3.x' with check_py3k_warnings() as w: self.assertWarning(buffer('a'), w, expected)
def test_main(): with check_py3k_warnings( ("exceptions must derive from BaseException", DeprecationWarning), ("catching classes that don't inherit " "from BaseException is not allowed", DeprecationWarning)): run_unittest(OpcodeTest)
def test_basics(self): c = Counter('abcaba') self.assertEqual(c, Counter({'a': 3, 'b': 2, 'c': 1})) self.assertEqual(c, Counter(a=3, b=2, c=1)) self.assertIsInstance(c, dict) self.assertIsInstance(c, Mapping) self.assertTrue(issubclass(Counter, dict)) self.assertTrue(issubclass(Counter, Mapping)) self.assertEqual(len(c), 3) self.assertEqual(sum(c.values()), 6) self.assertEqual(sorted(c.values()), [1, 2, 3]) self.assertEqual(sorted(c.keys()), ['a', 'b', 'c']) self.assertEqual(sorted(c), ['a', 'b', 'c']) self.assertEqual(sorted(c.items()), [('a', 3), ('b', 2), ('c', 1)]) self.assertEqual(c['b'], 2) self.assertEqual(c['z'], 0) with test_support.check_py3k_warnings(): self.assertEqual(c.has_key('c'), True) self.assertEqual(c.has_key('z'), False) self.assertEqual(c.__contains__('c'), True) self.assertEqual(c.__contains__('z'), False) self.assertEqual(c.get('b', 10), 2) self.assertEqual(c.get('z', 10), 10) self.assertEqual(c, dict(a=3, b=2, c=1)) self.assertEqual(repr(c), "Counter({'a': 3, 'b': 2, 'c': 1})") self.assertEqual(c.most_common(), [('a', 3), ('b', 2), ('c', 1)]) for i in range(5): self.assertEqual(c.most_common(i), [('a', 3), ('b', 2), ('c', 1)][:i]) self.assertEqual(''.join(sorted(c.elements())), 'aaabbc') c['a'] += 1 # increment an existing value c['b'] -= 2 # sub existing value to zero del c['c'] # remove an entry del c['c'] # make sure that del doesn't raise KeyError c['d'] -= 2 # sub from a missing value c['e'] = -5 # directly assign a missing value c['f'] += 4 # add to a missing value self.assertEqual(c, dict(a=4, b=0, d=-2, e=-5, f=4)) self.assertEqual(''.join(sorted(c.elements())), 'aaaaffff') self.assertEqual(c.pop('f'), 4) self.assertNotIn('f', c) for i in range(3): elem, cnt = c.popitem() self.assertNotIn(elem, c) c.clear() self.assertEqual(c, {}) self.assertEqual(repr(c), 'Counter()') self.assertRaises(NotImplementedError, Counter.fromkeys, 'abc') self.assertRaises(TypeError, hash, c) c.update(dict(a=5, b=3)) c.update(c=1) c.update(Counter('a' * 50 + 'b' * 30)) c.update() # test case with no args c.__init__('a' * 500 + 'b' * 300) c.__init__('cdc') c.__init__() self.assertEqual(c, dict(a=555, b=333, c=3, d=1)) self.assertEqual(c.setdefault('d', 5), 1) self.assertEqual(c['d'], 1) self.assertEqual(c.setdefault('e', 5), 5) self.assertEqual(c['e'], 5)
def test_main(): with check_py3k_warnings(("buffer.. not supported", DeprecationWarning), ("classic long division", DeprecationWarning)): run_unittest(TypesTests)
def test_tuple_parameter_unpacking(self): expected = "tuple parameter unpacking has been removed in 3.x" with check_py3k_warnings((expected, SyntaxWarning)): exec "def f((a, b)): pass"
def test_main(): with test_support.check_py3k_warnings( (".+__(get|set|del)slice__ has been removed", DeprecationWarning), ("classic int division", DeprecationWarning), ("<> not supported", DeprecationWarning)): test_support.run_unittest(ClassTests)
def test_object_inequality_comparisons(self): expected = 'comparing unequal types not supported in 3.x' with check_py3k_warnings() as w: self.assertWarning(str < [], w, expected) w.reset() self.assertWarning(object() < (1, 2), w, expected)
def test_Set_interoperability_with_real_sets(self): # Issue: 8743 class ListSet(Set): def __init__(self, elements=()): self.data = [] for elem in elements: if elem not in self.data: self.data.append(elem) def __contains__(self, elem): return elem in self.data def __iter__(self): return iter(self.data) def __len__(self): return len(self.data) def __repr__(self): return 'Set({!r})'.format(self.data) r1 = set('abc') r2 = set('bcd') r3 = set('abcde') f1 = ListSet('abc') f2 = ListSet('bcd') f3 = ListSet('abcde') l1 = list('abccba') l2 = list('bcddcb') l3 = list('abcdeedcba') p1 = sets.Set('abc') p2 = sets.Set('bcd') p3 = sets.Set('abcde') target = r1 & r2 self.assertSameSet(f1 & f2, target) self.assertSameSet(f1 & r2, target) self.assertSameSet(r2 & f1, target) self.assertSameSet(f1 & p2, target) self.assertSameSet(p2 & f1, target) self.assertSameSet(f1 & l2, target) target = r1 | r2 self.assertSameSet(f1 | f2, target) self.assertSameSet(f1 | r2, target) self.assertSameSet(r2 | f1, target) self.assertSameSet(f1 | p2, target) self.assertSameSet(p2 | f1, target) self.assertSameSet(f1 | l2, target) fwd_target = r1 - r2 rev_target = r2 - r1 self.assertSameSet(f1 - f2, fwd_target) self.assertSameSet(f2 - f1, rev_target) self.assertSameSet(f1 - r2, fwd_target) self.assertSameSet(f2 - r1, rev_target) self.assertSameSet(r1 - f2, fwd_target) self.assertSameSet(r2 - f1, rev_target) self.assertSameSet(f1 - p2, fwd_target) self.assertSameSet(f2 - p1, rev_target) self.assertSameSet(p1 - f2, fwd_target) self.assertSameSet(p2 - f1, rev_target) self.assertSameSet(f1 - l2, fwd_target) self.assertSameSet(f2 - l1, rev_target) target = r1 ^ r2 self.assertSameSet(f1 ^ f2, target) self.assertSameSet(f1 ^ r2, target) self.assertSameSet(r2 ^ f1, target) self.assertSameSet(f1 ^ p2, target) self.assertSameSet(p2 ^ f1, target) self.assertSameSet(f1 ^ l2, target) # proper subset self.assertTrue(f1 < f3) self.assertFalse(f1 < f1) self.assertFalse(f1 < f2) self.assertTrue(r1 < f3) self.assertFalse(r1 < f1) self.assertFalse(r1 < f2) self.assertTrue(r1 < r3) self.assertFalse(r1 < r1) self.assertFalse(r1 < r2) with test_support.check_py3k_warnings(): # python 2 only, cross-type compares will succeed f1 < l3 f1 < l1 f1 < l2 # any subset self.assertTrue(f1 <= f3) self.assertTrue(f1 <= f1) self.assertFalse(f1 <= f2) self.assertTrue(r1 <= f3) self.assertTrue(r1 <= f1) self.assertFalse(r1 <= f2) self.assertTrue(r1 <= r3) self.assertTrue(r1 <= r1) self.assertFalse(r1 <= r2) with test_support.check_py3k_warnings(): # python 2 only, cross-type compares will succeed f1 <= l3 f1 <= l1 f1 <= l2 # proper superset self.assertTrue(f3 > f1) self.assertFalse(f1 > f1) self.assertFalse(f2 > f1) self.assertTrue(r3 > r1) self.assertFalse(f1 > r1) self.assertFalse(f2 > r1) self.assertTrue(r3 > r1) self.assertFalse(r1 > r1) self.assertFalse(r2 > r1) with test_support.check_py3k_warnings(): # python 2 only, cross-type compares will succeed f1 > l3 f1 > l1 f1 > l2 # any superset self.assertTrue(f3 >= f1) self.assertTrue(f1 >= f1) self.assertFalse(f2 >= f1) self.assertTrue(r3 >= r1) self.assertTrue(f1 >= r1) self.assertFalse(f2 >= r1) self.assertTrue(r3 >= r1) self.assertTrue(r1 >= r1) self.assertFalse(r2 >= r1) with test_support.check_py3k_warnings(): # python 2 only, cross-type compares will succeed f1 >= l3 f1 >= l1 f1 >= l2 # equality self.assertTrue(f1 == f1) self.assertTrue(r1 == f1) self.assertTrue(f1 == r1) self.assertFalse(f1 == f3) self.assertFalse(r1 == f3) self.assertFalse(f1 == r3) # python 2 only, cross-type compares will succeed f1 == l3 f1 == l1 f1 == l2 # inequality self.assertFalse(f1 != f1) self.assertFalse(r1 != f1) self.assertFalse(f1 != r1) self.assertTrue(f1 != f3) self.assertTrue(r1 != f3) self.assertTrue(f1 != r3) # python 2 only, cross-type compares will succeed f1 != l3 f1 != l1 f1 != l2
def test_all(self): # Test constructors u = UserDict.UserDict() u0 = UserDict.UserDict(d0) u1 = UserDict.UserDict(d1) u2 = UserDict.IterableUserDict(d2) uu = UserDict.UserDict(u) uu0 = UserDict.UserDict(u0) uu1 = UserDict.UserDict(u1) uu2 = UserDict.UserDict(u2) # keyword arg constructor self.assertEqual(UserDict.UserDict(one=1, two=2), d2) # item sequence constructor self.assertEqual(UserDict.UserDict([('one', 1), ('two', 2)]), d2) with test_support.check_warnings( (".*'dict'.*", PendingDeprecationWarning)): self.assertEqual(UserDict.UserDict(dict=[('one', 1), ('two', 2)]), d2) # both together self.assertEqual( UserDict.UserDict([('one', 1), ('two', 2)], two=3, three=5), d3) # alternate constructor self.assertEqual(UserDict.UserDict.fromkeys('one two'.split()), d4) self.assertEqual(UserDict.UserDict().fromkeys('one two'.split()), d4) self.assertEqual(UserDict.UserDict.fromkeys('one two'.split(), 1), d5) self.assertEqual(UserDict.UserDict().fromkeys('one two'.split(), 1), d5) self.assertTrue(u1.fromkeys('one two'.split()) is not u1) self.assertIsInstance(u1.fromkeys('one two'.split()), UserDict.UserDict) self.assertIsInstance(u2.fromkeys('one two'.split()), UserDict.IterableUserDict) # Test __repr__ self.assertEqual(str(u0), str(d0)) self.assertEqual(repr(u1), repr(d1)) self.assertEqual(repr(u2), repr(d2)) # Test __cmp__ and __len__ all = [d0, d1, d2, u, u0, u1, u2, uu, uu0, uu1, uu2] for a in all: for b in all: self.assertEqual(cmp(a, b), cmp(len(a), len(b))) # Test __getitem__ self.assertEqual(u2["one"], 1) self.assertRaises(KeyError, u1.__getitem__, "two") # Test __setitem__ u3 = UserDict.UserDict(u2) u3["two"] = 2 u3["three"] = 3 # Test __delitem__ del u3["three"] self.assertRaises(KeyError, u3.__delitem__, "three") # Test clear u3.clear() self.assertEqual(u3, {}) # Test copy() u2a = u2.copy() self.assertEqual(u2a, u2) u2b = UserDict.UserDict(x=42, y=23) u2c = u2b.copy() # making a copy of a UserDict is special cased self.assertEqual(u2b, u2c) class MyUserDict(UserDict.UserDict): def display(self): print self m2 = MyUserDict(u2) m2a = m2.copy() self.assertEqual(m2a, m2) # SF bug #476616 -- copy() of UserDict subclass shared data m2['foo'] = 'bar' self.assertNotEqual(m2a, m2) # Test keys, items, values self.assertEqual(u2.keys(), d2.keys()) self.assertEqual(u2.items(), d2.items()) self.assertEqual(u2.values(), d2.values()) # Test has_key and "in". for i in u2.keys(): self.assertIn(i, u2) self.assertEqual(i in u1, i in d1) self.assertEqual(i in u0, i in d0) with test_support.check_py3k_warnings(): self.assertTrue(u2.has_key(i)) self.assertEqual(u1.has_key(i), d1.has_key(i)) self.assertEqual(u0.has_key(i), d0.has_key(i)) # Test update t = UserDict.UserDict() t.update(u2) self.assertEqual(t, u2) class Items: def items(self): return (("x", 42), ("y", 23)) t = UserDict.UserDict() t.update(Items()) self.assertEqual(t, {"x": 42, "y": 23}) # Test get for i in u2.keys(): self.assertEqual(u2.get(i), u2[i]) self.assertEqual(u1.get(i), d1.get(i)) self.assertEqual(u0.get(i), d0.get(i)) # Test "in" iteration. for i in xrange(20): u2[i] = str(i) ikeys = [] for k in u2: ikeys.append(k) keys = u2.keys() self.assertEqual(set(ikeys), set(keys)) # Test setdefault t = UserDict.UserDict() self.assertEqual(t.setdefault("x", 42), 42) self.assertTrue(t.has_key("x")) self.assertEqual(t.setdefault("x", 23), 42) # Test pop t = UserDict.UserDict(x=42) self.assertEqual(t.pop("x"), 42) self.assertRaises(KeyError, t.pop, "x") self.assertEqual(t.pop("x", 1), 1) t["x"] = 42 self.assertEqual(t.pop("x", 1), 42) # Test popitem t = UserDict.UserDict(x=42) self.assertEqual(t.popitem(), ("x", 42)) self.assertRaises(KeyError, t.popitem)
def test_buffer(self): for s in ["", "Andrè Previn", "abc", " " * 10000]: with test_support.check_py3k_warnings( ("buffer.. not supported", DeprecationWarning)): b = buffer(s) self.helper(b, expected=s)
def test_main(): test_support.requires('network') with test_support.check_py3k_warnings( ("urllib.urlopen.. has been removed", DeprecationWarning)): test_support.run_unittest(URLTimeoutTest, urlopenNetworkTests, urlretrieveNetworkTests, urlopen_HttpsTests)
def test_main(): test_support.run_unittest(TestStringIO, TestcStringIO) with test_support.check_py3k_warnings( ("buffer.. not supported", DeprecationWarning)): test_support.run_unittest(TestBufferStringIO, TestBuffercStringIO)
def _testRecvFromIntoArray(self): with test_support.check_py3k_warnings(): buf = buffer(MSG) self.serv_conn.send(buf)
def test_main(): with check_py3k_warnings(("classic int division", DeprecationWarning)): run_unittest(AugAssignTest)
def test_getitem(self): self._getitem_helper(object) with test_support.check_py3k_warnings(): self._getslice_helper_deprecated(object)
def test_buffer(self): a = array.array(self.typecode, self.example) with test_support.check_py3k_warnings(): b = buffer(a) self.assertEqual(b[0], a.tostring()[0])
def test_hash_inheritance(self): with check_py3k_warnings() as w: # With object as the base class class WarnOnlyCmp(object): def __cmp__(self, other): pass self.assertEqual(len(w.warnings), 0) w.reset() class WarnOnlyEq(object): def __eq__(self, other): pass self.assertEqual(len(w.warnings), 1) self.assertWarning( None, w, "Overriding __eq__ blocks inheritance of __hash__ in 3.x") w.reset() class WarnCmpAndEq(object): def __cmp__(self, other): pass def __eq__(self, other): pass self.assertEqual(len(w.warnings), 1) self.assertWarning( None, w, "Overriding __eq__ blocks inheritance of __hash__ in 3.x") w.reset() class NoWarningOnlyHash(object): def __hash__(self): pass self.assertEqual(len(w.warnings), 0) # With an intermediate class in the heirarchy class DefinesAllThree(object): def __cmp__(self, other): pass def __eq__(self, other): pass def __hash__(self): pass class WarnOnlyCmp(DefinesAllThree): def __cmp__(self, other): pass self.assertEqual(len(w.warnings), 0) w.reset() class WarnOnlyEq(DefinesAllThree): def __eq__(self, other): pass self.assertEqual(len(w.warnings), 1) self.assertWarning( None, w, "Overriding __eq__ blocks inheritance of __hash__ in 3.x") w.reset() class WarnCmpAndEq(DefinesAllThree): def __cmp__(self, other): pass def __eq__(self, other): pass self.assertEqual(len(w.warnings), 1) self.assertWarning( None, w, "Overriding __eq__ blocks inheritance of __hash__ in 3.x") w.reset() class NoWarningOnlyHash(DefinesAllThree): def __hash__(self): pass self.assertEqual(len(w.warnings), 0)
def test_file_xreadlines(self): expected = ("f.xreadlines() not supported in 3.x, " "try 'for line in f' instead") with file(__file__) as f: with check_py3k_warnings() as w: self.assertWarning(f.xreadlines(), w, expected)