Remove sys.version_info checks for python2 and clean some imports.

This commit is contained in:
Emmanuel Gil Peyrot 2014-08-16 22:37:25 +02:00 committed by Florent Le Coz
parent b92dac72f3
commit 0e95015410
13 changed files with 23 additions and 114 deletions

View File

@ -12,9 +12,6 @@
:license: MIT, see LICENSE for more details :license: MIT, see LICENSE for more details
""" """
from __future__ import with_statement, unicode_literals
import sys
import logging import logging
import threading import threading
@ -38,13 +35,6 @@ from slixmpp.plugins import PluginManager, load_plugin
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
# In order to make sure that Unicode is handled properly
# in Python 2.x, reset the default encoding.
if sys.version_info < (3, 0):
from slixmpp.util.misc_ops import setdefaultencoding
setdefaultencoding('utf8')
class BaseXMPP(XMLStream): class BaseXMPP(XMLStream):
""" """

View File

@ -12,8 +12,6 @@
:license: MIT, see LICENSE for more details :license: MIT, see LICENSE for more details
""" """
from __future__ import absolute_import, unicode_literals
import logging import logging
from slixmpp.stanza import StreamFeatures from slixmpp.stanza import StreamFeatures

View File

@ -12,10 +12,7 @@
:license: MIT, see LICENSE for more details :license: MIT, see LICENSE for more details
""" """
from __future__ import absolute_import
import logging import logging
import sys
import hashlib import hashlib
from slixmpp.basexmpp import BaseXMPP from slixmpp.basexmpp import BaseXMPP
@ -136,10 +133,7 @@ class ComponentXMPP(BaseXMPP):
# Construct a hash of the stream ID and the component secret. # Construct a hash of the stream ID and the component secret.
sid = xml.get('id', '') sid = xml.get('id', '')
pre_hash = '%s%s' % (sid, self.secret) pre_hash = bytes('%s%s' % (sid, self.secret), 'utf-8')
if sys.version_info >= (3, 0):
# Handle Unicode byte encoding in Python 3.
pre_hash = bytes(pre_hash, 'utf-8')
handshake = ET.Element('{jabber:component:accept}handshake') handshake = ET.Element('{jabber:component:accept}handshake')
handshake.text = hashlib.sha1(pre_hash).hexdigest().lower() handshake.text = hashlib.sha1(pre_hash).hexdigest().lower()

View File

@ -19,10 +19,6 @@ import logging
import threading import threading
if sys.version_info >= (3, 0):
unicode = str
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -89,7 +85,7 @@ def load_plugin(name, module=None):
module = 'slixmpp.features.%s' % name module = 'slixmpp.features.%s' % name
__import__(module) __import__(module)
mod = sys.modules[module] mod = sys.modules[module]
elif isinstance(module, (str, unicode)): elif isinstance(module, str):
__import__(module) __import__(module)
mod = sys.modules[module] mod = sys.modules[module]
else: else:

View File

@ -10,10 +10,6 @@ from slixmpp.xmlstream import ET
import base64 import base64
import logging import logging
import time import time
import sys
if sys.version_info > (3, 0):
unicode = str
log = logging.getLogger(__name__) log = logging.getLogger(__name__)
@ -58,7 +54,7 @@ def _py2xml(*args):
boolean = ET.Element("{%s}boolean" % _namespace) boolean = ET.Element("{%s}boolean" % _namespace)
boolean.text = str(int(x)) boolean.text = str(int(x))
val.append(boolean) val.append(boolean)
elif type(x) in (str, unicode): elif type(x) is str:
string = ET.Element("{%s}string" % _namespace) string = ET.Element("{%s}string" % _namespace)
string.text = x string.text = x
val.append(string) val.append(string)
@ -156,7 +152,7 @@ class rpctime(object):
def __init__(self,data=None): def __init__(self,data=None):
#assume string data is in iso format YYYYMMDDTHH:MM:SS #assume string data is in iso format YYYYMMDDTHH:MM:SS
if type(data) in (str, unicode): if type(data) is str:
self.timestamp = time.strptime(data,"%Y%m%dT%H:%M:%S") self.timestamp = time.strptime(data,"%Y%m%dT%H:%M:%S")
elif type(data) is time.struct_time: elif type(data) is time.struct_time:
self.timestamp = data self.timestamp = data

