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

        L = UserList.UserList()
        p = weakref.proxy(L)
        self.failIf(p, "proxy for empty UserList should be false")
        p.append(12)
        self.assertEqual(len(L), 1)
        self.failUnless(p, "proxy for non-empty UserList should be true")
        with test_support._check_py3k_warnings():
            p[:] = [2, 3]
        self.assertEqual(len(L), 2)
        self.assertEqual(len(p), 2)
        self.failUnless(3 in 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])
예제 #2
0
    def test_basic_proxy(self):
        o = C()
        self.check_proxy(o, weakref.proxy(o))

        L = UserList.UserList()
        p = weakref.proxy(L)
        self.failIf(p, "proxy for empty UserList should be false")
        p.append(12)
        self.assertEqual(len(L), 1)
        self.failUnless(p, "proxy for non-empty UserList should be true")
        with test_support._check_py3k_warnings():
            p[:] = [2, 3]
        self.assertEqual(len(L), 2)
        self.assertEqual(len(p), 2)
        self.failUnless(3 in 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])
예제 #3
0
파일: test_iter.py 프로젝트: zeus911/9miao
    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
예제 #4
0
 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)
예제 #5
0
    def testMethods(self):
        methods = [
            'fileno', 'flush', 'isatty', 'next', 'read', 'readinto',
            'readline', 'readlines', 'seek', 'tell', 'truncate', 'write',
            'xreadlines', '__iter__'
        ]
        if sys.platform.startswith('atheos'):
            methods.remove('truncate')

        # __exit__ should close the file
        self.f.__exit__(None, None, None)
        self.assert_(self.f.closed)

        for methodname in methods:
            method = getattr(self.f, methodname)
            # should raise on closed file
            with test_support._check_py3k_warnings(quiet=True):
                self.assertRaises(ValueError, method)
        self.assertRaises(ValueError, self.f.writelines, [])

        # file is closed, __exit__ shouldn't do anything
        self.assertEquals(self.f.__exit__(None, None, None), None)
        # it must also return None if an exception was given
        try:
            1 // 0
        except:
            self.assertEquals(self.f.__exit__(*sys.exc_info()), None)
예제 #6
0
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)
예제 #7
0
파일: test_scope.py 프로젝트: redb/MNPP
    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))
예제 #8
0
 def test_socketserver(self):
     """Using a SocketServer to create and manage SSL connections."""
     server = SocketServerHTTPSServer(CERTFILE)
     flag = threading.Event()
     server.start(flag)
     # wait for it to start
     flag.wait()
     # try to connect
     try:
         if test_support.verbose:
             sys.stdout.write("\n")
         with open(CERTFILE, "rb") as f:
             d1 = f.read()
         d2 = ""
         # now fetch the same data from the HTTPS server
         url = "https://127.0.0.1:%d/%s" % (server.port, os.path.split(CERTFILE)[1])
         with test_support._check_py3k_warnings():
             f = urllib.urlopen(url)
         dlen = f.info().getheader("content-length")
         if dlen and (int(dlen) > 0):
             d2 = f.read(int(dlen))
             if test_support.verbose:
                 sys.stdout.write(" client: read %d bytes from remote server '%s'\n" % (len(d2), server))
         f.close()
         self.assertEqual(d1, d2)
     finally:
         server.stop()
         server.join()
예제 #9
0
def test_main():
    with _check_py3k_warnings(("buffer.. not supported", DeprecationWarning),
                              ("classic (int|long) division", DeprecationWarning),):
        import ctypes.test
        skipped, testcases = ctypes.test.get_tests(ctypes.test, "test_*.py", verbosity=0)
        suites = [unittest.makeSuite(t) for t in testcases]
        run_unittest(unittest.TestSuite(suites))
