diff --git a/pyVim/sso.py b/pyVim/sso.py index 94c575c5..070893f0 100644 --- a/pyVim/sso.py +++ b/pyVim/sso.py @@ -9,11 +9,7 @@ #Standard library imports. from six.moves.http_client import HTTPConnection, HTTPSConnection import re -from six import PY3 -if PY3: - from html import escape -else: - from cgi import escape +from html import escape import datetime import base64 import hashlib @@ -25,7 +21,7 @@ from uuid import uuid4 from io import BytesIO -from six.moves.urllib.parse import urlparse +from urllib.parse import urlparse #Third-party imports. from lxml import etree from OpenSSL import crypto diff --git a/pyVmomi/Differ.py b/pyVmomi/Differ.py index 3eaa11cc..6ac50e42 100644 --- a/pyVmomi/Differ.py +++ b/pyVmomi/Differ.py @@ -5,9 +5,6 @@ import logging -import six -from six.moves import zip - from .VmomiSupport import F_LINK, F_OPTIONAL, GetWsdlName, Type, types __Log__ = logging.getLogger('ObjDiffer') @@ -23,9 +20,9 @@ def IsPrimitiveType(obj): """See if the passed in type is a Primitive Type""" return (isinstance(obj, types.bool) or isinstance(obj, types.byte) or isinstance(obj, types.short) - or isinstance(obj, six.integer_types) + or isinstance(obj, int) or isinstance(obj, types.double) or isinstance(obj, types.float) - or isinstance(obj, six.string_types) + or isinstance(obj, str) or isinstance(obj, types.PropertyPath) or isinstance(obj, types.ManagedMethod) or isinstance(obj, types.datetime) or isinstance(obj, types.URI) diff --git a/pyVmomi/Iso8601.py b/pyVmomi/Iso8601.py index fed9f8d4..f8259fb9 100644 --- a/pyVmomi/Iso8601.py +++ b/pyVmomi/Iso8601.py @@ -9,8 +9,6 @@ import time from datetime import datetime, timedelta, tzinfo -import six - # Regular expression to parse a subset of ISO 8601 format _dtExpr = re.compile( # XMLSchema datetime. Mandatory to have - and : @@ -112,7 +110,7 @@ def ParseISO8601(datetimeStr): if match: try: dt = {} - for key, defaultVal in six.iteritems(_dtExprKeyDefValMap): + for key, defaultVal in _dtExprKeyDefValMap.items(): val = match.group(key) if val: if key == 'microsecond': diff --git a/pyVmomi/SoapAdapter.py b/pyVmomi/SoapAdapter.py index 64835d56..6f53a352 100644 --- a/pyVmomi/SoapAdapter.py +++ b/pyVmomi/SoapAdapter.py @@ -12,14 +12,12 @@ import threading import time from datetime import datetime +from io import StringIO from xml.parsers.expat import ExpatError, ParserCreate # For Visor, space is very limited. Import xml.sax pull in too much junk. # Define our own xml escape instead # from xml.sax.saxutils import escape -import six -from six import PY3 -from six.moves import StringIO, zip from six.moves.urllib.parse import urlparse from six.moves.http_cookies import SimpleCookie from six.moves.http_client import (HTTPConnection, HTTPSConnection, @@ -74,7 +72,7 @@ NSMAP_DEF = ' '.join([ 'xmlns:{}="{}"'.format(prefix, urn) - for urn, prefix in six.iteritems(SOAP_NSMAP) + for urn, prefix in SOAP_NSMAP.items() ]) SOAP_ENVELOPE_START = '<{} {}>\n'.format(SOAP_ENVELOPE_TAG, NSMAP_DEF) @@ -286,7 +284,7 @@ def __init__(self, writer, version, nsMap, encoding=None): self.writer = writer self.version = version self.nsMap = nsMap and nsMap or {} - for ns, prefix in six.iteritems(self.nsMap): + for ns, prefix in self.nsMap.items(): if prefix == '': self.defaultNS = ns break @@ -485,7 +483,7 @@ def _Serialize(self, val, info, defNS): attr += '{0} {1}type="{2}"'.format( nsattr, self.xsiPrefix, qName) result = base64.b64encode(val) - if PY3: + if True: # In python3 the bytes result after the base64 encoding has a # leading 'b' which causes error when we use it to construct # the soap message. Workaround the issue by converting the @@ -503,12 +501,12 @@ def _Serialize(self, val, info, defNS): result = val and "true" or "false" self.writer.write('<{0}{1}>{2}'.format( info.name, attr, result)) - elif isinstance(val, six.integer_types) or isinstance(val, float): + elif isinstance(val, int) or isinstance(val, float): if info.type is object: nsattr, qName = self._QName(Type(val), currDefNS) attr += '{0} {1}type="{2}"'.format( nsattr, self.xsiPrefix, qName) - result = six.text_type(val) + result = str(val) self.writer.write('<{0}{1}>{2}'.format( info.name, attr, result)) elif isinstance(val, Enum): @@ -528,7 +526,7 @@ def _Serialize(self, val, info, defNS): attr += '{0} {1}type="{2}"'.format( nsattr, self.xsiPrefix, qName) - if isinstance(val, six.binary_type): + if isinstance(val, bytes): # Use UTF-8 rather than self.encoding. self.encoding is for # output of serializer, while 'val' is our input. # And regardless of what our output is, our input should be @@ -589,7 +587,7 @@ def Deserialize(data, resultType=object, stub=None): # But in python3 the input become unicode and the handling will fall into # ParseFile case. # Adding unicode input support to make it more test friendly. - if isinstance(data, six.binary_type) or isinstance(data, six.text_type): + if isinstance(data, bytes) or isinstance(data, str): parser.Parse(data) else: parser.ParseFile(data) @@ -917,8 +915,7 @@ def Deserialize(self, response, resultType, nsMap=None): # purpose. But in python3 the input become unicode and the handling # will fall into ParseFile case. # Adding unicode input support to make it more test friendly. - if isinstance(response, six.binary_type) or isinstance( - response, six.text_type): + if isinstance(response, (bytes, str)): self.parser.Parse(response) else: self.parser.ParseFile(response) @@ -1019,9 +1016,9 @@ def SerializeRequest(self, mo, info, args): if reqContexts or samlToken: result.append(SOAP_HEADER_START) - for key, val in six.iteritems(reqContexts): + for key, val in reqContexts.items(): # Note: Support req context of string type only - if not isinstance(val, six.string_types): + if not isinstance(val, str): raise TypeError( "Request context key ({0}) has non-string value" " ({1}) of {2}".format(key, val, type(val))) diff --git a/pyVmomi/VmomiJSONEncoder.py b/pyVmomi/VmomiJSONEncoder.py index 691c0b30..18abf302 100644 --- a/pyVmomi/VmomiJSONEncoder.py +++ b/pyVmomi/VmomiJSONEncoder.py @@ -5,7 +5,6 @@ import json from datetime import datetime -from six import PY3 from . import Iso8601 from .VmomiSupport import ManagedObject, DataObject, ManagedMethod, \ @@ -91,8 +90,8 @@ def default(self, obj): # pylint: disable=method-hidden return self._remove_empty_dynamic_if(result) if isinstance(obj, binary): result = base64.b64encode(obj) - if PY3: # see VmomiSupport.FormatObject - result = str(result, 'utf-8') + # see VmomiSupport.FormatObject + result = str(result, 'utf-8') return result if isinstance(obj, datetime): return Iso8601.ISO8601Format(obj) diff --git a/pyVmomi/VmomiSupport.py b/pyVmomi/VmomiSupport.py index d6eda56a..5a52781b 100644 --- a/pyVmomi/VmomiSupport.py +++ b/pyVmomi/VmomiSupport.py @@ -9,17 +9,14 @@ from functools import partial from sys import version_info -import six -from six import PY3, binary_type, string_types -from six.moves import map, range +from six import PY3, binary_type from . import Iso8601 from . import _allowGetSet from . import _allowCapitalizedNames from . import _binaryIsBytearray -if version_info[0] >= 3: - from functools import cmp_to_key +from functools import cmp_to_key NoneType = type(None) try: @@ -171,13 +168,13 @@ def __getattr__(self, attr): raise AttributeError(attr) -class Link(six.text_type): +class Link(str): def __new__(cls, obj): - if isinstance(obj, string_types): - return six.text_type.__new__(cls, obj) + if isinstance(obj, str): + return str.__new__(cls, obj) elif isinstance(obj, DataObject): if obj.key: - return six.text_type.__new__(cls, obj.key) + return str.__new__(cls, obj.key) raise AttributeError("DataObject does not have a key to link") else: raise ValueError @@ -1099,8 +1096,8 @@ def _areBasicTypes(info, valType): or issubclass(info, long) and (issubclass(valType, int) or issubclass(valType, long)) or issubclass(info, float) and issubclass(valType, float) - or issubclass(info, string_types) and issubclass(valType, string_types) - or issubclass(info, binary_type) and issubclass(valType, binary_type)) + or issubclass(info, str) and issubclass(valType, str) + or issubclass(info, bytes) and issubclass(valType, bytes)) # Check that a value matches a given type, and annotate if neccesary @@ -1142,7 +1139,7 @@ def CheckField(info, val): if issubclass(valType, GetVmodlType(info.expectedType)): return elif issubclass(info.type.Item, Enum) and issubclass( - valType.Item, string_types): + valType.Item, str): # Allow String array object to be assigned to enum array return elif val: @@ -1286,7 +1283,7 @@ def GetWsdlTypes(): with _lazyLock: for ns, name in _wsdlDefMap: GetWsdlType(ns, name) - return six.itervalues(_wsdlTypeMap) + return _wsdlTypeMap.values() # Get the qualified XML schema name (ns, name) of a type @@ -1438,14 +1435,9 @@ def compare(a, b): return 1 return (a > b) - (a < b) - if version_info[0] >= 3: - return sorted( - [v for (v, n) in six.iteritems(serviceNsMap) if n == namespace], + return sorted( + [v for (v, n) in serviceNsMap.items() if n == namespace], key=cmp_to_key(compare)) - else: - return sorted( - [v for (v, n) in six.iteritems(serviceNsMap) if n == namespace], - compare) # Set a WSDL method with wsdl namespace and wsdl name @@ -1549,7 +1541,7 @@ def GetCompatibleType(type, version): # Invert an injective mapping def InverseMap(map): - return dict([(v, k) for (k, v) in six.iteritems(map)]) + return dict([(v, k) for (k, v) in map.items()]) def GetVmodlNs(version): @@ -1702,7 +1694,7 @@ def EnumerateWireIds(self): binary = type("binary", (bytearray,), {}) else: binary = type("binary", (binary_type,), {}) -PropertyPath = type("PropertyPath", (six.text_type, ), {}) +PropertyPath = type("PropertyPath", (str, ), {}) # _wsdlTypeMapNSs store namespaces added to _wsdlTypeMap in _SetWsdlType _wsdlTypeMapNSs = set() @@ -1759,8 +1751,8 @@ def EnumerateWireIds(self): # unicode is mapped to wsdl name 'string' (Cannot put in wsdlTypeMap or name # collision with non-unicode string) -_wsdlNameMap[six.text_type] = (XMLNS_XSD, 'string') -_wsdlNameMap[CreateArrayType(six.text_type)] = (XMLNS_VMODL_BASE, +_wsdlNameMap[str] = (XMLNS_XSD, 'string') +_wsdlNameMap[CreateArrayType(str)] = (XMLNS_VMODL_BASE, 'ArrayOfString') # _wsdlMethodNSs store namespaces added to _wsdlMethodMap in _SetWsdlMethod @@ -1806,7 +1798,7 @@ def EnumerateWireIds(self): # Add array type into special names -for name, typ in six.iteritems(vmodlTypes.copy()): +for name, typ in vmodlTypes.copy().items(): if typ is not NoneType: try: arrayType = typ.Array @@ -1976,7 +1968,7 @@ def __init__(self, *args, **kwargs): # Same as dict setdefault, except this will call through our __setitem__ def update(self, *args, **kwargs): - for k, v in six.iteritems(dict(*args, **kwargs)): + for k, v in dict(*args, **kwargs).items(): self[k] = v # Same as dict setdefault, except this will call through our __setitem__ @@ -1989,7 +1981,7 @@ def setdefault(self, key, val=None): def __setitem__(self, key, val): """x.__setitem__(i, y) <==> x[i]=y, where y must be a string""" - if not isinstance(val, string_types): + if not isinstance(val, str): raise TypeError("key %s has non-string value %s of %s" % (key, val, type(val))) return dict.__setitem__(self, key, val) diff --git a/tests/test_connect.py b/tests/test_connect.py index 849e687a..cf377a49 100644 --- a/tests/test_connect.py +++ b/tests/test_connect.py @@ -18,15 +18,11 @@ import tests import unittest import sys +from unittest.mock import patch, MagicMock from pyVim import connect from pyVmomi import vim -if sys.version_info >= (3, 3): - from unittest.mock import patch, MagicMock -else: - from mock import patch, MagicMock - class ConnectionTests(tests.VCRTestBase):