Example #1
0
    def test_basic_proxy(self):
        o = C()
        self.check_proxy(o, weakref.proxy(o))

        L = collections.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 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 = collections.UserList(L)
        p2 = weakref.proxy(L2)
        self.assertEqual(p, p2)
        ## self.assertEqual(repr(L2), repr(p2))
        L3 = collections.UserList(list(range(10)))
        p3 = weakref.proxy(L3)
        with 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])
Example #2
0
    def test_auto_overflow(self):
        special = [0, 1, 2, 3, sys.maxsize-1, sys.maxsize, sys.maxsize+1]
        sqrt = int(math.sqrt(sys.maxsize))
        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 = int(x)

            expected = -longx
            got = -x
            checkit('-', x)

            for y in special:
                longy = int(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 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, int(z))
                                got = pow(x, y, z)
                                checkit('pow', x, y, '%', z)
                            else:
                                self.assertRaises(TypeError, pow, longx, longy, int(z))
Example #3
0
    def testAttributes(self):
        # verify expected attributes exist
        f = self.f
        with support.check_py3k_warnings():
            softspace = f.softspace
        f.name     # merely shouldn't blow up
        f.mode     # ditto
        f.closed   # ditto

        with 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')
Example #4
0
    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)
            # should raise on closed file
            self.assertRaises((TypeError, ValueError), method)
        with 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)
Example #5
0
    def test_builtin_map(self):
        self.assertEqual([x+1 for x in SequenceClass(5)], list(range(1, 6)))

        d = {"one": 1, "two": 2, "three": 3}
        self.assertEqual(list(map(lambda k, d=d: (k, d[k]), d)), list(d.items()))
        dkeys = list(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(list(SequenceClass(5)), list(range(5)))
            self.assertEqual(list(d), list(d.keys()))
            self.assertEqual(map(None, d,
                                       SequenceClass(5),
                                       iter(d.keys())),
                             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(list(map(len, f)), list(range(1, 21, 2)))
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass
Example #6
0
    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)
            # should raise on closed file
            self.assertRaises((TypeError, ValueError), method)
        with 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)
