Bobby Impollonia avatar Bobby Impollonia committed 0976fe8 Merge

merging

Comments (0)

Files changed (20)

lib-python/modified-2.7.0/test/pickletester.py

         s = StringIO.StringIO("X''.")
         self.assertRaises(EOFError, self.module.load, s)
 
+    @impl_detail("no full restricted mode in pypy", pypy=False)
     def test_restricted(self):
         # issue7128: cPickle failed in restricted mode
         builtins = {self.module.__name__: self.module,

lib-python/modified-2.7.0/test/test_descr.py

                 raise MyException
 
         for name, runner, meth_impl, ok, env in specials:
-            if name == '__length_hint__':
+            if name == '__length_hint__' or name == '__sizeof__':
                 if not test_support.check_impl_detail():
                     continue
 
         except TypeError, msg:
             self.assertTrue(str(msg).find("weak reference") >= 0)
         else:
-            self.fail("weakref.ref(no) should be illegal")
+            if test_support.check_impl_detail(pypy=False):
+                self.fail("weakref.ref(no) should be illegal")
+            #else: pypy supports taking weakrefs to some more objects
         class Weak(object):
             __slots__ = ['foo', '__weakref__']
         yes = Weak()

lib-python/modified-2.7.0/test/test_isinstance.py

+# Tests some corner cases with isinstance() and issubclass().  While these
+# tests use new style classes and properties, they actually do whitebox
+# testing of error conditions uncovered when using extension types.
+
+import unittest
+from test import test_support
+import sys
+
+
+
+class TestIsInstanceExceptions(unittest.TestCase):
+    # Test to make sure that an AttributeError when accessing the instance's
+    # class's bases is masked.  This was actually a bug in Python 2.2 and
+    # 2.2.1 where the exception wasn't caught but it also wasn't being cleared
+    # (leading to an "undetected error" in the debug build).  Set up is,
+    # isinstance(inst, cls) where:
+    #
+    # - inst isn't an InstanceType
+    # - cls isn't a ClassType, a TypeType, or a TupleType
+    # - cls has a __bases__ attribute
+    # - inst has a __class__ attribute
+    # - inst.__class__ as no __bases__ attribute
+    #
+    # Sounds complicated, I know, but this mimics a situation where an
+    # extension type raises an AttributeError when its __bases__ attribute is
+    # gotten.  In that case, isinstance() should return False.
+    def test_class_has_no_bases(self):
+        class I(object):
+            def getclass(self):
+                # This must return an object that has no __bases__ attribute
+                return None
+            __class__ = property(getclass)
+
+        class C(object):
+            def getbases(self):
+                return ()
+            __bases__ = property(getbases)
+
+        self.assertEqual(False, isinstance(I(), C()))
+
+    # Like above except that inst.__class__.__bases__ raises an exception
+    # other than AttributeError
+    def test_bases_raises_other_than_attribute_error(self):
+        class E(object):
+            def getbases(self):
+                raise RuntimeError
+            __bases__ = property(getbases)
+
+        class I(object):
+            def getclass(self):
+                return E()
+            __class__ = property(getclass)
+
+        class C(object):
+            def getbases(self):
+                return ()
+            __bases__ = property(getbases)
+
+        self.assertRaises(RuntimeError, isinstance, I(), C())
+
+    # Here's a situation where getattr(cls, '__bases__') raises an exception.
+    # If that exception is not AttributeError, it should not get masked
+    def test_dont_mask_non_attribute_error(self):
+        class I: pass
+
+        class C(object):
+            def getbases(self):
+                raise RuntimeError
+            __bases__ = property(getbases)
+
+        self.assertRaises(RuntimeError, isinstance, I(), C())
+
+    # Like above, except that getattr(cls, '__bases__') raises an
+    # AttributeError, which /should/ get masked as a TypeError
+    def test_mask_attribute_error(self):
+        class I: pass
+
+        class C(object):
+            def getbases(self):
+                raise AttributeError
+            __bases__ = property(getbases)
+
+        self.assertRaises(TypeError, isinstance, I(), C())
+
+
+
+# These tests are similar to above, but tickle certain code paths in
+# issubclass() instead of isinstance() -- really PyObject_IsSubclass()
+# vs. PyObject_IsInstance().
+class TestIsSubclassExceptions(unittest.TestCase):
+    def test_dont_mask_non_attribute_error(self):
+        class C(object):
+            def getbases(self):
+                raise RuntimeError
+            __bases__ = property(getbases)
+
+        class S(C): pass
+
+        self.assertRaises(RuntimeError, issubclass, C(), S())
+
+    def test_mask_attribute_error(self):
+        class C(object):
+            def getbases(self):
+                raise AttributeError
+            __bases__ = property(getbases)
+
+        class S(C): pass
+
+        self.assertRaises(TypeError, issubclass, C(), S())
+
+    # Like above, but test the second branch, where the __bases__ of the
+    # second arg (the cls arg) is tested.  This means the first arg must
+    # return a valid __bases__, and it's okay for it to be a normal --
+    # unrelated by inheritance -- class.
+    def test_dont_mask_non_attribute_error_in_cls_arg(self):
+        class B: pass
+
+        class C(object):
+            def getbases(self):
+                raise RuntimeError
+            __bases__ = property(getbases)
+
+        self.assertRaises(RuntimeError, issubclass, B, C())
+
+    def test_mask_attribute_error_in_cls_arg(self):
+        class B: pass
+
+        class C(object):
+            def getbases(self):
+                raise AttributeError
+            __bases__ = property(getbases)
+
+        self.assertRaises(TypeError, issubclass, B, C())
+
+
+
+# meta classes for creating abstract classes and instances
+class AbstractClass(object):
+    def __init__(self, bases):
+        self.bases = bases
+
+    def getbases(self):
+        return self.bases
+    __bases__ = property(getbases)
+
+    def __call__(self):
+        return AbstractInstance(self)
+
+class AbstractInstance(object):
+    def __init__(self, klass):
+        self.klass = klass
+
+    def getclass(self):
+        return self.klass
+    __class__ = property(getclass)
+
+# abstract classes
+AbstractSuper = AbstractClass(bases=())
+
+AbstractChild = AbstractClass(bases=(AbstractSuper,))
+
+# normal classes
+class Super:
+    pass
+
+class Child(Super):
+    pass
+
+# new-style classes
+class NewSuper(object):
+    pass
+
+class NewChild(NewSuper):
+    pass
+
+
+
+class TestIsInstanceIsSubclass(unittest.TestCase):
+    # Tests to ensure that isinstance and issubclass work on abstract
+    # classes and instances.  Before the 2.2 release, TypeErrors were
+    # raised when boolean values should have been returned.  The bug was
+    # triggered by mixing 'normal' classes and instances were with
+    # 'abstract' classes and instances.  This case tries to test all
+    # combinations.
+
+    def test_isinstance_normal(self):
+        # normal instances
+        self.assertEqual(True, isinstance(Super(), Super))
+        self.assertEqual(False, isinstance(Super(), Child))
+        self.assertEqual(False, isinstance(Super(), AbstractSuper))
+        self.assertEqual(False, isinstance(Super(), AbstractChild))
+
+        self.assertEqual(True, isinstance(Child(), Super))
+        self.assertEqual(False, isinstance(Child(), AbstractSuper))
+
+    def test_isinstance_abstract(self):
+        # abstract instances
+        self.assertEqual(True, isinstance(AbstractSuper(), AbstractSuper))
+        self.assertEqual(False, isinstance(AbstractSuper(), AbstractChild))
+        self.assertEqual(False, isinstance(AbstractSuper(), Super))
+        self.assertEqual(False, isinstance(AbstractSuper(), Child))
+
+        self.assertEqual(True, isinstance(AbstractChild(), AbstractChild))
+        self.assertEqual(True, isinstance(AbstractChild(), AbstractSuper))
+        self.assertEqual(False, isinstance(AbstractChild(), Super))
+        self.assertEqual(False, isinstance(AbstractChild(), Child))
+
+    def test_subclass_normal(self):
+        # normal classes
+        self.assertEqual(True, issubclass(Super, Super))
+        self.assertEqual(False, issubclass(Super, AbstractSuper))
+        self.assertEqual(False, issubclass(Super, Child))
+
+        self.assertEqual(True, issubclass(Child, Child))
+        self.assertEqual(True, issubclass(Child, Super))
+        self.assertEqual(False, issubclass(Child, AbstractSuper))
+
+    def test_subclass_abstract(self):
+        # abstract classes
+        self.assertEqual(True, issubclass(AbstractSuper, AbstractSuper))
+        self.assertEqual(False, issubclass(AbstractSuper, AbstractChild))
+        self.assertEqual(False, issubclass(AbstractSuper, Child))
+
+        self.assertEqual(True, issubclass(AbstractChild, AbstractChild))
+        self.assertEqual(True, issubclass(AbstractChild, AbstractSuper))
+        self.assertEqual(False, issubclass(AbstractChild, Super))
+        self.assertEqual(False, issubclass(AbstractChild, Child))
+
+    def test_subclass_tuple(self):
+        # test with a tuple as the second argument classes
+        self.assertEqual(True, issubclass(Child, (Child,)))
+        self.assertEqual(True, issubclass(Child, (Super,)))
+        self.assertEqual(False, issubclass(Super, (Child,)))
+        self.assertEqual(True, issubclass(Super, (Child, Super)))
+        self.assertEqual(False, issubclass(Child, ()))
+        self.assertEqual(True, issubclass(Super, (Child, (Super,))))
+
+        self.assertEqual(True, issubclass(NewChild, (NewChild,)))
+        self.assertEqual(True, issubclass(NewChild, (NewSuper,)))
+        self.assertEqual(False, issubclass(NewSuper, (NewChild,)))
+        self.assertEqual(True, issubclass(NewSuper, (NewChild, NewSuper)))
+        self.assertEqual(False, issubclass(NewChild, ()))
+        self.assertEqual(True, issubclass(NewSuper, (NewChild, (NewSuper,))))
+
+        self.assertEqual(True, issubclass(int, (long, (float, int))))
+        if test_support.have_unicode:
+            self.assertEqual(True, issubclass(str, (unicode, (Child, NewChild, basestring))))
+
+    def test_subclass_recursion_limit(self):
+        # make sure that issubclass raises RuntimeError before the C stack is
+        # blown
+        self.assertRaises(RuntimeError, blowstack, issubclass, str, str)
+
+    def test_isinstance_recursion_limit(self):
+        # make sure that issubclass raises RuntimeError before the C stack is
+        # blown
+        self.assertRaises(RuntimeError, blowstack, isinstance, '', str)
+
+def blowstack(fxn, arg, compare_to):
+    # Make sure that calling isinstance with a deeply nested tuple for its
+    # argument will raise RuntimeError eventually.
+    tuple_arg = (compare_to,)
+
+
+    if test_support.check_impl_detail(cpython=True):
+        RECURSION_LIMIT = sys.getrecursionlimit()
+    else:
+        # on non-CPython implementations, the maximum
+        # actual recursion limit might be higher, but
+        # probably not higher than 99999
+        #
+        RECURSION_LIMIT = 99999
+
+    for cnt in xrange(RECURSION_LIMIT+5):
+        tuple_arg = (tuple_arg,)
+        fxn(arg, tuple_arg)
+
+
+def test_main():
+    test_support.run_unittest(
+        TestIsInstanceExceptions,
+        TestIsSubclassExceptions,
+        TestIsInstanceIsSubclass
+    )
+
+
+if __name__ == '__main__':
+    test_main()

pypy/interpreter/typedef.py

         Delete the value of the slot 'member' from the given 'obj'."""
         self = member
         self.typecheck(space, w_obj)
+        w_oldresult = w_obj.getslotvalue(self.index)
+        if w_oldresult is None:
+            raise OperationError(space.w_AttributeError,
+                                 space.wrap(self.name)) # XXX better message
         w_obj.setslotvalue(self.index, None)
 
 Member.typedef = TypeDef(

pypy/module/_io/interp_stringio.py

 from pypy.module._io.interp_textio import W_TextIOBase
 from pypy.module._io.interp_iobase import convert_size
 
+
 class W_StringIO(W_TextIOBase):
     def __init__(self, space):
         W_TextIOBase.__init__(self, space)
         self.pos = end
         return space.wrap(u''.join(self.buf[start:end]))
 
-    @unwrap_spec('self', ObjSpace, int)
-    def seek_w(self, space, pos):
-        if pos < 0:
+    @unwrap_spec('self', ObjSpace, int, int)
+    def seek_w(self, space, pos, mode=0):
+        self._check_closed(space)
+
+        if not 0 <= mode <= 2:
+            raise operationerrfmt(space.w_ValueError,
+                "Invalid whence (%d, should be 0, 1 or 2)", mode
+            )
+        elif mode == 0 and pos < 0:
             raise operationerrfmt(space.w_ValueError,
                 "negative seek position: %d", pos
             )
+        elif mode != 0 and pos != 0:
+            raise OperationError(space.w_IOError,
+                space.wrap("Can't do nonzero cur-relative seeks")
+            )
+
+        # XXX: this makes almost no sense, but its how CPython does it.
+        if mode == 1:
+            pos = self.pos
+        elif mode == 2:
+            pos = len(self.buf)
         self.pos = pos
+        return space.wrap(pos)
 
     @unwrap_spec('self', ObjSpace)
     def getvalue_w(self, space):
     'StringIO', W_TextIOBase.typedef,
     __new__  = generic_new_descr(W_StringIO),
     __init__ = interp2app(W_StringIO.descr_init),
-    write=interp2app(W_StringIO.write_w),
-    read=interp2app(W_StringIO.read_w),
-    seek=interp2app(W_StringIO.seek_w),
-    getvalue=interp2app(W_StringIO.getvalue_w),
+    write = interp2app(W_StringIO.write_w),
+    read = interp2app(W_StringIO.read_w),
+    seek = interp2app(W_StringIO.seek_w),
+    getvalue = interp2app(W_StringIO.getvalue_w),
     readable = interp2app(W_StringIO.readable_w),
     writable = interp2app(W_StringIO.writable_w),
     seekable = interp2app(W_StringIO.seekable_w),

pypy/module/_io/interp_textio.py

     setstate = interp2app(W_IncrementalNewlineDecoder.setstate_w),
 
     newlines = GetSetProperty(W_IncrementalNewlineDecoder.newlines_get_w),
-    )
+)
 
 class W_TextIOBase(W_IOBase):
     w_encoding = None

pypy/module/_io/test/test_stringio.py

         exc_info = raises(ValueError, sio.seek, -3)
         assert exc_info.value.args[0] == "negative seek position: -3"
 
+        raises(ValueError, sio.seek, 3, -1)
+        raises(ValueError, sio.seek, 3, -3)
+
+        sio.close()
+        raises(ValueError, sio.seek, 0)
+
+    def test_tell(self):
+        import io
+
+        s = u"1234567890"
+        sio = io.StringIO(s)
+
+        assert sio.tell() == 0
+        sio.seek(5)
+        assert sio.tell() == 5
+        sio.seek(10000)
+        assert sio.tell() == 10000
+
+        sio.close()
+        raises(ValueError, sio.tell)
+
     def test_write_error(self):
         import io
 

pypy/module/itertools/interp_itertools.py

         self.w_c = self.space.add(w_c, self.w_step)
         return w_c
 
+    def single_argument(self):
+        space = self.space
+        return (space.isinstance_w(self.w_step, space.w_int) and
+                space.eq_w(self.w_step, space.wrap(1)))
+
     def repr_w(self):
         space = self.space
         c = space.str_w(space.repr(self.w_c))
-        if (space.isinstance_w(self.w_step, space.w_int) and
-            space.eq_w(self.w_step, space.wrap(1))):
+        if self.single_argument():
             s = 'count(%s)' % (c,)
         else:
             step = space.str_w(space.repr(self.w_step))
             s = 'count(%s, %s)' % (c, step)
         return self.space.wrap(s)
 
+    def reduce_w(self):
+        space = self.space
+        if self.single_argument():
+            args_w = [self.w_c]
+        else:
+            args_w = [self.w_c, self.w_step]
+        return space.newtuple([space.gettypefor(W_Count),
+                               space.newtuple(args_w)])
 
 def check_number(space, w_obj):
     if (space.lookup(w_obj, '__add__') is None or
 
 W_Count.typedef = TypeDef(
         'count',
+        __module__ = 'itertools',
         __new__ = interp2app(W_Count___new__),
         __iter__ = interp2app(W_Count.iter_w, unwrap_spec=['self']),
         next = interp2app(W_Count.next_w, unwrap_spec=['self']),
+        __reduce__ = interp2app(W_Count.reduce_w, unwrap_spec=['self']),
         __repr__ = interp2app(W_Count.repr_w, unwrap_spec=['self']),
         __doc__ = """Make an iterator that returns consecutive integers starting
     with n.  If not specified n defaults to zero. Does not currently
 
 W_Repeat.typedef = TypeDef(
         'repeat',
+        __module__ = 'itertools',
         __new__  = interp2app(W_Repeat___new__, unwrap_spec=[ObjSpace, W_Root, W_Root, W_Root]),
         __iter__ = interp2app(W_Repeat.iter_w, unwrap_spec=['self']),
         next     = interp2app(W_Repeat.next_w, unwrap_spec=['self']),
 
 W_TakeWhile.typedef = TypeDef(
         'takewhile',
+        __module__ = 'itertools',
         __new__  = interp2app(W_TakeWhile___new__, unwrap_spec=[ObjSpace, W_Root, W_Root, W_Root]),
         __iter__ = interp2app(W_TakeWhile.iter_w, unwrap_spec=['self']),
         next     = interp2app(W_TakeWhile.next_w, unwrap_spec=['self']),
 
 W_DropWhile.typedef = TypeDef(
         'dropwhile',
+        __module__ = 'itertools',
         __new__  = interp2app(W_DropWhile___new__, unwrap_spec=[ObjSpace, W_Root, W_Root, W_Root]),
         __iter__ = interp2app(W_DropWhile.iter_w, unwrap_spec=['self']),
         next     = interp2app(W_DropWhile.next_w, unwrap_spec=['self']),
 
 W_IFilter.typedef = TypeDef(
         'ifilter',
+        __module__ = 'itertools',
         __new__  = interp2app(W_IFilter___new__, unwrap_spec=[ObjSpace, W_Root, W_Root, W_Root]),
         __iter__ = interp2app(W_IFilter.iter_w, unwrap_spec=['self']),
         next     = interp2app(W_IFilter.next_w, unwrap_spec=['self']),
 
 W_IFilterFalse.typedef = TypeDef(
         'ifilterfalse',
+        __module__ = 'itertools',
         __new__  = interp2app(W_IFilterFalse___new__, unwrap_spec=[ObjSpace, W_Root, W_Root, W_Root]),
         __iter__ = interp2app(W_IFilterFalse.iter_w, unwrap_spec=['self']),
         next     = interp2app(W_IFilterFalse.next_w, unwrap_spec=['self']),
 
 W_ISlice.typedef = TypeDef(
         'islice',
+        __module__ = 'itertools',
         __new__  = interp2app(W_ISlice___new__, unwrap_spec=[ObjSpace, W_Root, W_Root, W_Root, 'args_w']),
         __iter__ = interp2app(W_ISlice.iter_w, unwrap_spec=['self']),
         next     = interp2app(W_ISlice.next_w, unwrap_spec=['self']),
 
 W_Chain.typedef = TypeDef(
         'chain',
+        __module__ = 'itertools',
         __new__  = interp2app(W_Chain___new__, unwrap_spec=[ObjSpace, W_Root, 'args_w']),
         __iter__ = interp2app(W_Chain.iter_w, unwrap_spec=['self']),
         next     = interp2app(W_Chain.next_w, unwrap_spec=['self']),
 
 W_IMap.typedef = TypeDef(
         'imap',
+        __module__ = 'itertools',
         __new__  = interp2app(W_IMap___new__, unwrap_spec=[ObjSpace, W_Root, W_Root, 'args_w']),
         __iter__ = interp2app(W_IMap.iter_w, unwrap_spec=['self']),
         next     = interp2app(W_IMap.next_w, unwrap_spec=['self']),
 
 W_IZip.typedef = TypeDef(
         'izip',
+        __module__ = 'itertools',
         __new__  = interp2app(W_IZip___new__, unwrap_spec=[ObjSpace, W_Root, 'args_w']),
         __iter__ = interp2app(W_IZip.iter_w, unwrap_spec=['self']),
         next     = interp2app(W_IZip.next_w, unwrap_spec=['self']),
 
 W_IZipLongest.typedef = TypeDef(
         'izip_longest',
+        __module__ = 'itertools',
         __new__  = interp2app(W_IZipLongest___new__),
         __iter__ = interp2app(W_IZipLongest.iter_w, unwrap_spec=['self']),
         next     = interp2app(W_IZipLongest.next_w, unwrap_spec=['self']),
 
 W_Cycle.typedef = TypeDef(
         'cycle',
+        __module__ = 'itertools',
         __new__  = interp2app(W_Cycle___new__, unwrap_spec=[ObjSpace, W_Root, W_Root]),
         __iter__ = interp2app(W_Cycle.iter_w, unwrap_spec=['self']),
         next     = interp2app(W_Cycle.next_w, unwrap_spec=['self']),
 
 W_StarMap.typedef = TypeDef(
         'starmap',
+        __module__ = 'itertools',
         __new__  = interp2app(W_StarMap___new__, unwrap_spec=[ObjSpace, W_Root, W_Root, W_Root]),
 
         __iter__ = interp2app(W_StarMap.iter_w, unwrap_spec=['self']),
 
 W_TeeIterable.typedef = TypeDef(
         '_tee',
+        __module__ = 'itertools',
         __new__ = interp2app(W_TeeIterable___new__, unwrap_spec=[ObjSpace,
                                                                  W_Root,
                                                                  W_Root]),
 
 W_GroupBy.typedef = TypeDef(
         'groupby',
+        __module__ = 'itertools',
         __new__  = interp2app(W_GroupBy___new__, unwrap_spec=[ObjSpace, W_Root, W_Root, W_Root]),
         __iter__ = interp2app(W_GroupBy.iter_w, unwrap_spec=['self']),
         next     = interp2app(W_GroupBy.next_w, unwrap_spec=['self']),
 
 W_GroupByIterator.typedef = TypeDef(
         '_groupby',
+        __module__ = 'itertools',
         __iter__ = interp2app(W_GroupByIterator.iter_w, unwrap_spec=['self']),
         next     = interp2app(W_GroupByIterator.next_w, unwrap_spec=['self']))
 W_GroupByIterator.typedef.acceptable_as_base_class = False
 
 W_Compress.typedef = TypeDef(
     'compress',
+    __module__ = 'itertools',
     __new__ = interp2app(W_Compress__new__,
                          unwrap_spec=[ObjSpace, W_Root, W_Root, W_Root]),
     __iter__ = interp2app(W_Compress.iter_w, unwrap_spec=['self']),
 
 W_Product.typedef = TypeDef(
     'product',
+    __module__ = 'itertools',
     __new__ = interp2app(W_Product__new__),
     __iter__ = interp2app(W_Product.iter_w),
     next = interp2app(W_Product.next_w),
     return space.wrap(res)
 
 W_Combinations.typedef = TypeDef("combinations",
+    __module__ = 'itertools',
     __new__ = interp2app(W_Combinations__new__),
     __iter__ = interp2app(W_Combinations.descr__iter__),
     next = interp2app(W_Combinations.descr_next),
     return space.wrap(res)
 
 W_CombinationsWithReplacement.typedef = TypeDef("combinations_with_replacement",
+    __module__ = 'itertools',
     __new__ = interp2app(W_CombinationsWithReplacement__new__),
     __iter__ = interp2app(W_CombinationsWithReplacement.descr__iter__),
     next = interp2app(W_CombinationsWithReplacement.descr_next),
     return space.wrap(res)
 
 W_Permutations.typedef = TypeDef("permutations",
+    __module__ = 'itertools',
     __new__ = interp2app(W_Permutations__new__),
     __iter__ = interp2app(W_Permutations.descr__iter__),
     next = interp2app(W_Permutations.descr_next),

pypy/module/itertools/test/test_itertools.py

         assert type(A('', 0)) is A
         class A(itertools.combinations_with_replacement): pass
         assert type(A('', 0)) is A
+
+    def test_copy_pickle(self):
+        import itertools, copy, pickle, sys
+        for value in [42, -sys.maxint*99]:
+            for step in [1, sys.maxint*42, 5.5]:
+                expected = [value, value+step, value+2*step]
+                c = itertools.count(value, step)
+                assert list(itertools.islice(c, 3)) == expected
+                c = itertools.count(value, step)
+                c1 = copy.copy(c)
+                assert list(itertools.islice(c1, 3)) == expected
+                c2 = copy.deepcopy(c)
+                assert list(itertools.islice(c2, 3)) == expected
+                c3 = pickle.loads(pickle.dumps(c))
+                assert list(itertools.islice(c3, 3)) == expected

pypy/module/posix/__init__.py

     'fdopen'     : 'app_posix.fdopen',
     'tmpfile'    : 'app_posix.tmpfile',
     'popen'      : 'app_posix.popen',
+    'tmpnam'     : 'app_posix.tmpnam',
+    'tempnam'    : 'app_posix.tempnam',
     }
     if os.name == 'nt':
         appleveldefs.update({
         interpleveldefs['ttyname'] = 'interp_posix.ttyname'
     if hasattr(os, 'getloadavg'):
         interpleveldefs['getloadavg'] = 'interp_posix.getloadavg'
+    if hasattr(os, 'makedev'):
+        interpleveldefs['makedev'] = 'interp_posix.makedev'
+    if hasattr(os, 'major'):
+        interpleveldefs['major'] = 'interp_posix.major'
+    if hasattr(os, 'minor'):
+        interpleveldefs['minor'] = 'interp_posix.minor'
     if hasattr(os, 'mkfifo'):
         interpleveldefs['mkfifo'] = 'interp_posix.mkfifo'
     if hasattr(os, 'mknod'):

pypy/module/posix/app_posix.py

     return f
 
 
+def tmpnam():
+    """Return an absolute pathname of a file that did not exist at the
+    time the call is made."""
+    import tempfile
+    return tempfile.mktemp()
+
+def tempnam(dir=None, prefix=None):
+    """Return an absolute pathname of a file that did not exist at the
+    time the call is made.  The directory and a prefix may be specified
+    as strings; they may be omitted or None if not needed."""
+    import tempfile
+    return tempfile.mktemp('', prefix or 'tmp', dir)
+
+
 # Implement popen() for platforms which have os.fork()
 if osname == 'posix':
 

pypy/module/posix/interp_posix.py

                            space.wrap(load[2])])
 getloadavg.unwrap_spec = [ObjSpace]
 
+def makedev(space, major, minor):
+    result = os.makedev(major, minor)
+    return space.wrap(result)
+makedev.unwrap_spec = [ObjSpace, 'c_int', 'c_int']
+
+def major(space, device):
+    result = os.major(device)
+    return space.wrap(result)
+major.unwrap_spec = [ObjSpace, 'c_int']
+
+def minor(space, device):
+    result = os.minor(device)
+    return space.wrap(result)
+minor.unwrap_spec = [ObjSpace, 'c_int']
+
 def nice(space, inc):
     "Decrease the priority of process by inc and return the new priority."
     try:

pypy/module/posix/test/test_posix2.py

             cls.w_sysconf_result = space.wrap(os.sysconf(sysconf_name))
         cls.w_SIGABRT = space.wrap(signal.SIGABRT)
         cls.w_python = space.wrap(sys.executable)
+        if hasattr(os, 'major'):
+            cls.w_expected_major_12345 = space.wrap(os.major(12345))
+            cls.w_expected_minor_12345 = space.wrap(os.minor(12345))
+        cls.w_udir = space.wrap(str(udir))
 
     def setup_method(self, meth):
         if getattr(meth, 'need_sparse_files', False):
             assert type(l1) is float and l0 >= 0.0
             assert type(l2) is float and l0 >= 0.0
 
+    if hasattr(os, 'major'):
+        def test_major_minor(self):
+            os = self.posix
+            assert os.major(12345) == self.expected_major_12345
+            assert os.minor(12345) == self.expected_minor_12345
+            assert os.makedev(self.expected_major_12345,
+                              self.expected_minor_12345) == 12345
+
     if hasattr(os, 'fsync'):
         def test_fsync(self):
             os = self.posix
             assert os.WIFEXITED(status1)
             assert os.WEXITSTATUS(status1) == myprio + 3
 
+    def test_tmpfile(self):
+        os = self.posix
+        f = os.tmpfile()
+        f.write("xxx")
+        f.flush()
+        f.seek(0, 0)
+        assert isinstance(f, file)
+        assert f.read() == 'xxx'
+
+    def test_tmpnam(self):
+        import stat, os
+        s1 = os.tmpnam()
+        s2 = os.tmpnam()
+        assert s1 != s2
+        def isdir(s):
+            try:
+                return stat.S_ISDIR(os.stat(s).st_mode)
+            except OSError:
+                return -1
+        assert isdir(s1) == -1
+        assert isdir(s2) == -1
+        assert isdir(os.path.dirname(s1)) == 1
+        assert isdir(os.path.dirname(s2)) == 1
+
+    def test_tempnam(self):
+        import stat, os
+        for dir in [None, self.udir]:
+            for prefix in [None, 'foobar']:
+                s1 = os.tempnam(dir, prefix)
+                s2 = os.tempnam(dir, prefix)
+                assert s1 != s2
+                def isdir(s):
+                    try:
+                        return stat.S_ISDIR(os.stat(s).st_mode)
+                    except OSError:
+                        return -1
+                assert isdir(s1) == -1
+                assert isdir(s2) == -1
+                assert isdir(os.path.dirname(s1)) == 1
+                assert isdir(os.path.dirname(s2)) == 1
+                if dir:
+                    assert os.path.dirname(s1) == dir
+                    assert os.path.dirname(s2) == dir
+                assert os.path.basename(s1).startswith(prefix or 'tmp')
+                assert os.path.basename(s2).startswith(prefix or 'tmp')
+
 
 class AppTestEnvironment(object):
     def setup_class(cls): 
             res = os.system(cmd)
             assert res == 0
 
-    def test_tmpfile(self):
-        os = self.os
-        f = os.tmpfile()
-        f.write("xxx")
-        f.flush()
-        f.seek(0, 0)
-        assert isinstance(f, file)
-        assert f.read() == 'xxx'
-
 class AppTestPosixUnicode:
 
     def setup_class(cls):

pypy/objspace/std/complexobject.py

 def repr__Complex(space, w_complex):
     if w_complex.realval == 0 and copysign(1., w_complex.realval) == 1.:
         return space.wrap(repr_format(w_complex.imagval) + 'j')
-    sign = (copysign(1., w_complex.imagval) == 1.) and '+' or ''
+    sign = (copysign(1., w_complex.imagval) == 1. or
+            isnan(w_complex.imagval)) and '+' or ''
     return space.wrap('(' + repr_format(w_complex.realval)
                       + sign + repr_format(w_complex.imagval) + 'j)')
 
 def str__Complex(space, w_complex):
     if w_complex.realval == 0 and copysign(1., w_complex.realval) == 1.:
         return space.wrap(str_format(w_complex.imagval) + 'j')
-    sign = (copysign(1., w_complex.imagval) == 1.) and '+' or ''
+    sign = (copysign(1., w_complex.imagval) == 1. or
+            isnan(w_complex.imagval)) and '+' or ''
     return space.wrap('(' + str_format(w_complex.realval)
                       + sign + str_format(w_complex.imagval) + 'j)')
 

pypy/objspace/std/dictmultiobject.py

             w_missing = space.lookup(w_dict, "__missing__")
             if w_missing is None:
                 return None
-            return space.call_function(w_missing, w_dict, w_key)
+            return space.get_and_call_function(w_missing, w_dict, w_key)
         else:
             return None
 

pypy/objspace/std/test/test_complexobject.py

         assert repr(complex(-0.0, -0.0)) == '(-0-0j)'
         assert repr(complex(1e45)) == "(" + repr(1e45) + "+0j)"
         assert repr(complex(1e200*1e200)) == '(inf+0j)'
+        assert repr(complex(1,-float("nan"))) == '(1+nanj)'
 
     def test_neg(self):
         h = self.helper

pypy/objspace/std/test/test_dictmultiobject.py

         iterable = {}
         raises(TypeError, len, iter(iterable))
 
+    def test_missing(self):
+        class X(dict):
+            def __missing__(self, x):
+                assert x == 'hi'
+                return 42
+        assert X()['hi'] == 42
+
+    def test_missing_more(self):
+        def missing(self, x):
+            assert x == 'hi'
+            return 42
+        class SpecialDescr(object):
+            def __init__(self, impl):
+                self.impl = impl
+            def __get__(self, obj, owner):
+                return self.impl.__get__(obj, owner)
+        class X(dict):
+            __missing__ = SpecialDescr(missing)
+        assert X()['hi'] == 42
+
+
 class AppTest_DictMultiObject(AppTest_DictObject):
 
     def test_emptydict_unhashable(self):

pypy/objspace/std/test/test_typeobject.py

             __slots__ = ('x',)
         a = A()
         raises(AttributeError, getattr, a, 'x')
+        raises(AttributeError, delattr, a, 'x')
         a.x = 1
         assert a.x == 1
         assert A.__dict__['x'].__get__(a) == 1
         del a.x
         raises(AttributeError, getattr, a, 'x')
+        raises(AttributeError, delattr, a, 'x')
         class B(A):
             pass
         b = B()
         raises(AttributeError, getattr, b, 'x')
+        raises(AttributeError, delattr, b, 'x')
         b.x = 1
         assert b.x == 1
         assert A.__dict__['x'].__get__(b) == 1
         del b.x
         raises(AttributeError, getattr, b, 'x')
+        raises(AttributeError, delattr, b, 'x')
         class Z(object):
             pass
         z = Z()

pypy/rpython/module/ll_os.py

         return extdef([], (float, float, float),
                       "ll_os.ll_getloadavg", llimpl=getloadavg_llimpl)
 
+    @registering_if(os, 'makedev')
+    def register_os_makedev(self):
+        c_makedev = self.llexternal('makedev', [rffi.INT, rffi.INT], rffi.INT)
+        def makedev_llimpl(maj, min):
+            return c_makedev(maj, min)
+        return extdef([int, int], int,
+                      "ll_os.ll_makedev", llimpl=makedev_llimpl)
+
+    @registering_if(os, 'major')
+    def register_os_major(self):
+        c_major = self.llexternal('major', [rffi.INT], rffi.INT)
+        def major_llimpl(dev):
+            return c_major(dev)
+        return extdef([int], int,
+                      "ll_os.ll_major", llimpl=major_llimpl)
+
+    @registering_if(os, 'minor')
+    def register_os_minor(self):
+        c_minor = self.llexternal('minor', [rffi.INT], rffi.INT)
+        def minor_llimpl(dev):
+            return c_minor(dev)
+        return extdef([int], int,
+                      "ll_os.ll_minor", llimpl=minor_llimpl)
+
 # ------------------------------- os.read -------------------------------
 
     @registering(os.read)

pypy/translator/c/test/test_extfunc.py

         res = f()
         assert type(res) is float and res >= 0.0
 
+if hasattr(os, 'major'):
+    def test_os_major_minor():
+        def does_stuff(n):
+            a = os.major(n)
+            b = os.minor(n)
+            x = os.makedev(a, b)
+            return '%d,%d,%d' % (a, b, x)
+        f = compile(does_stuff, [int])
+        res = f(12345)
+        assert res == '%d,%d,12345' % (os.major(12345), os.minor(12345))
+
 if hasattr(os, 'fchdir'):
     def test_os_fchdir():
         def does_stuff():
Tip: Filter by directory path e.g. /media app.js to search for public/media/app.js.
Tip: Use camelCasing e.g. ProjME to search for ProjectModifiedEvent.java.
Tip: Filter by extension type e.g. /repo .js to search for all .js files in the /repo directory.
Tip: Separate your search with spaces e.g. /ssh pom.xml to search for src/ssh/pom.xml.
Tip: Use ↑ and ↓ arrow keys to navigate and return to view the file.
Tip: You can also navigate files with Ctrl+j (next) and Ctrl+k (previous) and view the file with Ctrl+o.
Tip: You can also navigate files with Alt+j (next) and Alt+k (previous) and view the file with Alt+o.