예제 #10
0
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)
예제 #11
0
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)
예제 #12
0
    def testMethods(self):
        methods = ['fileno', 'flush', 'isatty', 'next', 'read', 'readinto',
                   'readline', 'readlines', 'seek', 'tell', 'truncate',
                   'write', 'xreadlines', '__iter__']
        if sys.platform.startswith('atheos'):
            methods.remove('truncate')

        # __exit__ should close the file
        self.f.__exit__(None, None, None)
        self.assert_(self.f.closed)

        for methodname in methods:
            method = getattr(self.f, methodname)
            # should raise on closed file
            with test_support._check_py3k_warnings(quiet=True):
                self.assertRaises(ValueError, method)
        self.assertRaises(ValueError, self.f.writelines, [])

        # file is closed, __exit__ shouldn't do anything
        self.assertEquals(self.f.__exit__(None, None, None), None)
        # it must also return None if an exception was given
        try:
            1 // 0
        except:
            self.assertEquals(self.f.__exit__(*sys.exc_info()), None)
예제 #13
0
 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)
예제 #14
0
    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
예제 #15
0
 def test_varargs2_ext(self):
     try:
         with test_support._check_py3k_warnings():
             {}.has_key(*(1, 2))
     except TypeError:
         pass
     else:
         raise RuntimeError
예제 #16
0
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)
예제 #17
0
 def test_varargs2_ext(self):
     try:
         with test_support._check_py3k_warnings():
             {}.has_key(*(1, 2))
     except TypeError:
         pass
     else:
         raise RuntimeError
예제 #18
0
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)
예제 #19
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'])
예제 #20
0
def test_main():
    with test_support._check_py3k_warnings(
        ('dict(.has_key..| inequality comparisons) not supported in 3.x',
         DeprecationWarning)):
        test_support.run_unittest(
            DictTest,
            GeneralMappingTests,
            SubclassMappingTests,
        )
예제 #21
0
파일: test_dict.py 프로젝트: redb/MNPP
def test_main():
    with test_support._check_py3k_warnings(
        ('dict(.has_key..| inequality comparisons) not supported in 3.x',
         DeprecationWarning)):
        test_support.run_unittest(
            DictTest,
            GeneralMappingTests,
            SubclassMappingTests,
        )
예제 #22
0
    def test_setslice_without_getslice(self):
        tmp = []
        class X(object):
            def __setslice__(self, i, j, k):
                tmp.append((i, j, k))

        x = X()
        with test_support._check_py3k_warnings():
            x[1:2] = 42
        self.assertEquals(tmp, [(1, 2, 42)])
예제 #23
0
 def test_buffer(self):
     for s in ["", "Andrè Previn", "abc", " "*10000]:
         with test_support._check_py3k_warnings(("buffer.. not supported",
                                                  DeprecationWarning)):
             b = buffer(s)
         new = marshal.loads(marshal.dumps(b))
         self.assertEqual(s, new)
         marshal.dump(b, file(test_support.TESTFN, "wb"))
         new = marshal.load(file(test_support.TESTFN, "rb"))
         self.assertEqual(s, new)
     os.unlink(test_support.TESTFN)
예제 #24
0
파일: test_cgi.py 프로젝트: zeus911/9miao
 def test_weird_formcontentdict(self):
     # Test the weird FormContentDict classes
     env = {'QUERY_STRING': "x=1&y=2.0&z=2-3.%2b0&1=1abc"}
     expect = {'x': 1, 'y': 2.0, 'z': '2-3.+0', '1': '1abc'}
     d = cgi.InterpFormContentDict(env)
     for k, v in expect.items():
         self.assertEqual(d[k], v)
     for k, v in d.items():
         self.assertEqual(expect[k], v)
     with _check_py3k_warnings():
         self.assertEqual(sorted(expect.values()), sorted(d.values()))
예제 #25
0
 def test_weird_formcontentdict(self):
     # Test the weird FormContentDict classes
     env = {'QUERY_STRING': "x=1&y=2.0&z=2-3.%2b0&1=1abc"}
     expect = {'x': 1, 'y': 2.0, 'z': '2-3.+0', '1': '1abc'}
     d = cgi.InterpFormContentDict(env)
     for k, v in expect.items():
         self.assertEqual(d[k], v)
     for k, v in d.items():
         self.assertEqual(expect[k], v)
     with _check_py3k_warnings():
         self.assertEqual(sorted(expect.values()), sorted(d.values()))
