PageRenderTime 33ms CodeModel.GetById 2ms app.highlight 25ms RepoModel.GetById 1ms app.codeStats 1ms

/IronPython_Main/Languages/IronPython/Tests/test_property.py

#
Python | 243 lines | 153 code | 58 blank | 32 comment | 17 complexity | 2aca4b542d9803a825d8d22a1a8ff059 MD5 | raw file
  1#####################################################################################
  2#
  3#  Copyright (c) Microsoft Corporation. All rights reserved.
  4#
  5# This source code is subject to terms and conditions of the Apache License, Version 2.0. A
  6# copy of the license can be found in the License.html file at the root of this distribution. If
  7# you cannot locate the  Apache License, Version 2.0, please send an email to
  8# ironpy@microsoft.com. By using this source code in any fashion, you are agreeing to be bound
  9# by the terms of the Apache License, Version 2.0.
 10#
 11# You must not remove this notice, or any other, from this software.
 12#
 13#
 14#####################################################################################
 15
 16from iptest.assert_util import *
 17
 18array_list_options = []
 19if is_cli or is_silverlight:
 20    array_list_options.append(System.Collections.Generic.List[int])
 21    if not is_silverlight:
 22        array_list_options.append(System.Collections.ArrayList)
 23
 24for ArrayList in array_list_options:
 25    l = ArrayList()
 26    
 27    index = l.Add(22)
 28    Assert(l[0] == 22)
 29    l[0] = 33
 30    Assert(l[0] == 33)
 31
 32import sys
 33Assert('<stdin>' in str(sys.stdin))
 34#Assert('<stdout>' in str(sys.stdout))
 35#Assert('<stderr>' in str(sys.stderr))
 36
 37
 38# getting a property from a class should return the property,
 39# getting it from an instance should do the descriptor check
 40def test_sanity():
 41    class foo(object):
 42        def myset(self, value): pass
 43        def myget(self): return "hello"
 44        prop = property(fget=myget,fset=myset)
 45
 46    AreEqual(type(foo.prop), property)
 47
 48    a = foo()
 49    AreEqual(a.prop, 'hello')
 50
 51
 52@skip("win32")
 53def test_builtinclrtype_set():
 54    # setting an instance property on a built-in type should
 55    # throw that you can't set on built-in types
 56    for ArrayList in array_list_options:
 57        def setCount():
 58            ArrayList.Count = 23
 59
 60        AssertError(AttributeError, setCount)
 61    
 62        # System.String.Empty is a read-only static field
 63        AssertError(AttributeError, setattr, System.String, "Empty", "foo")
 64
 65
 66# a class w/ a metaclass that has a property
 67# defined should hit the descriptor when getting
 68# it on the class.
 69def test_metaclass():
 70    class MyType(type):
 71        def myget(self): return 'hello'
 72        aaa = property(fget=myget)
 73
 74    class foo(object):
 75        __metaclass__ = MyType
 76
 77    AreEqual(foo.aaa, 'hello')
 78
 79
 80def test_reflected_property():
 81    # ReflectedProperty tests
 82    for ArrayList in array_list_options:
 83        alist = ArrayList()
 84        AreEqual(ArrayList.Count.__set__(None, 5), None)
 85        AssertError(TypeError, ArrayList.Count, alist, 5)
 86        AreEqual(alist.Count, 0)
 87        AreEqual(str(ArrayList.__dict__['Count']), '<property# Count on %s>' % ArrayList.__name__)
 88    
 89        def tryDelReflectedProp():
 90            del ArrayList.Count
 91
 92        AssertError(AttributeError, tryDelReflectedProp)
 93
 94    
 95@skip("win32")
 96def test_reflected_extension_property_ops():
 97    '''
 98    Test to hit IronPython.RunTime.Operations.ReflectedExtensionPropertyOps
 99    '''