View File

@ -9,8 +9,6 @@
import uuid import uuid
import logging import logging
import hashlib import hashlib
import random
import sys
from slixmpp.jid import JID from slixmpp.jid import JID
from slixmpp.exceptions import IqError, IqTimeout from slixmpp.exceptions import IqError, IqTimeout
@ -105,12 +103,8 @@ class XEP_0078(BasePlugin):
if 'digest' in resp['auth']['fields']: if 'digest' in resp['auth']['fields']:
log.debug('Authenticating via jabber:iq:auth Digest') log.debug('Authenticating via jabber:iq:auth Digest')
if sys.version_info < (3, 0): stream_id = bytes(self.xmpp.stream_id, encoding='utf-8')
stream_id = bytes(self.xmpp.stream_id) password = bytes(self.xmpp.password, encoding='utf-8')
password = bytes(self.xmpp.password)
else:
stream_id = bytes(self.xmpp.stream_id, encoding='utf-8')
password = bytes(self.xmpp.password, encoding='utf-8')
digest = hashlib.sha1(b'%s%s' % (stream_id, password)).hexdigest() digest = hashlib.sha1(b'%s%s' % (stream_id, password)).hexdigest()
iq['auth']['digest'] = digest iq['auth']['digest'] = digest

View File

@ -12,7 +12,7 @@
from slixmpp.util.misc_ops import bytes, unicode, hashes, hash, \ from slixmpp.util.misc_ops import bytes, unicode, hashes, hash, \
num_to_bytes, bytes_to_num, quote, \ num_to_bytes, bytes_to_num, quote, \
XOR, safedict XOR
# ===================================================================== # =====================================================================

View File

@ -3,12 +3,7 @@ import hashlib
def unicode(text): def unicode(text):
if sys.version_info < (3, 0): if not isinstance(text, str):
if isinstance(text, str):
text = text.decode('utf-8')
import __builtin__
return __builtin__.unicode(text)
elif not isinstance(text, str):
return text.decode('utf-8') return text.decode('utf-8')
else: else:
return text return text
@ -27,20 +22,16 @@ def bytes(text):
if text is None: if text is None:
return b'' return b''
if sys.version_info < (3, 0): import builtins
import __builtin__ if isinstance(text, builtins.bytes):
return __builtin__.bytes(text) # We already have bytes, so do nothing
return text
if isinstance(text, list):
# Convert a list of integers to bytes
return builtins.bytes(text)
else: else:
import builtins # Convert UTF-8 text to bytes
if isinstance(text, builtins.bytes): return builtins.bytes(text, encoding='utf-8')
# We already have bytes, so do nothing
return text
if isinstance(text, list):
# Convert a list of integers to bytes
return builtins.bytes(text)
else:
# Convert UTF-8 text to bytes
return builtins.bytes(text, encoding='utf-8')
def quote(text): def quote(text):
@ -91,10 +82,7 @@ def XOR(x, y):
""" """
result = b'' result = b''
for a, b in zip(x, y): for a, b in zip(x, y):
if sys.version_info < (3, 0): result += bytes([a ^ b])
result += chr((ord(a) ^ ord(b)))
else:
result += bytes([a ^ b])
return result return result
@ -153,13 +141,3 @@ def setdefaultencoding(encoding):
raise RuntimeError("Could not find setdefaultencoding") raise RuntimeError("Could not find setdefaultencoding")
sys.setdefaultencoding = func sys.setdefaultencoding = func
return func(encoding) return func(encoding)
def safedict(data):
if sys.version_info < (2, 7):
safe = {}
for key in data:
safe[key.encode('utf8')] = data[key]
return safe
else:
return data

View File