예제 #26
0
    def test_unpack_with_buffer(self):
        with _check_py3k_warnings(("buffer.. not supported in 3.x",
                                  DeprecationWarning)):
            # SF bug 1563759: struct.unpack doesn't support buffer protocol objects
            data1 = array.array('B', '\x12\x34\x56\x78')
            data2 = buffer('......\x12\x34\x56\x78......', 6, 4)
            for data in [data1, data2]:
                value, = struct.unpack('>I', data)
                self.assertEqual(value, 0x12345678)

            self.test_unpack_from(cls=buffer)
예제 #27
0
 def test_buffer(self):
     for s in ["", "Andrè Previn", "abc", " " * 10000]:
         with test_support._check_py3k_warnings(
             ("buffer.. not supported", DeprecationWarning)):
             b = buffer(s)
         new = marshal.loads(marshal.dumps(b))
         self.assertEqual(s, new)
         marshal.dump(b, file(test_support.TESTFN, "wb"))
         new = marshal.load(file(test_support.TESTFN, "rb"))
         self.assertEqual(s, new)
     os.unlink(test_support.TESTFN)
예제 #28
0
 def clientRun(self, test_func):
     self.server_ready.wait()
     self.client_ready.set()
     self.clientSetUp()
     with test_support._check_py3k_warnings():
         if not callable(test_func):
             raise TypeError("test_func must be a callable function.")
     try:
         test_func()
     except Exception, strerror:
         self.queue.put(strerror)
예제 #29
0
 def clientRun(self, test_func):
     self.server_ready.wait()
     self.client_ready.set()
     self.clientSetUp()
     with test_support._check_py3k_warnings():
         if not callable(test_func):
             raise TypeError("test_func must be a callable function.")
     try:
         test_func()
     except Exception, strerror:
         self.queue.put(strerror)
예제 #30
0
def test_main():
    with _check_py3k_warnings(
        ("buffer.. not supported", DeprecationWarning),
        ("classic (int|long) division", DeprecationWarning),
    ):
        import ctypes.test
        skipped, testcases = ctypes.test.get_tests(ctypes.test,
                                                   "test_*.py",
                                                   verbosity=0)
        suites = [unittest.makeSuite(t) for t in testcases]
        run_unittest(unittest.TestSuite(suites))
예제 #31
0
파일: test_struct.py 프로젝트: redb/MNPP
    def test_unpack_with_buffer(self):
        with _check_py3k_warnings(
            ("buffer.. not supported in 3.x", DeprecationWarning)):
            # SF bug 1563759: struct.unpack doesn't support buffer protocol objects
            data1 = array.array('B', '\x12\x34\x56\x78')
            data2 = buffer('......\x12\x34\x56\x78......', 6, 4)
            for data in [data1, data2]:
                value, = struct.unpack('>I', data)
                self.assertEqual(value, 0x12345678)

            self.test_unpack_from(cls=buffer)
예제 #32
0
    def test_setslice_without_getslice(self):
        tmp = []

        class X(object):
            def __setslice__(self, i, j, k):
                tmp.append((i, j, k))

        x = X()
        with test_support._check_py3k_warnings():
            x[1:2] = 42
        self.assertEquals(tmp, [(1, 2, 42)])
예제 #33
0
 def test_repeat(self, size):
     try:
         with test_support._check_py3k_warnings():
             b = buffer("AAAA") * size
     except MemoryError:
         pass  # acceptable on 32-bit
     else:
         count = 0
         for c in b:
             self.assertEquals(c, 'A')
             count += 1
         self.assertEquals(count, size * 4)
예제 #34
0
 def test_repeat(self, size):
     try:
         with test_support._check_py3k_warnings():
             b = buffer("AAAA")*size
     except MemoryError:
         pass # acceptable on 32-bit
     else:
         count = 0
         for c in b:
             self.assertEquals(c, 'A')
             count += 1
         self.assertEquals(count, size*4)
