Ticket #5385: patch_5385.patch

File patch_5385.patch, 18.8 KB (added by moijes12, 4 years ago)
  • twisted/test/test_compat.py

     
    8282    def testIsinstance(self):
    8383        self.assert_(isinstance(u'hi', types.StringTypes))
    8484        self.assert_(isinstance(self, unittest.TestCase))
    85         # I'm pretty sure it's impossible to implement this
    86         # without replacing isinstance on 2.2 as well :(
    87         # self.assert_(isinstance({}, dict))
     85        self.assert_(isinstance({}, dict))
    8886
    8987    def testStrip(self):
    9088        self.assertEqual(' x '.lstrip(' '), 'x ')
  • twisted/test/test_reflect.py

     
    1717from twisted.python import reflect, util
    1818from twisted.python.versions import Version
    1919
    20 
    21 
    22 class SettableTest(unittest.TestCase):
    23     def setUp(self):
    24         self.setter = reflect.Settable()
    25 
    26     def tearDown(self):
    27         del self.setter
    28 
    29     def testSet(self):
    30         self.setter(a=1, b=2)
    31         self.assertEqual(self.setter.a, 1)
    32         self.assertEqual(self.setter.b, 2)
    33 
    34 
    35 
    36 class AccessorTester(reflect.Accessor):
    37 
    38     def set_x(self, x):
    39         self.y = x
    40         self.reallySet('x', x)
    41 
    42 
    43     def get_z(self):
    44         self.q = 1
    45         return 1
    46 
    47 
    48     def del_z(self):
    49         self.reallyDel("q")
    50 
    51 
    52 
    53 class PropertyAccessorTester(reflect.PropertyAccessor):
    54     """
    55     Test class to check L{reflect.PropertyAccessor} functionalities.
    56     """
    57     r = 0
    58 
    59     def set_r(self, r):
    60         self.s = r
    61 
    62 
    63     def set_x(self, x):
    64         self.y = x
    65         self.reallySet('x', x)
    66 
    67 
    68     def get_z(self):
    69         self.q = 1
    70         return 1
    71 
    72 
    73     def del_z(self):
    74         self.reallyDel("q")
    75 
    76 
    77 
    78 class AccessorTest(unittest.TestCase):
    79     def setUp(self):
    80         self.tester = AccessorTester()
    81 
    82     def testSet(self):
    83         self.tester.x = 1
    84         self.assertEqual(self.tester.x, 1)
    85         self.assertEqual(self.tester.y, 1)
    86 
    87     def testGet(self):
    88         self.assertEqual(self.tester.z, 1)
    89         self.assertEqual(self.tester.q, 1)
    90 
    91     def testDel(self):
    92         self.tester.z
    93         self.assertEqual(self.tester.q, 1)
    94         del self.tester.z
    95         self.assertEqual(hasattr(self.tester, "q"), 0)
    96         self.tester.x = 1
    97         del self.tester.x
    98         self.assertEqual(hasattr(self.tester, "x"), 0)
    99 
    100 
    101 
    102 class PropertyAccessorTest(AccessorTest):
    103     """
    104     Tests for L{reflect.PropertyAccessor}, using L{PropertyAccessorTester}.
    105     """
    106 
    107     def setUp(self):
    108         self.tester = PropertyAccessorTester()
    109 
    110 
    111     def test_setWithDefaultValue(self):
    112         """
    113         If an attribute is present in the class, it can be retrieved by
    114         default.
    115         """
    116         self.assertEqual(self.tester.r, 0)
    117         self.tester.r = 1
    118         self.assertEqual(self.tester.r, 0)
    119         self.assertEqual(self.tester.s, 1)
    120 
    121 
    122     def test_getValueInDict(self):
    123         """
    124         The attribute value can be overriden by directly modifying the value in
    125         C{__dict__}.
    126         """
    127         self.tester.__dict__["r"] = 10
    128         self.assertEqual(self.tester.r, 10)
    129 
    130 
    131     def test_notYetInDict(self):
    132         """
    133         If a getter is defined on an attribute but without any default value,
    134         it raises C{AttributeError} when trying to access it.
    135         """
    136         self.assertRaises(AttributeError, getattr, self.tester, "x")
    137 
    138 
    139 
    14020class LookupsTestCase(unittest.TestCase):
    14121    """
    14222    Tests for L{namedClass}, L{namedModule}, and L{namedAny}.
     
    14727        L{namedClass} should return the class object for the name it is passed.
    14828        """
    14929        self.assertIdentical(
    150             reflect.namedClass("twisted.python.reflect.Summer"),
    151             reflect.Summer)
     30            reflect.namedClass("twisted.python.reflect.QueueMethod"),
     31            reflect.QueueMethod)
    15232
    15333
    15434    def test_namedModuleLookup(self):
     
    18161        L{namedAny} should return the class object for the name it is passed.
    18262        """
    18363        self.assertIdentical(
    184             reflect.namedAny("twisted.python.reflect.Summer"), reflect.Summer)
     64            reflect.namedAny("twisted.python.reflect.QueueMethod"), reflect.QueueMethod)
    18565
    18666
    18767    def test_namedAnyAttributeLookup(self):
     
    19373        # object every time.  This is a foolishness of Python's object
    19474        # implementation, not a bug in Twisted.
    19575        self.assertEqual(
    196             reflect.namedAny("twisted.python.reflect.Summer.reallySet"),
    197             reflect.Summer.reallySet)
     76            reflect.namedAny("twisted.python.reflect.QueueMethod.reallySet"),
     77            reflect.QueueMethod.reallySet)
    19878
    19979
    20080    def test_namedAnySecondAttributeLookup(self):
     
    20585        """
    20686        self.assertIdentical(
    20787            reflect.namedAny(
    208                 "twisted.python.reflect.Summer.reallySet.__doc__"),
    209             reflect.Summer.reallySet.__doc__)
     88                "twisted.python.reflect.QueueMethod.reallySet.__doc__"),
     89            reflect.QueueMethod.reallySet.__doc__)
    21090
    21191
    21292    def test_importExceptions(self):
     
    248128            reflect.namedAny, "twisted.nosuch.modulein.theworld")
    249129        self.assertRaises(
    250130            AttributeError,
    251             reflect.namedAny, "twisted.python.reflect.Summer.nosuchattributeintheworld")
     131            reflect.namedAny, "twisted.python.reflect.QueueMethod.nosuchattributeintheworld")
    252132
    253133
    254134    def test_invalidNames(self):
     
    718598        L{reflect.fullyQualifiedName} returns the name of a class and its
    719599        module.
    720600        """
    721         self._checkFullyQualifiedName(reflect.Settable,
    722                                       'twisted.python.reflect.Settable')
     601        self._checkFullyQualifiedName(reflect.QueueMethod,
     602                                      'twisted.python.reflect.QueueMethod')
    723603
    724604
    725605    def test_function(self):
     
    737617        its class and its module.
    738618        """
    739619        self._checkFullyQualifiedName(
    740             reflect.PropertyAccessor().reallyDel,
    741             "twisted.python.reflect.PropertyAccessor.reallyDel")
     620            reflect.QueueMethod().reallySet,
     621            "twisted.python.reflect.QueueMethod.reallySet")
    742622
    743623
    744624    def test_unboundMethod(self):
     
    747627        inside its class and its module.
    748628        """
    749629        self._checkFullyQualifiedName(
    750             reflect.PropertyAccessor.reallyDel,
    751             "twisted.python.reflect.PropertyAccessor.reallyDel")
     630            reflect.QueueMethod.reallySet,
     631            "twisted.python.reflect.QueueMethod.reallySet")
    752632
    753633
    754634
  • twisted/python/filepath.py

     
    11101110            os.unlink(self.path)
    11111111        os.rename(sib.path, self.path)
    11121112
    1113 
    1114     # new in 2.2.0
    1115 
    11161113    def __cmp__(self, other):
    11171114        if not isinstance(other, FilePath):
    11181115            return NotImplemented
  • twisted/python/reflect.py

     
    3434from twisted.python.deprecate import _fullyQualifiedName as fullyQualifiedName
    3535from twisted.python.versions import Version
    3636
    37 
    38 
    39 class Settable:
    40     """
    41     A mixin class for syntactic sugar.  Lets you assign attributes by
    42     calling with keyword arguments; for example, C{x(a=b,c=d,y=z)} is the
    43     same as C{x.a=b;x.c=d;x.y=z}.  The most useful place for this is
    44     where you don't want to name a variable, but you do want to set
    45     some attributes; for example, C{X()(y=z,a=b)}.
    46     """
    47     def __init__(self, **kw):
    48         self(**kw)
    49 
    50     def __call__(self,**kw):
    51         for key,val in kw.items():
    52             setattr(self,key,val)
    53         return self
    54 
    55 
    56 class AccessorType(type):
    57     """Metaclass that generates properties automatically.
    58 
    59     This is for Python 2.2 and up.
    60 
    61     Using this metaclass for your class will give you explicit accessor
    62     methods; a method called set_foo, will automatically create a property
    63     'foo' that uses set_foo as a setter method. Same for get_foo and del_foo.
    64 
    65     Note that this will only work on methods that are present on class
    66     creation. If you add methods after the class is defined they will not
    67     automatically become properties. Likewise, class attributes will only
    68     be used if they are present upon class creation, and no getter function
    69     was set - if a getter is present, the class attribute will be ignored.
    70 
    71     This is a 2.2-only alternative to the Accessor mixin - just set in your
    72     class definition::
    73 
    74         __metaclass__ = AccessorType
    75 
    76     """
    77 
    78     def __init__(self, name, bases, d):
    79         type.__init__(self, name, bases, d)
    80         accessors = {}
    81         prefixs = ["get_", "set_", "del_"]
    82         for k in d.keys():
    83             v = getattr(self, k)
    84             for i in range(3):
    85                 if k.startswith(prefixs[i]):
    86                     accessors.setdefault(k[4:], [None, None, None])[i] = v
    87         for name, (getter, setter, deler) in accessors.items():
    88             # create default behaviours for the property - if we leave
    89             # the getter as None we won't be able to getattr, etc..
    90             if getter is None:
    91                 if hasattr(self, name):
    92                     value = getattr(self, name)
    93                     def getter(this, value=value, name=name):
    94                         if name in this.__dict__:
    95                             return this.__dict__[name]
    96                         else:
    97                             return value
    98                 else:
    99                     def getter(this, name=name):
    100                         if name in this.__dict__:
    101                             return this.__dict__[name]
    102                         else:
    103                             raise AttributeError("no such attribute %r" % name)
    104             if setter is None:
    105                 def setter(this, value, name=name):
    106                     this.__dict__[name] = value
    107             if deler is None:
    108                 def deler(this, name=name):
    109                     del this.__dict__[name]
    110             setattr(self, name, property(getter, setter, deler, ""))
    111 
    112 
    113 class PropertyAccessor(object):
    114     """A mixin class for Python 2.2 that uses AccessorType.
    115 
    116     This provides compatability with the pre-2.2 Accessor mixin, up
    117     to a point.
    118 
    119     Extending this class will give you explicit accessor methods; a
    120     method called set_foo, for example, is the same as an if statement
    121     in __setattr__ looking for 'foo'.  Same for get_foo and del_foo.
    122 
    123     There are also reallyDel and reallySet methods, so you can
    124     override specifics in subclasses without clobbering __setattr__
    125     and __getattr__, or using non-2.1 compatible code.
    126 
    127     There is are incompatibilities with Accessor - accessor
    128     methods added after class creation will *not* be detected. OTOH,
    129     this method is probably way faster.
    130 
    131     In addition, class attributes will only be used if no getter
    132     was defined, and instance attributes will not override getter methods
    133     whereas in original Accessor the class attribute or instance attribute
    134     would override the getter method.
    135     """
    136     # addendum to above:
    137     # The behaviour of Accessor is wrong IMHO, and I've found bugs
    138     # caused by it.
    139     #  -- itamar
    140 
    141     __metaclass__ = AccessorType
    142 
    143     def reallySet(self, k, v):
    144         self.__dict__[k] = v
    145 
    146     def reallyDel(self, k):
    147         del self.__dict__[k]
    148 
    149 
    150 class Accessor:
    151     """
    152     Extending this class will give you explicit accessor methods; a
    153     method called C{set_foo}, for example, is the same as an if statement
    154     in L{__setattr__} looking for C{'foo'}.  Same for C{get_foo} and
    155     C{del_foo}.  There are also L{reallyDel} and L{reallySet} methods,
    156     so you can override specifics in subclasses without clobbering
    157     L{__setattr__} and L{__getattr__}.
    158 
    159     This implementation is for Python 2.1.
    160     """
    161 
    162     def __setattr__(self, k,v):
    163         kstring='set_%s'%k
    164         if hasattr(self.__class__,kstring):
    165             return getattr(self,kstring)(v)
    166         else:
    167             self.reallySet(k,v)
    168 
    169     def __getattr__(self, k):
    170         kstring='get_%s'%k
    171         if hasattr(self.__class__,kstring):
    172             return getattr(self,kstring)()
    173         raise AttributeError("%s instance has no accessor for: %s" % (qual(self.__class__),k))
    174 
    175     def __delattr__(self, k):
    176         kstring='del_%s'%k
    177         if hasattr(self.__class__,kstring):
    178             getattr(self,kstring)()
    179             return
    180         self.reallyDel(k)
    181 
     37class QueueMethod:
     38    """ I represent a method that doesn't exist yet."""
     39    def __init__(self, name='', calls=''):
     40        self.name = name
     41        self.calls = calls
     42    def __call__(self, *args):
     43        self.calls.append((self.name, args))
     44   
    18245    def reallySet(self, k,v):
    18346        """
    18447        *actually* set self.k to v without incurring side-effects.
     
    19053        else:
    19154            self.__dict__[k]=v
    19255
    193     def reallyDel(self, k):
    194         """
    195         *actually* del self.k without incurring side-effects.  This is a
    196         hook to be overridden by subclasses.
    197         """
    198         del self.__dict__[k]
     56       
    19957
    200 # just in case
    201 OriginalAccessor = Accessor
    202 
    203 
    204 class Summer(Accessor):
    205     """
    206     Extend from this class to get the capability to maintain 'related
    207     sums'.  Have a tuple in your class like the following::
    208 
    209         sums=(('amount','credit','credit_total'),
    210               ('amount','debit','debit_total'))
    211 
    212     and the 'credit_total' member of the 'credit' member of self will
    213     always be incremented when the 'amount' member of self is
    214     incremented, similiarly for the debit versions.
    215     """
    216 
    217     def reallySet(self, k,v):
    218         "This method does the work."
    219         for sum in self.sums:
    220             attr=sum[0]
    221             obj=sum[1]
    222             objattr=sum[2]
    223             if k == attr:
    224                 try:
    225                     oldval=getattr(self, attr)
    226                 except:
    227                     oldval=0
    228                 diff=v-oldval
    229                 if hasattr(self, obj):
    230                     ob=getattr(self,obj)
    231                     if ob is not None:
    232                         try:oldobjval=getattr(ob, objattr)
    233                         except:oldobjval=0.0
    234                         setattr(ob,objattr,oldobjval+diff)
    235 
    236             elif k == obj:
    237                 if hasattr(self, attr):
    238                     x=getattr(self,attr)
    239                     setattr(self,attr,0)
    240                     y=getattr(self,k)
    241                     Accessor.reallySet(self,k,v)
    242                     setattr(self,attr,x)
    243                     Accessor.reallySet(self,y,v)
    244         Accessor.reallySet(self,k,v)
    245 
    246 
    247 class QueueMethod:
    248     """ I represent a method that doesn't exist yet."""
    249     def __init__(self, name, calls):
    250         self.name = name
    251         self.calls = calls
    252     def __call__(self, *args):
    253         self.calls.append((self.name, args))
    254 
    255 
    25658def funcinfo(function):
    25759    """
    25860    this is more documentation for myself than useful code.
     
    805607    'InvalidName', 'ModuleNotFound', 'ObjectNotFound',
    806608
    807609    'ISNT', 'WAS', 'IS',
     610   
     611    'QueueMethod',
    808612
    809     'Settable', 'AccessorType', 'PropertyAccessor', 'Accessor', 'Summer',
    810     'QueueMethod', 'OriginalAccessor',
    811 
    812613    'funcinfo', 'fullFuncName', 'qual', 'getcurrent', 'getClass', 'isinst',
    813614    'namedModule', 'namedObject', 'namedClass', 'namedAny', 'macro',
    814615    'safe_repr', 'safe_str', 'allYourBase', 'accumulateBases',
  • twisted/python/dist.py

     
    210210
    211211def getPackages(dname, pkgname=None, results=None, ignore=None, parent=None):
    212212    """
    213     Get all packages which are under dname. This is necessary for
    214     Python 2.2's distutils. Pretty similar arguments to getDataFiles,
    215     including 'parent'.
     213    Get all packages which are under dname.
     214    Pretty similar arguments to getDataFiles,including 'parent'.
    216215    """
    217216    parent = parent or ""
    218217    prefix = []
  • twisted/internet/error.py

     
    193193    except ValueError:
    194194        return ConnectError(string=e)
    195195
    196     if hasattr(socket, 'gaierror') and isinstance(e, socket.gaierror):
    197         # only works in 2.2
    198         klass = UnknownHostError
    199     else:
    200         klass = errnoMapping.get(number, ConnectError)
     196    klass = errnoMapping.get(number,ConnectError)
    201197    return klass(number, string)
    202198
    203199
  • doc/core/howto/pb-copyable.xhtml

     
    405405attribute is changed<span class="footnote">Of course you could be clever and
    406406add a hook to <code>__setattr__</code>, along with magical change-announcing
    407407subclasses of the usual builtin types, to detect changes that result from
    408 normal <q>=</q> set operations. The semi-magical <q>property attributes</q>
    409 that were introduced in Python 2.2 could be useful too. The result might be
    410 hard to maintain or extend, though.</span>.</p>
     408normal <q>=</q> set operations.
     409</span></p>
    411410
    412411<p>You derive your sender-side class from <code>pb.Cacheable</code>, and you
    413412add two methods: <code class="API"
  • doc/web/howto/xmlrpc.xhtml

     
    1515<p><a href="http://www.xmlrpc.com">XML-RPC</a> is a simple request/reply protocol
    1616that runs over HTTP. It is simple, easy to implement and supported by most programming
    1717languages. Twisted's XML-RPC support is implemented using the
    18 <a href='http://docs.python.org/library/xmlrpclib.html'>xmlrpclib</a> library that is
    19 included with Python 2.2 and later.</p>
     18<a href='http://docs.python.org/library/xmlrpclib.html'>xmlrpclib</a>.
     19</p>
    2020
    2121<h2>Creating a XML-RPC server</h2>
    2222
  • doc/web/examples/xmlrpc.py

     
    2222from twisted.web import xmlrpc
    2323from twisted.internet import defer
    2424
    25 # This module is standard in Python 2.2, otherwise get it from
    26 #   http://www.pythonware.com/products/xmlrpc/
    2725import xmlrpclib
    2826
    2927