@ -15,7 +15,6 @@
:license: MIT, see LICENSE for more details :license: MIT, see LICENSE for more details
""" """
import sys
import hmac import hmac
import random import random
@ -365,8 +364,7 @@ class DIGEST(Mech):
for char in challenge: for char in challenge:
if sys.version_info >= (3, 0): char = bytes([char])
char = bytes([char])
if state == 'var': if state == 'var':
if char.isspace(): if char.isspace():

View File

@ -13,14 +13,6 @@
:license: MIT, see LICENSE for more details :license: MIT, see LICENSE for more details
""" """
from __future__ import unicode_literals
import sys
if sys.version_info < (3, 0):
import types
XML_NS = 'http://www.w3.org/XML/1998/namespace' XML_NS = 'http://www.w3.org/XML/1998/namespace'
@ -145,10 +137,6 @@ def escape(text, use_cdata=False):
:param string text: The XML text to convert. :param string text: The XML text to convert.
:rtype: Unicode string :rtype: Unicode string
""" """
if sys.version_info < (3, 0):
if type(text) != types.UnicodeType:
text = unicode(text, 'utf-8', 'ignore')
escapes = {'&': '&amp;', escapes = {'&': '&amp;',
'<': '&lt;', '<': '&lt;',
'>': '&gt;', '>': '&gt;',

View File

@ -12,32 +12,19 @@
:license: MIT, see LICENSE for more details :license: MIT, see LICENSE for more details
""" """
from __future__ import with_statement, unicode_literals
import asyncio import asyncio
import functools import functools
import base64
import copy import copy
import logging import logging
import signal
import socket as Socket import socket as Socket
import ssl import ssl
import sys
import time
import random
import weakref import weakref
import uuid import uuid
import errno
from xml.parsers.expat import ExpatError
import xml.etree.ElementTree import xml.etree.ElementTree
import slixmpp from slixmpp.xmlstream import tostring
from slixmpp.util import Queue, QueueEmpty, safedict from slixmpp.xmlstream.stanzabase import StanzaBase, ElementBase
from slixmpp.xmlstream import tostring, cert
from slixmpp.xmlstream.stanzabase import StanzaBase, ET, ElementBase
from slixmpp.xmlstream.handler import Waiter, XMLCallback
from slixmpp.xmlstream.matcher import MatchXMLMask
from slixmpp.xmlstream.resolver import resolve, default_resolver from slixmpp.xmlstream.resolver import resolve, default_resolver
#: The time in seconds to wait before timing out waiting for response stanzas. #: The time in seconds to wait before timing out waiting for response stanzas.
@ -584,10 +571,7 @@ class XMLStream(object):
if not self.dns_answers: if not self.dns_answers:
self.dns_answers = self.get_dns_records(domain, port) self.dns_answers = self.get_dns_records(domain, port)
if sys.version_info < (3, 0): return next(self.dns_answers)
return self.dns_answers.next()
else:
return next(self.dns_answers)
def add_event_handler(self, name, pointer, disposable=False): def add_event_handler(self, name, pointer, disposable=False):
"""Add a custom event handler that will be executed whenever """Add a custom event handler that will be executed whenever

View File

@ -15,10 +15,7 @@ class TestOverall(unittest.TestCase):
def testModules(self): def testModules(self):
"""Testing all modules by compiling them""" """Testing all modules by compiling them"""
src = '.%sslixmpp' % os.sep src = '.%sslixmpp' % os.sep
if sys.version_info < (3, 0): rx = re.compile('/[.]svn|.*26.*')
rx = re.compile('/[.]svn')
else:
rx = re.compile('/[.]svn|.*26.*')
self.failUnless(compileall.compile_dir(src, rx=rx, quiet=True)) self.failUnless(compileall.compile_dir(src, rx=rx, quiet=True))
def testTabNanny(self): def testTabNanny(self):

View File

@ -24,10 +24,6 @@ from slixmpp.xmlstream.tostring import tostring
import unittest import unittest
if sys.version_info > (3, 0):
unicode = str
class TestJabberRPC(SlixTest): class TestJabberRPC(SlixTest):
def setUp(self): def setUp(self):