Ticket #5895: ticket5895_2.patch

File ticket5895_2.patch, 10.5 KB (added by mateusbraga, 3 years ago)

twisted/topfiles/5895.removal added to the patch

  • twisted/python/compat.py

     
    3030
    3131
    3232
    33 def inet_pton(af, addr):
    34     if af == socket.AF_INET:
    35         return socket.inet_aton(addr)
    36     elif af == getattr(socket, 'AF_INET6', 'AF_INET6'):
    37         if [x for x in addr if x not in string.hexdigits + ':.']:
    38             raise ValueError("Illegal characters: %r" % (''.join(x),))
    3933
    40         parts = addr.split(':')
    41         elided = parts.count('')
    42         ipv4Component = '.' in parts[-1]
    4334
    44         if len(parts) > (8 - ipv4Component) or elided > 3:
    45             raise ValueError("Syntactically invalid address")
    46 
    47         if elided == 3:
    48             return '\x00' * 16
    49 
    50         if elided:
    51             zeros = ['0'] * (8 - len(parts) - ipv4Component + elided)
    52 
    53             if addr.startswith('::'):
    54                 parts[:2] = zeros
    55             elif addr.endswith('::'):
    56                 parts[-2:] = zeros
    57             else:
    58                 idx = parts.index('')
    59                 parts[idx:idx+1] = zeros
    60 
    61             if len(parts) != 8 - ipv4Component:
    62                 raise ValueError("Syntactically invalid address")
    63         else:
    64             if len(parts) != (8 - ipv4Component):
    65                 raise ValueError("Syntactically invalid address")
    66 
    67         if ipv4Component:
    68             if parts[-1].count('.') != 3:
    69                 raise ValueError("Syntactically invalid address")
    70             rawipv4 = socket.inet_aton(parts[-1])
    71             unpackedipv4 = struct.unpack('!HH', rawipv4)
    72             parts[-1:] = [hex(x)[2:] for x in unpackedipv4]
    73 
    74         parts = [int(x, 16) for x in parts]
    75         return struct.pack('!8H', *parts)
    76     else:
    77         raise socket.error(97, 'Address family not supported by protocol')
    78 
    79 def inet_ntop(af, addr):
    80     if af == socket.AF_INET:
    81         return socket.inet_ntoa(addr)
    82     elif af == socket.AF_INET6:
    83         if len(addr) != 16:
    84             raise ValueError("address length incorrect")
    85         parts = struct.unpack('!8H', addr)
    86         curBase = bestBase = None
    87         for i in range(8):
    88             if not parts[i]:
    89                 if curBase is None:
    90                     curBase = i
    91                     curLen = 0
    92                 curLen += 1
    93             else:
    94                 if curBase is not None:
    95                     if bestBase is None or curLen > bestLen:
    96                         bestBase = curBase
    97                         bestLen = curLen
    98                     curBase = None
    99         if curBase is not None and (bestBase is None or curLen > bestLen):
    100             bestBase = curBase
    101             bestLen = curLen
    102         parts = [hex(x)[2:] for x in parts]
    103         if bestBase is not None:
    104             parts[bestBase:bestBase + bestLen] = ['']
    105         if parts[0] == '':
    106             parts.insert(0, '')
    107         if parts[-1] == '':
    108             parts.insert(len(parts) - 1, '')
    109         return ':'.join(parts)
    110     else:
    111         raise socket.error(97, 'Address family not supported by protocol')
    112 
    113 try:
    114     socket.AF_INET6
    115 except AttributeError:
    116     socket.AF_INET6 = 'AF_INET6'
    117 
    118 try:
    119     socket.inet_pton(socket.AF_INET6, "::")
    120 except (AttributeError, NameError, socket.error):
    121     socket.inet_pton = inet_pton
    122     socket.inet_ntop = inet_ntop
    123 
    124 
    125 adict = dict
    126 
    127 
    128 
    129 if _PY3:
    130     # These are actually useless in Python 2 as well, but we need to go
    131     # through deprecation process there (ticket #5895):
    132     del adict, inet_pton, inet_ntop
    133 
    134 
    13535set = set
    13636frozenset = frozenset
    13737
     
    404304@rtype: C{bytes}
    405305"""
    406306
     307# These import are here because of the circular dependency
     308# between compat and the Version module
     309from twisted.python.deprecate import deprecated, deprecatedModuleAttribute
     310from twisted.python.versions import Version
    407311
     312@deprecated(Version("Twisted", 13, 1, 0), socket.inet_pton)
     313def inet_pton(af, addr):
     314    if af == socket.AF_INET:
     315        return socket.inet_aton(addr)
     316    elif af == getattr(socket, 'AF_INET6', 'AF_INET6'):
     317        if [x for x in addr if x not in string.hexdigits + ':.']:
     318            raise ValueError("Illegal characters: %r" % (''.join(x),))
     319
     320        parts = addr.split(':')
     321        elided = parts.count('')
     322        ipv4Component = '.' in parts[-1]
     323
     324        if len(parts) > (8 - ipv4Component) or elided > 3:
     325            raise ValueError("Syntactically invalid address")
     326
     327        if elided == 3:
     328            return '\x00' * 16
     329
     330        if elided:
     331            zeros = ['0'] * (8 - len(parts) - ipv4Component + elided)
     332
     333            if addr.startswith('::'):
     334                parts[:2] = zeros
     335            elif addr.endswith('::'):
     336                parts[-2:] = zeros
     337            else:
     338                idx = parts.index('')
     339                parts[idx:idx+1] = zeros
     340
     341            if len(parts) != 8 - ipv4Component:
     342                raise ValueError("Syntactically invalid address")
     343        else:
     344            if len(parts) != (8 - ipv4Component):
     345                raise ValueError("Syntactically invalid address")
     346
     347        if ipv4Component:
     348            if parts[-1].count('.') != 3:
     349                raise ValueError("Syntactically invalid address")
     350            rawipv4 = socket.inet_aton(parts[-1])
     351            unpackedipv4 = struct.unpack('!HH', rawipv4)
     352            parts[-1:] = [hex(x)[2:] for x in unpackedipv4]
     353
     354        parts = [int(x, 16) for x in parts]
     355        return struct.pack('!8H', *parts)
     356    else:
     357        raise socket.error(97, 'Address family not supported by protocol')
     358
     359@deprecated(Version("Twisted", 13, 1, 0), socket.inet_ntop)
     360def inet_ntop(af, addr):
     361    if af == socket.AF_INET:
     362        return socket.inet_ntoa(addr)
     363    elif af == socket.AF_INET6:
     364        if len(addr) != 16:
     365            raise ValueError("address length incorrect")
     366        parts = struct.unpack('!8H', addr)
     367        curBase = bestBase = None
     368        for i in range(8):
     369            if not parts[i]:
     370                if curBase is None:
     371                    curBase = i
     372                    curLen = 0
     373                curLen += 1
     374            else:
     375                if curBase is not None:
     376                    if bestBase is None or curLen > bestLen:
     377                        bestBase = curBase
     378                        bestLen = curLen
     379                    curBase = None
     380        if curBase is not None and (bestBase is None or curLen > bestLen):
     381            bestBase = curBase
     382            bestLen = curLen
     383        parts = [hex(x)[2:] for x in parts]
     384        if bestBase is not None:
     385            parts[bestBase:bestBase + bestLen] = ['']
     386        if parts[0] == '':
     387            parts.insert(0, '')
     388        if parts[-1] == '':
     389            parts.insert(len(parts) - 1, '')
     390        return ':'.join(parts)
     391    else:
     392        raise socket.error(97, 'Address family not supported by protocol')
     393
     394try:
     395    socket.AF_INET6
     396except AttributeError:
     397    socket.AF_INET6 = 'AF_INET6'
     398
     399try:
     400    socket.inet_pton(socket.AF_INET6, "::")
     401except (AttributeError, NameError, socket.error):
     402    socket.inet_pton = inet_pton
     403    socket.inet_ntop = inet_ntop
     404
     405
     406adict = dict
     407deprecatedModuleAttribute(
     408    Version("Twisted", 13, 1, 0),
     409    "adict is useless in Python 2.", __name__, "adict")
     410
     411
    408412__all__ = [
    409413    "reraise",
    410414    "execfile",
  • twisted/test/test_compat.py

     
    88
    99from __future__ import division, absolute_import
    1010
    11 import socket, sys, traceback
     11import socket
     12import sys
     13import traceback
    1214
    1315from twisted.trial import unittest
    1416
     17from twisted.python import compat
    1518from twisted.python.compat import reduce, execfile, _PY3
    1619from twisted.python.compat import comparable, cmp, nativeString, networkString
    1720from twisted.python.compat import unicode as unicodeCompat, lazyByteSlice
    1821from twisted.python.compat import reraise, NativeStringIO, iterbytes, intToBytes
     22from twisted.python.versions import Version
    1923from twisted.python.filepath import FilePath
    2024
    2125
     
    621625        """
    622626        data = b'123XYZ'
    623627        self.assertEqual(bytes(lazyByteSlice(data, 2, 3)), data[2:5])
     628
     629
     630class DeprecationTestCase(unittest.TestCase):
     631    """
     632    Test deprecations in twisted.python.compat
     633    """
     634
     635    def test_inet_ntop(self):
     636        """
     637        Test deprecation of L{compat.inet_ntop}.
     638        """
     639        self.callDeprecated(
     640            (Version("Twisted", 13, 1, 0), socket.inet_ntop),
     641            compat.inet_ntop, socket.AF_INET, "\x01\x00\x01\x00")
     642
     643    def test_inet_pton(self):
     644        """
     645        Test deprecation of L{compat.inet_pton}.
     646        """
     647        self.callDeprecated(
     648            (Version("Twisted", 13, 1, 0), socket.inet_pton),
     649            compat.inet_pton, socket.AF_INET, "0.0.0.0")
     650
     651
     652    def lookForDeprecationWarning(self, testMethod, attributeName, warningMsg):
     653        """
     654        Test deprecation of attribute 'compat.attributeName' by calling
     655        'compat.testMethod' and verifying the warning message
     656        'compat.warningMsg'
     657
     658        @param testMethod: Name of the offending function to be used with
     659            flushWarnings
     660        @type testmethod: C{str}
     661
     662        @param attributeName: Name of attribute to be checked for deprecation
     663        @type attributeName: C{str}
     664
     665        @param warningMsg: Deprecation warning message
     666        @type warningMsg: C{str}
     667        """
     668        warningsShown = self.flushWarnings([testMethod])
     669        self.assertEqual(len(warningsShown), 1)
     670        self.assertIdentical(warningsShown[0]['category'], DeprecationWarning)
     671        self.assertEqual(
     672            warningsShown[0]['message'],
     673            "twisted.python.compat." + attributeName + " "
     674            "was deprecated in Twisted 13.1.0: " + warningMsg + ".")
     675
     676
     677    def test_adict(self):
     678        """
     679        Test deprecation of L{compat.adict}.
     680        """
     681        a = compat.adict
     682        del a
     683        self.lookForDeprecationWarning(
     684            self.test_adict, "adict",
     685            "adict is useless in Python 2")
     686
  • twisted/topfiles/5895.removal

     
     1twisted.python.compat.adict is now deprecated.
     2twisted.python.compat.inet_pton is now deprecated in favor of socket.inet_pton from the standard library.
     3twisted.python.compat.inet_ntop is now deprecated in favor of socket.inet_ntop from the standard library.
     4