Skip to content

Commit

Permalink
python3: fix serializer
Browse files Browse the repository at this point in the history
Python 3 series improper serialization
... introduces a 'b' character in front of string.

fixes #90
  • Loading branch information
hartsock committed Jul 28, 2014
1 parent 66e515b commit 4ab4560
Show file tree
Hide file tree
Showing 3 changed files with 111 additions and 3 deletions.
16 changes: 13 additions & 3 deletions pyVmomi/SoapAdapter.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,11 @@
## Localized MethodFault type
LocalizedMethodFault = GetVmodlType("vmodl.LocalizedMethodFault")

def encode(string, encoding):
if PY2:
return string.encode(encoding)
return u(string)

## Escape <, >, &
def XmlEscape(xmlStr):
escaped = xmlStr.replace("&", "&amp;").replace(">", "&gt;").replace("<", "&lt;")
Expand Down Expand Up @@ -316,7 +321,7 @@ def _Serialize(self, val, info, defNS):
ns, name = GetQualifiedWsdlName(Type(val))
attr += ' type="{0}"'.format(name)
self.writer.write('<{0}{1}>{2}</{3}>'.format(info.name, attr,
val._moId.encode(self.encoding),
encode(val._moId, self.encoding),
info.name))
elif isinstance(val, list):
if info.type is object:
Expand Down Expand Up @@ -399,7 +404,8 @@ def _Serialize(self, val, info, defNS):
val = val.decode('UTF-8')
result = XmlEscape(val)
self.writer.write('<{0}{1}>{2}</{0}>'.format(info.name, attr,
result.encode(self.encoding)))
encode(result,
self.encoding)))

## Serialize a a data object (internal)
#
Expand Down Expand Up @@ -576,7 +582,11 @@ def StartElementHandler(self, tag, attr):
if not self.stack:
if self.isFault:
ns, name = self.SplitTag(tag)
objType = self.LookupWsdlType(ns, name[:-5])
try:
objType = self.LookupWsdlType(ns, name[:-5])
except KeyError:
message = "{0} was not found in the WSDL".format(name[:-5])
raise VmomiMessageFault(message)
# Only top level soap fault should be deserialized as method fault
deserializeAsLocalizedMethodFault = False
else:
Expand Down
44 changes: 44 additions & 0 deletions tests/fixtures/test_simple_request_serializer.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
interactions:
- request:
body: '<?xml version="1.0" encoding="UTF-8"?>
<soapenv:Envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/"
xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<soapenv:Body><RetrieveServiceContent xmlns="urn:vim25"><_this type="ServiceInstance">ServiceInstance</_this></RetrieveServiceContent></soapenv:Body>
</soapenv:Envelope>'
headers:
Accept-Encoding: ['gzip, deflate']
Content-Type: [text/xml; charset=UTF-8]
Cookie: ['']
SOAPAction: ['"urn:vim2/2.0"']
method: POST
uri: https://vcsa:443/sdk
response:
body: {string: "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<soapenv:Envelope
xmlns:soapenc=\"http://schemas.xmlsoap.org/soap/encoding/\"\n xmlns:soapenv=\"http://schemas.xmlsoap.org/soap/envelope/\"\n
xmlns:xsd=\"http://www.w3.org/2001/XMLSchema\"\n xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">\n<soapenv:Body>\n<RetrieveServiceContentResponse
xmlns=\"urn:vim2\"><returnval><rootFolder type=\"Folder\">group-d1</rootFolder><propertyCollector
type=\"PropertyCollector\">propertyCollector</propertyCollector><about><name>VMware
vCenter Server</name><fullName>VMware vCenter Server 5.5.0 build-1750787 (Sim)</fullName><vendor>VMware,
Inc.</vendor><version>5.5.0</version><build>1750787 (Sim)</build><localeVersion>INTL</localeVersion><localeBuild>000</localeBuild><osType>linux-x64</osType><productLineId>vpx</productLineId><apiType>VirtualCenter</apiType><apiVersion>5.5</apiVersion></about><setting
type=\"OptionManager\">VpxSettings</setting><userDirectory type=\"UserDirectory\">UserDirectory</userDirectory><sessionManager
type=\"SessionManager\">SessionManager</sessionManager><authorizationManager
type=\"AuthorizationManager\">AuthorizationManager</authorizationManager><perfManager
type=\"PerformanceManager\">PerfMgr</perfManager><scheduledTaskManager type=\"ScheduledTaskManager\">ScheduledTaskManager</scheduledTaskManager><alarmManager
type=\"AlarmManager\">AlarmManager</alarmManager><eventManager type=\"EventManager\">EventManager</eventManager><taskManager
type=\"TaskManager\">TaskManager</taskManager><customizationSpecManager type=\"CustomizationSpecManager\">CustomizationSpecManager</customizationSpecManager><customFieldsManager
type=\"CustomFieldsManager\">CustomFieldsManager</customFieldsManager><diagnosticManager
type=\"DiagnosticManager\">DiagMgr</diagnosticManager><licenseManager type=\"LicenseManager\">LicenseManager</licenseManager><searchIndex
type=\"SearchIndex\">SearchIndex</searchIndex></returnval></RetrieveServiceContentResponse>\n</soapenv:Body>\n</soapenv:Envelope>"}
headers:
Cache-Control: [no-cache]
Connection: [Keep-Alive]
Content-Length: ['1948']
Content-Type: [text/xml; charset=utf-8]
Date: ['Mon, 28 Jul 2014 22:02:17 GMT']
Set-Cookie: ['vmware_soap_session="52d2bdd9-aec7-5f5c-652e-09737979ce13"; Path=/;
HttpOnly; Secure; ']
status: {code: 200, message: OK}
version: 1
54 changes: 54 additions & 0 deletions tests/test_serializer.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
# VMware vSphere Python SDK
# Copyright (c) 2008-2014 VMware, Inc. All Rights Reserved.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
from tests import fixtures_path
import unittest
import vcr


from pyVmomi import SoapStubAdapter
from pyVmomi import vim

class SerializerTests(unittest.TestCase):

def test_simple_request_serializer(self):
def request_matcher(r1, r2):
soap_msg = ('<soapenv:Body>'
'<RetrieveServiceContent xmlns="urn:vim25">'
'<_this type="ServiceInstance">'
'ServiceInstance'
'</_this>'
'</RetrieveServiceContent>'
'</soapenv:Body>')
if soap_msg in r1.body:
return True
raise SystemError('serialization error occurred')

my_vcr = vcr.VCR()
my_vcr.register_matcher('request_matcher', request_matcher)

with my_vcr.use_cassette(
'test_simple_request_serializer.yaml',
cassette_library_dir=fixtures_path,
record_mode='none',
match_on=['request_matcher']) as cass:
host = 'vcsa'
port = 443
stub = SoapStubAdapter(host, port)
si = vim.ServiceInstance("ServiceInstance", stub)
content = si.RetrieveContent()
self.assertTrue(content is not None)
self.assertTrue(
'<_this type="ServiceInstance">ServiceInstance</_this>'
in cass.requests[0].body)

0 comments on commit 4ab4560

Please sign in to comment.