Example #7
0
    def test_builtin_map(self):
        self.assertEqual([x + 1 for x in SequenceClass(5)], list(range(1, 6)))

        d = {"one": 1, "two": 2, "three": 3}
        self.assertEqual(list(map(lambda k, d=d: (k, d[k]), d)),
                         list(d.items()))
        dkeys = list(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(list(SequenceClass(5)), list(range(5)))
            self.assertEqual(list(d), list(d.keys()))
            self.assertEqual(map(None, d, SequenceClass(5), iter(d.keys())),
                             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(list(map(len, f)), list(range(1, 21, 2)))
        finally:
            f.close()
            try:
                unlink(TESTFN)
            except OSError:
                pass
Example #8
0
def test_main():
    support.requires('network')
    with support.check_py3k_warnings(
            ("urllib.urlopen.. has been removed", DeprecationWarning)):
        support.run_unittest(URLTimeoutTest,
                                  urlopenNetworkTests,
                                  urlretrieveNetworkTests)
Example #9
0
    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
""", locals())
        self.assertEqual(makeAddPair((1, 2))((100, 200)), (101, 202))
Example #10
0
    def testAttributes(self):
        # verify expected attributes exist
        f = self.f
        with support.check_py3k_warnings():
            softspace = f.softspace
        f.name  # merely shouldn't blow up
        f.mode  # ditto
        f.closed  # ditto

        with 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')
Example #11
0
    def test_getargspec_sublistofone(self):
        with check_py3k_warnings(
                ("tuple parameter unpacking has been removed", SyntaxWarning),
                ("parenthesized argument names are invalid", SyntaxWarning)):
            exec('def sublistOfOne((foo,)): return 1')
            self.assertArgSpecEquals(sublistOfOne, [['foo']])

            exec('def fakeSublistOfOne((foo)): return 1')
            self.assertArgSpecEquals(fakeSublistOfOne, ['foo'])
Example #12
0
 def makeCallable(self, signature):
     """Create a function that returns its locals(), excluding the
     autogenerated '.1', '.2', etc. tuple param names (if any)."""
     with check_py3k_warnings(
         ("tuple parameter unpacking has been removed", SyntaxWarning),
         quiet=True):
         code = ("lambda %s: dict(i for i in locals().items() "
                 "if not is_tuplename(i[0]))")
         return eval(code % signature, {'is_tuplename' : self.is_tuplename})
Example #13
0
 def makeCallable(self, signature):
     """Create a function that returns its locals(), excluding the
     autogenerated '.1', '.2', etc. tuple param names (if any)."""
     with check_py3k_warnings(
         ("tuple parameter unpacking has been removed", SyntaxWarning),
         quiet=True):
         code = ("lambda %s: dict(i for i in locals().items() "
                 "if not is_tuplename(i[0]))")
         return eval(code % signature, {'is_tuplename' : self.is_tuplename})
Example #14
0
    def test_jumpahead(self):
        self.gen.seed()
        state1 = self.gen.getstate()
        self.gen.jumpahead(100)
        state2 = self.gen.getstate()  # s/b distinct from state1
        self.assertNotEqual(state1, state2)
        self.gen.jumpahead(100)
        state3 = self.gen.getstate()  # s/b distinct from state2
        self.assertNotEqual(state2, state3)

        with support.check_py3k_warnings(quiet=True):
            self.assertRaises(TypeError, self.gen.jumpahead)  # needs an arg
            self.assertRaises(TypeError, self.gen.jumpahead, 2, 3)  # too many
Example #15
0
    def test_jumpahead(self):
        self.gen.seed()
        state1 = self.gen.getstate()
        self.gen.jumpahead(100)
        state2 = self.gen.getstate()    # s/b distinct from state1
        self.assertNotEqual(state1, state2)
        self.gen.jumpahead(100)
        state3 = self.gen.getstate()    # s/b distinct from state2
        self.assertNotEqual(state2, state3)

        with support.check_py3k_warnings(quiet=True):
            self.assertRaises(TypeError, self.gen.jumpahead)  # needs an arg
            self.assertRaises(TypeError, self.gen.jumpahead, 2, 3)  # too many
Example #16
0
def test_main(verbose=None):
    test_classes = (
        TestBase,
        TestDecorateSortUndecorate,
        TestBugs,
    )

    with support.check_py3k_warnings(
        ("the cmp argument is not supported", DeprecationWarning)):
        support.run_unittest(*test_classes)

        # verify reference counting
        if verbose and hasattr(sys, "gettotalrefcount"):
            import gc
            counts = [None] * 5
            for i in range(len(counts)):
                support.run_unittest(*test_classes)
                gc.collect()
                counts[i] = sys.gettotalrefcount()
            print(counts)
Example #17
0
def test_main(verbose=None):
    test_classes = (
        TestBase,
        TestDecorateSortUndecorate,
        TestBugs,
    )

    with support.check_py3k_warnings(
            ("the cmp argument is not supported", DeprecationWarning)):
        support.run_unittest(*test_classes)

        # verify reference counting
        if verbose and hasattr(sys, "gettotalrefcount"):
            import gc
            counts = [None] * 5
            for i in range(len(counts)):
                support.run_unittest(*test_classes)
                gc.collect()
                counts[i] = sys.gettotalrefcount()
            print(counts)
    def test_getargspec(self):
        self.assertArgSpecEquals(mod.eggs, ['x', 'y'], formatted='(x, y)')

        self.assertArgSpecEquals(
            mod.spam, ['a', 'b', 'c', 'd', ['e', ['f']]], 'g', 'h',
            (3, (4, (5, ))), '(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h)')

        with check_py3k_warnings(
            ("tuple parameter unpacking has been removed", SyntaxWarning),
                quiet=True):
            exec(
                textwrap.dedent('''
                def spam_deref(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h):
                    def eggs():
                        return a + b + c + d + e + f + g + h
                    return eggs
            '''))
        self.assertArgSpecEquals(
            spam_deref, ['a', 'b', 'c', 'd', ['e', ['f']]], 'g', 'h',
            (3, (4, (5, ))), '(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h)')
Example #19
0
    def test_getargspec(self):
        self.assertArgSpecEquals(mod.eggs, ['x', 'y'], formatted = '(x, y)')

        self.assertArgSpecEquals(mod.spam,
                                 ['a', 'b', 'c', 'd', ['e', ['f']]],
                                 'g', 'h', (3, (4, (5,))),
                                 '(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h)')

        with check_py3k_warnings(("tuple parameter unpacking has been removed",
                                  SyntaxWarning),
                                 quiet=True):
            exec(textwrap.dedent('''
                def spam_deref(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h):
                    def eggs():
                        return a + b + c + d + e + f + g + h
                    return eggs
            '''))
        self.assertArgSpecEquals(spam_deref,
                                 ['a', 'b', 'c', 'd', ['e', ['f']]],
                                 'g', 'h', (3, (4, (5,))),
                                 '(a, b, c, d=3, (e, (f,))=(4, (5,)), *g, **h)')
Example #20
0
    def test_complex_args(self):

        with support.check_py3k_warnings(
                ("tuple parameter unpacking has been removed", SyntaxWarning)):
            exec(textwrap.dedent('''
        def comp_args((a, b)):
            return a,b
        self.assertEqual(comp_args((1, 2)), (1, 2))

        def comp_args((a, b)=(3, 4)):
            return a, b
        self.assertEqual(comp_args((1, 2)), (1, 2))
        self.assertEqual(comp_args(), (3, 4))

        def comp_args(a, (b, c)):
            return a, b, c
        self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))

        def comp_args(a=2, (b, c)=(3, 4)):
            return a, b, c
        self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
        self.assertEqual(comp_args(), (2, 3, 4))
        '''))
Example #21
0
    def test_complex_args(self):

        with support.check_py3k_warnings(
            ("tuple parameter unpacking has been removed", SyntaxWarning)):
            exec(
                textwrap.dedent('''
        def comp_args((a, b)):
            return a,b
        self.assertEqual(comp_args((1, 2)), (1, 2))

        def comp_args((a, b)=(3, 4)):
            return a, b
        self.assertEqual(comp_args((1, 2)), (1, 2))
        self.assertEqual(comp_args(), (3, 4))

        def comp_args(a, (b, c)):
            return a, b, c
        self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))

        def comp_args(a=2, (b, c)=(3, 4)):
            return a, b, c
        self.assertEqual(comp_args(1, (2, 3)), (1, 2, 3))
        self.assertEqual(comp_args(), (2, 3, 4))
        '''))
Example #22
0
import re
import sys
import types
import unittest
import inspect
import linecache
import datetime
import textwrap
from UserList import UserList
from UserDict import UserDict

from test.support import run_unittest, check_py3k_warnings, have_unicode

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
try:
    import unicodedata
except ImportError:
    unicodedata = None

# 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
Example #23
0
 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 support.check_py3k_warnings():
         self.assertEqual('c' in c, True)
         self.assertEqual('z' in c, 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)
Example #24
0
 def test_assign_repr(self):
     with support.check_py3k_warnings(
         ('backquote not supported', SyntaxWarning)):
         self._check_error("`1` = 1", "assign to repr")
Example #25
0
def test_main():
    support.requires('network')
    with support.check_py3k_warnings(
        ("urllib.urlopen.. has been removed", DeprecationWarning)):
        support.run_unittest(URLTimeoutTest, urlopenNetworkTests,
                             urlretrieveNetworkTests)
Example #26
0
def test_main():
    support.run_unittest(TestStringIO, TestcStringIO)
    with support.check_py3k_warnings(("buffer.. not supported",
                                             DeprecationWarning)):
        support.run_unittest(TestBufferStringIO, TestBuffercStringIO)
Example #27
0
import re
import sys
import types
import unittest
import inspect
import linecache
import datetime
from collections import UserList
from UserDict import UserDict

from test.support import run_unittest, check_py3k_warnings, is_jython

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, but note it's not C for Jython :)
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.
Example #28
0
 def test_sort(self):
     with support.check_py3k_warnings(
             ("the cmp argument is not supported", DeprecationWarning)):
         self._test_sort()
Example #29
0
def test_main():
    with support.check_py3k_warnings(
            (".+__(get|set|del)slice__ has been removed", DeprecationWarning),
            ("classic int division", DeprecationWarning),
            ("<> not supported", DeprecationWarning)):
        support.run_unittest(ClassTests)
Example #30
0
 def test_deprecated_builtin_reduce(self):
     with check_py3k_warnings():
         self._test_builtin_reduce()
Example #31
0
 def check(self, o, v):
     self.assertEqual(hasattr(o, '__call__'), v)
     with support.check_py3k_warnings():
         self.assertEqual(isinstance(o, collections.Callable), v)
Example #32
0
 def test_buffer(self):
     # XXX doesn't test buffers with no b_base or read-write buffers (see
     # bufferobject.c).  The test is fairly incomplete too.  Sigh.
     with check_py3k_warnings():
         x = buffer('foo')
     self.assertTrue(repr(x).startswith('<read-only buffer for 0x'))
Example #33
0
def test_main():
    with check_py3k_warnings(("buffer.. not supported", DeprecationWarning),
                             ("classic long division", DeprecationWarning)):
        run_unittest(TypesTests)
Example #34
0
 def test_assign_repr(self):
     with support.check_py3k_warnings(('backquote not supported',
                                       SyntaxWarning)):
         self._check_error("`1` = 1", "assign to repr")
Example #35
0
    def test_misc(self):

        # check the extremes in int<->long conversion
        hugepos = sys.maxsize
        hugeneg = -hugepos - 1
        hugepos_aslong = int(hugepos)
        hugeneg_aslong = int(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, int,
            "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, int,
               "int(long(-sys.maxint-1) - 1) should have returned long")

        class long2(long):
            pass
        x = long2(1<<100)
        y = int(x)
        self.assertTrue(isinstance(y, int),
            "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 support.check_py3k_warnings():
            self.assertEqual(X()[-5:7], (-5, 7))
            # use the clamping effect to test the smallest and largest longs
            # that fit a Py_ssize_t
            slicemin, slicemax = X()[-2**100:2**100]
            self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax))
Example #36
0
 def test_deprecated_builtin_reduce(self):
     with check_py3k_warnings():
         self._test_builtin_reduce()
Example #37
0
 def test_sort(self):
     with support.check_py3k_warnings(
         ("the cmp argument is not supported", DeprecationWarning)):
         self._test_sort()
Example #38
0
 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 support.check_py3k_warnings():
         self.assertEqual('c' in c, True)
         self.assertEqual('z' in c, 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)
Example #39
0
def test_main():
    support.run_unittest(TestStringIO, TestcStringIO)
    with support.check_py3k_warnings(
        ("buffer.. not supported", DeprecationWarning)):
        support.run_unittest(TestBufferStringIO, TestBuffercStringIO)
Example #40
0
 def test_buffer(self):
     # XXX doesn't test buffers with no b_base or read-write buffers (see
     # bufferobject.c).  The test is fairly incomplete too.  Sigh.
     with check_py3k_warnings():
         x = buffer('foo')
     self.assertTrue(repr(x).startswith('<read-only buffer for 0x'))
Example #41
0
    def test_misc(self):

        # check the extremes in int<->long conversion
        hugepos = sys.maxsize
        hugeneg = -hugepos - 1
        hugepos_aslong = int(hugepos)
        hugeneg_aslong = int(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, int, "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, int, "int(long(-sys.maxint-1) - 1) should have returned long")

        class long2(long):
            pass

        x = long2(1 << 100)
        y = int(x)
        self.assertTrue(
            isinstance(y, int),
            "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 support.check_py3k_warnings():
            self.assertEqual(X()[-5:7], (-5, 7))
            # use the clamping effect to test the smallest and largest longs
            # that fit a Py_ssize_t
            slicemin, slicemax = X()[-2**100:2**100]
            self.assertEqual(X()[slicemin:slicemax], (slicemin, slicemax))
Example #42
0
    def test_auto_overflow(self):
        special = [0, 1, 2, 3, sys.maxsize - 1, sys.maxsize, sys.maxsize + 1]
        sqrt = int(math.sqrt(sys.maxsize))
        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 = int(x)

            expected = -longx
            got = -x
            checkit('-', x)

            for y in special:
                longy = int(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 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, int(z))
                                got = pow(x, y, z)
                                checkit('pow', x, y, '%', z)
                            else:
                                self.assertRaises(TypeError, pow, longx, longy,
                                                  int(z))
Example #43
0
 def check(self, o, v):
     self.assertEqual(hasattr(o, '__call__'), v)
     with support.check_py3k_warnings():
         self.assertEqual(isinstance(o, collections.Callable), v)
Example #44
0
 def test_CheckBinary(self):
     with (test_support.check_warnings() if sys.version_info[0] >= 3 else
           test_support.check_py3k_warnings()):
         b = sqlite.Binary(
             chr(0).encode() +
             b"'" if sys.version_info[0] >= 3 else chr(0) + b"'")
Example #45
0
 def test_buffer(self):
     a = array.array(self.typecode, self.example)
     with support.check_py3k_warnings():
         b = buffer(a)
     self.assertEqual(b[0], a.tostring()[0])