예제 #35
0
 def test_iterable_args(self):
     for f in (self.module.nlargest, self.module.nsmallest):
         for s in ("123", "", range(1000), ('do', 1.2), xrange(2000,2200,5)):
             for g in (G, I, Ig, L, R):
                 with test_support._check_py3k_warnings(
                         ("comparing unequal types not supported",
                          DeprecationWarning), quiet=True):
                     self.assertEqual(f(2, g(s)), f(2,s))
             self.assertEqual(f(2, S(s)), [])
             self.assertRaises(TypeError, f, 2, X(s))
             self.assertRaises(TypeError, f, 2, N(s))
             self.assertRaises(ZeroDivisionError, f, 2, E(s))
예제 #36
0
 def _getitem_helper(self, base):
     class GetItem(base):
         def __len__(self):
             return maxint #cannot return long here
         def __getitem__(self, key):
             return key
         def __getslice__(self, i, j):
             return i, j
     x = GetItem()
     self.assertEqual(x[self.pos], self.pos)
     self.assertEqual(x[self.neg], self.neg)
     with test_support._check_py3k_warnings():
         self.assertEqual(x[self.neg:self.pos], (maxint+minsize, maxsize))
         self.assertEqual(x[self.neg:self.pos:1].indices(maxsize), (0, maxsize, 1))
예제 #37
0
 def test_iterable_args(self):
     for f in (self.module.nlargest, self.module.nsmallest):
         for s in ("123", "", range(1000), ('do', 1.2),
                   xrange(2000, 2200, 5)):
             for g in (G, I, Ig, L, R):
                 with test_support._check_py3k_warnings(
                     ("comparing unequal types not supported",
                      DeprecationWarning),
                         quiet=True):
                     self.assertEqual(f(2, g(s)), f(2, s))
             self.assertEqual(f(2, S(s)), [])
             self.assertRaises(TypeError, f, 2, X(s))
             self.assertRaises(TypeError, f, 2, N(s))
             self.assertRaises(ZeroDivisionError, f, 2, E(s))
예제 #38
0
파일: test_index.py 프로젝트: zeus911/9miao
 def _getitem_helper(self, base):
     class GetItem(base):
         def __len__(self):
             return maxint #cannot return long here
         def __getitem__(self, key):
             return key
         def __getslice__(self, i, j):
             return i, j
     x = GetItem()
     self.assertEqual(x[self.pos], self.pos)
     self.assertEqual(x[self.neg], self.neg)
     with test_support._check_py3k_warnings():
         self.assertEqual(x[self.neg:self.pos], (maxint+minsize, maxsize))
         self.assertEqual(x[self.neg:self.pos:1].indices(maxsize), (0, maxsize, 1))
예제 #39
0
 def testImpWrapper(self):
     i = ImpWrapper()
     sys.meta_path.append(i)
     sys.path_hooks.append(ImpWrapper)
     mnames = ("colorsys", "urlparse", "distutils.core", "compiler.misc")
     for mname in mnames:
         parent = mname.split(".")[0]
         for n in sys.modules.keys():
             if n.startswith(parent):
                 del sys.modules[n]
     with test_support._check_py3k_warnings():
         for mname in mnames:
             m = __import__(mname, globals(), locals(), ["__dummy__"])
             m.__loader__  # to make sure we actually handled the import
예제 #40
0
 def testImpWrapper(self):
     i = ImpWrapper()
     sys.meta_path.append(i)
     sys.path_hooks.append(ImpWrapper)
     mnames = ("colorsys", "urlparse", "distutils.core", "compiler.misc")
     for mname in mnames:
         parent = mname.split(".")[0]
         for n in sys.modules.keys():
             if n.startswith(parent):
                 del sys.modules[n]
     with test_support._check_py3k_warnings():
         for mname in mnames:
             m = __import__(mname, globals(), locals(), ["__dummy__"])
             m.__loader__  # to make sure we actually handled the import
예제 #41
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 test_support._check_py3k_warnings(quiet=True):
            self.assertRaises(TypeError, self.gen.jumpahead)  # needs an arg
            self.assertRaises(TypeError, self.gen.jumpahead, "ick")  # wrong type
            self.assertRaises(TypeError, self.gen.jumpahead, 2.3)  # wrong type
            self.assertRaises(TypeError, self.gen.jumpahead, 2, 3)  # too many