100    t_list = [  (complex.__dict__['real'], 'complex', 'float', 'real'),
101                (complex.__dict__['imag'], 'complex', 'float', 'imag'),
102                ]
103    
104    for stuff, typename, returnType, propName in t_list:
105        expected = "Get: " + propName + "(self: " + typename + ") -> " + returnType + newline
106        Assert(stuff.__doc__.startswith(expected), stuff.__doc__)
107                
108                
109def test_class_doc():
110    AreEqual(object.__dict__['__class__'].__doc__, "the object's class")
111    
112def test_prop_doc_only():
113    # define a property w/ only the doc
114
115    x = property(None, None, doc = 'Holliday')
116    AreEqual(x.fget, None)
117    AreEqual(x.fset, None)
118    AreEqual(x.fdel, None)
119    AreEqual(x.__doc__, 'Holliday')
120 
121def test_member_lookup_oldclass():
122    class OldC:
123        xprop = property(lambda self: self._xprop)
124        def __init__(self):
125            self._xprop = 42
126            self.xmember = 42
127            
128    c = OldC()
129    c.__dict__['xprop'] = 43
130    c.__dict__['xmember'] = 43
131    AreEqual(c.xprop, 43)
132    AreEqual(c.xmember, 43)
133    
134    c.xprop   = 41
135    c.xmember = 41
136    AreEqual(c.xprop, 41)
137    AreEqual(c.xmember, 41)
138    AreEqual(c.__dict__['xprop'], 41)
139    AreEqual(c.__dict__['xmember'], 41)
140
141
142def test_member_lookup_newclass():
143    class NewC(object):
144        def xprop_setter(self, xprop):
145            self._xprop = xprop
146    
147        xprop = property(lambda self: self._xprop,
148                         xprop_setter)
149        
150        def __init__(self):
151            self._xprop = 42
152            self.xmember = 42
153
154    c = NewC()
155    c.__dict__['xprop'] = 43
156    c.__dict__['xmember'] = 43
157    AreEqual(c.xprop, 42)
158    AreEqual(c.xmember, 43)
159    
160    c.xprop = 41
161    c.xmember = 41
162    AreEqual(c.xprop, 41)
163    AreEqual(c.xmember, 41)
164    AreEqual(c.__dict__['xprop'], 43)
165    AreEqual(c.__dict__['xmember'], 41)
166
167
168def test_inheritance():
169    class MyProperty(property):
170        def __init__(self, *args):
171            property.__init__(self, *args)
172            
173    x = MyProperty(1,2,3)
174    
175    AreEqual(x.fget, 1)
176    AreEqual(x.fset, 2)
177    AreEqual(x.fdel, 3)
178
179
180    class MyProperty(property):
181        def __init__(self, *args):
182            property.__init__(self, *args)
183        def __get__(self, *args):
184            return 42
185        def __set__(self, inst, value):
186            inst.foo = value
187        def __delete__(self, *args):
188            inst.bar = 'baz'
189            
190    class MyClass(object):
191        x = MyProperty()
192    
193    inst = MyClass()
194    AreEqual(inst.x, 42)
195
196    inst.x = 'abc'
197    AreEqual(inst.foo, 'abc')
198    
199    del inst.x
200    AreEqual(inst.bar, 'baz')
201
202def test_property_mutation():
203    class x(object): pass
204    
205    prop = property()
206    x.foo = prop
207    inst = x()
208    for i in xrange(42):
209        prop.__init__(lambda self: i)
210        AreEqual(inst.foo, i)
211        
212
213def test_property_doc():
214    def getter(self):
215        """getter doc"""
216    
217    AreEqual(property(getter).__doc__, "getter doc")
218    AreEqual(property(None).__doc__, None)
219    AreEqual(property(None, getter, getter).__doc__, None)
220    Assert(type(property.__doc__) is str)
221    
222    def assignerror(): 
223        property.__doc__ = None
224    AssertErrorWithMessage(TypeError, "can't set attributes of built-in/extension type 'property'", assignerror)
225
226def test_class_assign():
227    """assigning to a property through the class should replace the
228       property in the class dictionary"""
229    class x(object):
230        def set(self, value):
231            AssertUnreachable()
232        prop = property(lambda x:42, set)
233    
234    x.prop = 42
235    AreEqual(x.__dict__['prop'], 42)
236
237def test_assign():
238    x = property()
239    
240    for attr in ['__doc__', 'fdel', 'fget', 'fset']:
241        AssertErrorWithMessage(TypeError, "readonly attribute", lambda : setattr(x, attr, 'abc'))
242
243run_test(__name__)