예제 #42
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 test_support._check_py3k_warnings(quiet=True):
            self.assertRaises(TypeError, self.gen.jumpahead)  # needs an arg
            self.assertRaises(TypeError, self.gen.jumpahead,
                              "ick")  # wrong type
            self.assertRaises(TypeError, self.gen.jumpahead, 2.3)  # wrong type
            self.assertRaises(TypeError, self.gen.jumpahead, 2, 3)  # too many
예제 #43
0
    def testAttributes(self):
        # verify expected attributes exist
        f = self.f

        f.name     # merely shouldn't blow up
        f.mode     # ditto
        f.closed   # ditto

        with test_support._check_py3k_warnings(
            ('file.softspace not supported in 3.x', DeprecationWarning)):
            softspace = f.softspace
            # 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')
예제 #44
0
    def testAttributes(self):
        # verify expected attributes exist
        f = self.f

        f.name  # merely shouldn't blow up
        f.mode  # ditto
        f.closed  # ditto

        with test_support._check_py3k_warnings(
            ('file.softspace not supported in 3.x', DeprecationWarning)):
            softspace = f.softspace
            # 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')
예제 #45
0
def test_main(verbose=None):
    import sys
    from test import test_support
    test_classes = (TestTranforms,)

    with test_support._check_py3k_warnings(
            ("backquote not supported", SyntaxWarning)):
        test_support.run_unittest(*test_classes)

        # verify reference counting
        if verbose and hasattr(sys, "gettotalrefcount"):
            import gc
            counts = [None] * 5
            for i in xrange(len(counts)):
                test_support.run_unittest(*test_classes)
                gc.collect()
                counts[i] = sys.gettotalrefcount()
            print counts
예제 #46
0
def test_main(verbose=None):
    import sys
    from test import test_support
    test_classes = (TestTranforms, )

    with test_support._check_py3k_warnings(
        ("backquote not supported", SyntaxWarning)):
        test_support.run_unittest(*test_classes)

        # verify reference counting
        if verbose and hasattr(sys, "gettotalrefcount"):
            import gc
            counts = [None] * 5
            for i in xrange(len(counts)):
                test_support.run_unittest(*test_classes)
                gc.collect()
                counts[i] = sys.gettotalrefcount()
            print counts
예제 #47
0
    def test(self):
        huge = 1L << 40000
        mhuge = -huge
        self.assertEqual(huge / huge, 1.0)
        self.assertEqual(mhuge / mhuge, 1.0)
        self.assertEqual(huge / mhuge, -1.0)
        self.assertEqual(mhuge / huge, -1.0)
        self.assertEqual(1 / huge, 0.0)
        self.assertEqual(1L / huge, 0.0)
        self.assertEqual(1 / mhuge, 0.0)
        self.assertEqual(1L / mhuge, 0.0)
        self.assertEqual((666 * huge + (huge >> 1)) / huge, 666.5)
        self.assertEqual((666 * mhuge + (mhuge >> 1)) / mhuge, 666.5)
        self.assertEqual((666 * huge + (huge >> 1)) / mhuge, -666.5)
        self.assertEqual((666 * mhuge + (mhuge >> 1)) / huge, -666.5)
        self.assertEqual(huge / (huge << 1), 0.5)
        self.assertEqual((1000000 * huge) / huge, 1000000)

        namespace = {'huge': huge, 'mhuge': mhuge}

        for overflow in [
                "float(huge)", "float(mhuge)", "huge / 1", "huge / 2L",
                "huge / -1", "huge / -2L", "mhuge / 100", "mhuge / 100L"
        ]:
            # XXX(cwinter) this test doesn't pass when converted to
            # use assertRaises.
            try:
                eval(overflow, namespace)
                self.fail("expected OverflowError from %r" % overflow)
            except OverflowError:
                pass

        for underflow in [
                "1 / huge", "2L / huge", "-1 / huge", "-2L / huge",
                "100 / mhuge", "100L / mhuge"
        ]:
            result = eval(underflow, namespace)
            self.assertEqual(result, 0.0,
                             "expected underflow to 0 from %r" % underflow)

        with _check_py3k_warnings(
            ('classic long division', DeprecationWarning)):
            for zero in ["huge / 0", "huge / 0L", "mhuge / 0", "mhuge / 0L"]:
                self.assertRaises(ZeroDivisionError, eval, zero, namespace)
예제 #48
0
def test_main(verbose=None):
    test_classes = (
        TestBase,
        TestDecorateSortUndecorate,
        TestBugs,
    )

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

        # verify reference counting
        if verbose and hasattr(sys, "gettotalrefcount"):
            import gc
            counts = [None] * 5
            for i in xrange(len(counts)):
                test_support.run_unittest(*test_classes)
                gc.collect()
                counts[i] = sys.gettotalrefcount()
            print counts
예제 #49
0
    def test(self):
        huge = 1L << 40000
        mhuge = -huge
        self.assertEqual(huge / huge, 1.0)
        self.assertEqual(mhuge / mhuge, 1.0)
        self.assertEqual(huge / mhuge, -1.0)
        self.assertEqual(mhuge / huge, -1.0)
        self.assertEqual(1 / huge, 0.0)
        self.assertEqual(1L / huge, 0.0)
        self.assertEqual(1 / mhuge, 0.0)
        self.assertEqual(1L / mhuge, 0.0)
        self.assertEqual((666 * huge + (huge >> 1)) / huge, 666.5)
        self.assertEqual((666 * mhuge + (mhuge >> 1)) / mhuge, 666.5)
        self.assertEqual((666 * huge + (huge >> 1)) / mhuge, -666.5)
        self.assertEqual((666 * mhuge + (mhuge >> 1)) / huge, -666.5)
        self.assertEqual(huge / (huge << 1), 0.5)
        self.assertEqual((1000000 * huge) / huge, 1000000)

        namespace = {'huge': huge, 'mhuge': mhuge}

        for overflow in ["float(huge)", "float(mhuge)",
                         "huge / 1", "huge / 2L", "huge / -1", "huge / -2L",
                         "mhuge / 100", "mhuge / 100L"]:
            # XXX(cwinter) this test doesn't pass when converted to
            # use assertRaises.
            try:
                eval(overflow, namespace)
                self.fail("expected OverflowError from %r" % overflow)
            except OverflowError:
                pass

        for underflow in ["1 / huge", "2L / huge", "-1 / huge", "-2L / huge",
                         "100 / mhuge", "100L / mhuge"]:
            result = eval(underflow, namespace)
            self.assertEqual(result, 0.0,
                             "expected underflow to 0 from %r" % underflow)

        with _check_py3k_warnings(('classic long division', DeprecationWarning)):
            for zero in ["huge / 0", "huge / 0L", "mhuge / 0", "mhuge / 0L"]:
                self.assertRaises(ZeroDivisionError, eval, zero, namespace)
예제 #50
0
    def test_complex_args(self):

        with test_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))
        ''')
예제 #51
0
파일: test_compile.py 프로젝트: redb/MNPP
    def test_complex_args(self):

        with test_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))
        ''')
예제 #52
0
def test_main():
    with test_support._check_py3k_warnings(
        (".+__(get|set|del)slice__ has been removed", DeprecationWarning)):
        test_support.run_unittest(UserListTest)
예제 #53
0
def test_main():
    with test_support._check_py3k_warnings(("backquote not supported",
                                             SyntaxWarning)):
        test_support.run_unittest(AST_Tests, ASTHelpers_Test)
예제 #54
0
 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])
예제 #55
0
파일: test_long.py 프로젝트: redb/MNPP
    def test_auto_overflow(self):
        import math, sys

        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))
예제 #56
0
파일: test_long.py 프로젝트: redb/MNPP
    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.assert_(isinstance(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.assert_(isinstance(y, long),
                     "int(long(-sys.maxint-1) - 1) should have returned long")

        class long2(long):
            pass

        x = long2(1L << 100)
        y = int(x)
        self.assert_(
            type(y) is 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))
예제 #57
0
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)