def check_empty_array(self): """Empty Array returned as list() """ data = [] s = str(SoapWriter().serialize(data, TC.Any(aslist=True))) p = ParsedSoap(s).Parse(TC.Any()) self.assertTrue(data == p, 'expecting "%s", got "%s"' % (data, p))
def check_any_nill(self): result = ['23', {'a' : None, 'b': 5}] soap = str(SoapWriter().serialize(result, TC.Any(pname="NilRequest", nillable=True, aslist=True))) ps = ParsedSoap(soap) tc = TC.Any(nillable=True) pyobj = ps.Parse(tc)
def serializeRequest(request): tc = getattr(request, 'typecode', None) sw = SoapWriter(nsdict={}, header=True, outputclass=None, encodingStyle=None) return str(sw.serialize(request, tc))
def test_local_serialize_schema(self): from ZSI import SoapWriter from ZSI import _child_elements from xml.dom.ext.reader import PyExpat msg = self.client_module.DSQueryRegistrySoapOut() msg.DSQueryRegistryResult = msg.new_DSQueryRegistryResult() msg.DSQueryRegistryResult.Any = 'hi' input = open('wsdl/nvo-admin.wsdl').read() reader = PyExpat.Reader() dom = reader.fromString(input) dnode = _child_elements(dom)[0] tnode = _child_elements(dnode)[0] snode = _child_elements(tnode)[0] msg.DSQueryRegistryResult.Schema = snode sw = SoapWriter() sw.serialize(msg) soap = str(sw) print(soap) ps = ParsedSoap(soap) pyobj = ps.Parse(msg.typecode) self.assertEqual(pyobj.DSQueryRegistryResult.Any, msg.DSQueryRegistryResult.Any) self.assertTrue(_is_element(pyobj.DSQueryRegistryResult.Schema)) print(_get_element_nsuri_name(pyobj.DSQueryRegistryResult.Schema)) self.assertEqual( _get_element_nsuri_name(pyobj.DSQueryRegistryResult.Schema), ('http://www.w3.org/2001/XMLSchema', 'schema'))
def check_empty_struct(self): """Empty Struct is None, maybe dict() makes more sense, but this is fairly hard to determine if not typed (which is the norm). """ data = {} s = str(SoapWriter().serialize(data, TC.Any())) p = ParsedSoap(s).Parse(TC.Any()) self.assertTrue(p == None, 'expecting "%s", got "%s"' % (None, p))
def _cache_soap(self, name, res): from ZSI import SoapWriter sw = SoapWriter() xml = str(sw.serialize(res)) self._soapcache[name] = xml # hack to get the cache to save self._soapcache = self._soapcache
def deserialize(objectToDeserialize): sw = SoapWriter(nsdict={}, header=True, outputclass=None, encodingStyle=None) tc = TC.Any(pname=None, aslist=False) deserializedObject = sw.serialize(objectToDeserialize, tc).body root = etree.XML(str(deserializedObject)) body = root[0] return etree.tostring(body, encoding='utf-8', pretty_print=True)
def AsSOAP(self, **kw): header = self.DataForSOAPHeader() sw = SoapWriter(**kw) self.serialize(sw) if header is not None: sw.serialize_header(header, header.typecode, typed=False) return str(sw)
def check_any_dict_list_rpcenc(self): sw = SoapWriter() testObj = [{"a":1,"b":2}, {"d":4,"e":5}, {"f":{"x":9}, "g":[6,7.0]}] typecode = TC.Any(aslist=True) sw.serialize(testObj, typecode=typecode) xml = str(sw) ps = ParsedSoap(xml) result = TC.Any().parse(ps.body_root, ps) self.assertTrue(result == testObj)
def check_parse_empty_string(self): # Empty String typecodes = list(TC.Any.parsemap.values()) for tc in [c for c in list(TC.Any.parsemap.values()) if isinstance(c, TC.String)]: sw = SoapWriter() sw.serialize("", typecode=tc, typed=True) soap = str(sw) ps = ParsedSoap(soap) parsed = ps.Parse(TC.Any()) self.assertEqual("", parsed)
def lather(obj, tc=None): ''' Serial a python object into SOAP, return the SOAP. If tc is None, expect obj to have a .typecode attribute. ''' if tc is None: tc = obj.typecode IO = StringIO() S = SoapWriter(IO) S.serialize(obj, tc) return str(S)
def check_parse_empty_all(self): # None skip = [TC.FPEnumeration, TC.Enumeration, TC.IEnumeration, TC.List, TC.Integer] for typeclass in [c for c in list(TC.__dict__.values()) if type(c) in [type,type] and not issubclass(c, TC.String) and issubclass(c, TC.SimpleType)]: if typeclass in skip: continue tc = typeclass() sw = SoapWriter() sw.serialize(None, typecode=tc, typed=True) soap = str(sw) ps = ParsedSoap(soap) parsed = ps.Parse(TC.Any()) self.assertEqual(None, parsed)
def test_local_generateMessageAttachment(self): """doc/lit, generating a message using MIME attachment, we don't have the server side implementation so we can really do a full test yet """ from TestService_server import uploadFileRequest #stubs were properly generated request = uploadFileRequest() request._name = "TestService_client.py" request._attachment = open("stubs/TestService_client.py", 'r') sw = SoapWriter({}, header=True, outputclass=None, encodingStyle=None) sw.serialize(request) print "the request message is: " + str(sw)
def checkt7(self): ps = ParsedSoap(text) tcdict = TC.Apache.Map('c-gensym1') tclist = TC.Apache.Map('c-gensym1', aslist=1) d = tcdict.parse(ps.body_root, ps) self.assertEqual(d, {u'a': 123, '\x00\x01': 456}) #print 'as dictionary\n', d l = tclist.parse(ps.body_root, ps) self.assertEqual(l, [('\x00\x01', 456), (u'a', 123)]) #print '\n', '=' * 30 #print 'as list\n', l #print '\n', '=' * 30 sw = SoapWriter() sw.serialize(d, tcdict) #print >>sys.stdout, sw #print '\n', '=' * 30 sw = SoapWriter() sw.serialize(l, tclist)
def newFunc(kw): try: log("%s(%s)\n" % (str(oldFunc.__name__), str(kw))) kw = trans.transArgs(oldFunc.__name__, kw) res = oldFunc(**kw) res = fixObject(res) log("%s(%s) -> %s\n" % (str(oldFunc.__name__), str(kw), str(res))) sw = SoapWriter() sw.serialize(res, res.typecode) res = trans.transResult(oldFunc.__name__, minidom.parseString(str(sw))) return res except: log("%s\n" % (traceback.format_exc(sys.exc_info()))) raise
def test_local_anyType(self): """rpc/lit, testing if <any/> lax content handling should get back dicts and strings """ ps = ParsedSoap(MSG) pyobj = ps.Parse(self.client_module.EventApproximatesSoapOut.typecode) any = { 'PoolTotals': { 'Pool': { 'Total': u'4117.66', 'ENumbers': None, 'JackpotNet': None } }, 'Approximates': { 'Pool': { 'Win': u'3.90,0.00,10.40,11.80,4.70,29.50,29.90,2.40,19.80,0.00', 'Place': u'1.04,0.00,2.80,5.90,2.00,5.20,7.40,1.04,4.00,0.00' } } } self.failUnless( pyobj.EventApproximatesResult.Any == any, 'Failed match:\n %s\n\n%s' % (pyobj.EventApproximatesResult.Any, any)) pyobj.EventApproximatesResult.Any = dict( pyobj.EventApproximatesResult.Any) sw = SoapWriter() sw.serialize(pyobj) print str(sw) ps2 = ParsedSoap(str(sw)) pyobj2 = ps.Parse(self.client_module.EventApproximatesSoapOut.typecode) print "EAR: ", pyobj2.EventApproximatesResult print "Any: ", pyobj2.EventApproximatesResult.Any self.failUnless( pyobj.EventApproximatesResult.Any == pyobj2.EventApproximatesResult.Any, 'Failed match:\n %s\n\n%s' % (pyobj.EventApproximatesResult.Any, pyobj2.EventApproximatesResult.Any))
def test_local_NoMessagePart(self): ## msg = self.client_module.HelloRequest() msg = None rsp = self.client_module.HelloResponse() # Core functionality required s = SoapWriter() xml = str(s) print xml # Core functionality required ps = ParsedSoap(xml) self.failUnless(ps.body.childNodes == 0, "Empty Body expected: " + ps.body.childNodes) self.failUnless(ps.body_root == None, "Body root should be None: " + ps.body_root) pyobj = ps.Parse(None) self.failUnless(pyobj == None, "pyobj should be None: " + pyobj)
def check_builtins(self): myInt,myLong,myStr,myDate,myFloat = 123,2147483648,\ "hello", time.gmtime(), 1.0001 orig = [myInt, myLong, myStr, myDate, myFloat] sw = SoapWriter() sw.serialize(orig, typecode=TC.Any(pname="builtins", aslist=True)) ps = ParsedSoap(str(sw)) parsed = ps.Parse(TC.Any()) self.assertEqual(len(orig), len(parsed)) self.assertEqual(myInt, parsed[0]) self.assertEqual(myLong, parsed[1]) self.assertEqual(myStr, parsed[2]) self.assertEqual(myDate[0:6], parsed[3][0:6]) self.assertEqual(myFloat, parsed[4]) self.assertEqual(type(myInt), type(parsed[0])) self.assertEqual(type(myLong), type(parsed[1])) self.assertEqual(type(myStr), type(parsed[2])) self.assertEqual(tuple, type(parsed[3])) self.assertEqual(type(myFloat), type(parsed[4]))
objType = getattr(SRW.types, classname) xreq = objType(operation + "Request", opts=opts, config=config, protocol="SRU") xreq.calledAt = path result = self.call(xreq) style = "" except AttributeError, err: result = self.processUnknownOperation( operation, err, config) reply = StringIO.StringIO() if (req.method == "GET"): sw = SoapWriter(reply, envelope=0) else: sw = SoapWriter(reply, nsdict=SRW.protocolNamespaces) try: sw.serialize(result, inline=1) sw.close() text = reply.getvalue() except Exception, err: self.send_fault(Fault(Fault.Client, 'Busted (%s)' % str(err)), req) return if (req.method == "GET"): if xreq and hasattr(xreq, 'stylesheet') and xreq.stylesheet: headerText = u'<?xml version="1.0"?>\n<?xml-stylesheet type="text/xsl" href="%s"?>\n' % ( xreq.stylesheet)
def test_local_substitute_SessionManager(self): # BUG [ 1755740 ] Multiple calls to the same method MSG = """<?xml version="1.0" encoding="UTF-8"?> <soapenv:Envelope xmlns:soapenc="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <soapenv:Body> <RetrieveServiceContentResponse xmlns="urn:vim2"> <returnval> <rootFolder type="Folder">group-d1</rootFolder> <propertyCollector type="PropertyCollector">propertyCollector</propertyCollector> <about> <name>VMware VirtualCenter</name> <fullName>VMware VirtualCenter 2.0.1 build-32042</fullName> <vendor>VMware, Inc.</vendor> <version>2.0.1</version> <build>32042</build> <localeVersion>INTL</localeVersion> <localeBuild>000</localeBuild> <osType>win32-x86</osType> <productLineId>vpx</productLineId> <apiType>VirtualCenter</apiType> <apiVersion>2.0.0</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> </soapenv:Body> </soapenv:Envelope>""" # Parse it out ps = ParsedSoap(MSG) pyobj = ps.Parse( self.client_module.RetrieveServiceContentResponseMsg.typecode) sessionMgr = pyobj.Returnval.SessionManager # Serialize SessionManager in different context msg = self.client_module.LogoutRequestMsg() msg._this = sessionMgr SoapWriter().serialize(msg) # Parse it out: was failing # ZSI.EvaluateException: Element "__this" missing from complexType # [Element trace: /soapenv:Envelope/soapenv:Body/RetrieveServiceContentResponse/returnval] ps = ParsedSoap(MSG) pyobj = ps.Parse( self.client_module.RetrieveServiceContentResponseMsg.typecode)
if len(mu): uri, localname = mu[0] print >> OUT, FaultFromNotUnderstood(uri, localname).AsSOAP() self.fail() try: player = ps.Parse(Player) except EvaluateException, e: print >> OUT, FaultFromZSIException(e).AsSOAP() self.fail() try: import operator total = reduce(operator.add, player.Scores, 0) result = Average(foo(total, len(player.Scores))) sw = SoapWriter().serialize(result) str(sw) #print >>OUT, str(sw) except Exception, e: print >> OUT, FaultFromException(e, 0, sys.exc_info()[2]).AsSOAP() self.fail() def makeTestSuite(): suite = unittest.TestSuite() suite.addTest(unittest.makeSuite(t2TestCase, "check")) return suite class Player: '''Input class.'''
def _Dispatch(ps, modules, SendResponse, SendFault, nsdict={}, typesmodule=None, gettypecode=gettypecode, rpc=False, docstyle=False, **kw): '''Find a handler for the SOAP request in ps; search modules. Call SendResponse or SendFault to send the reply back, appropriately. Behaviors: default -- Call "handler" method with pyobj representation of body root, and return a self-describing request (w/typecode). Parsing done via a typecode from typesmodule, or Any. docstyle -- Call "handler" method with ParsedSoap instance and parse result with an XML typecode (DOM). Behavior, wrap result in a body_root "Response" appended message. rpc -- Specify RPC wrapper of result. Behavior, ignore body root (RPC Wrapper) of request, parse all "parts" of message via individual typecodes. Expect the handler to return the parts of the message, whether it is a dict, single instance, or a list try to serialize it as a Struct but if this is not possible put it in an Array. Parsing done via a typecode from typesmodule, or Any. ''' global _client_binding try: what = str(ps.body_root.localName) # See what modules have the element name. if modules is None: modules = ( sys.modules['__main__'], ) handlers = [ getattr(m, what) for m in modules if hasattr(m, what) ] if len(handlers) == 0: raise TypeError("Unknown method " + what) # Of those modules, see who's callable. handlers = [ h for h in handlers if callable(h) ] if len(handlers) == 0: raise TypeError("Unimplemented method " + what) if len(handlers) > 1: raise TypeError("Multiple implementations found: %s" % handlers) handler = handlers[0] _client_binding = ClientBinding(ps) if docstyle: result = handler(ps.body_root) tc = TC.XML(aslist=1, pname=what+'Response') elif not rpc: try: tc = gettypecode(typesmodule, ps.body_root) except Exception: tc = TC.Any() try: arg = tc.parse(ps.body_root, ps) except EvaluateException as ex: SendFault(FaultFromZSIException(ex), **kw) return try: result = handler(arg) except Exception as ex: SendFault(FaultFromZSIException(ex), **kw) return try: tc = result.typecode except AttributeError as ex: SendFault(FaultFromZSIException(ex), **kw) return elif typesmodule is not None: kwargs = {} for e in _child_elements(ps.body_root): try: tc = gettypecode(typesmodule, e) except Exception: tc = TC.Any() try: kwargs[str(e.localName)] = tc.parse(e, ps) except EvaluateException as ex: SendFault(FaultFromZSIException(ex), **kw) return result = handler(**kwargs) aslist = False # make sure data is wrapped, try to make this a Struct if isinstance(result,_seqtypes): for _ in result: aslist = hasattr(result, 'typecode') if aslist: break elif not isinstance(result, dict): aslist = not hasattr(result, 'typecode') result = (result,) tc = TC.Any(pname=what+'Response', aslist=aslist) else: # if this is an Array, call handler with list # if this is an Struct, call handler with dict tp = _find_type(ps.body_root) isarray = ((isinstance(tp, (tuple,list)) and tp[1] == 'Array') or _find_arraytype(ps.body_root)) data = _child_elements(ps.body_root) tc = TC.Any() if isarray and len(data) == 0: result = handler() elif isarray: try: arg = [ tc.parse(e, ps) for e in data ] except EvaluateException as e: #SendFault(FaultFromZSIException(e), **kw) SendFault(RuntimeError("THIS IS AN ARRAY: %s" %isarray)) return result = handler(*arg) else: try: kwarg = dict([ (str(e.localName),tc.parse(e, ps)) for e in data ]) except EvaluateException as e: SendFault(FaultFromZSIException(e), **kw) return result = handler(**kwarg) # reponse typecode #tc = getattr(result, 'typecode', TC.Any(pname=what+'Response')) tc = TC.Any(pname=what+'Response') sw = SoapWriter(nsdict=nsdict) sw.serialize(result, tc) return SendResponse(str(sw), **kw) except Fault as e: return SendFault(e, **kw) except Exception as e: # Something went wrong, send a fault. return SendFault(FaultFromException(e, 0, sys.exc_info()[2]), **kw)
def processResponse(cls, output, **kw): sw = SoapWriter(outputclass=cls.writerClass) sw.serialize(output) return sw
def Send(self, url, opname, obj, nsdict={}, soapaction=None, wsaction=None, endPointReference=None, soapheaders=(), **kw): '''Send a message. If url is None, use the value from the constructor (else error). obj is the object (data) to send. Data may be described with a requesttypecode keyword, the default is the class's typecode (if there is one), else Any. Try to serialize as a Struct, if this is not possible serialize an Array. If data is a sequence of built-in python data types, it will be serialized as an Array, unless requesttypecode is specified. arguments: url -- opname -- struct wrapper obj -- python instance key word arguments: nsdict -- soapaction -- wsaction -- WS-Address Action, goes in SOAP Header. endPointReference -- set by calling party, must be an EndPointReference type instance. soapheaders -- list of pyobj, typically w/typecode attribute. serialized in the SOAP:Header. requesttypecode -- ''' url = url or self.url endPointReference = endPointReference or self.endPointReference # Serialize the object. d = {} d.update(self.nsdict) d.update(nsdict) sw = SoapWriter( nsdict=d, header=True, outputclass=self.writerclass, encodingStyle=kw.get('encodingStyle'), ) requesttypecode = kw.get('requesttypecode') if kw.has_key('_args'): #NamedParamBinding tc = requesttypecode or TC.Any(pname=opname, aslist=False) sw.serialize(kw['_args'], tc) elif not requesttypecode: tc = getattr(obj, 'typecode', None) or TC.Any(pname=opname, aslist=False) try: if type(obj) in _seqtypes: obj = dict(map(lambda i: (i.typecode.pname, i), obj)) except AttributeError: # can't do anything but serialize this in a SOAP:Array tc = TC.Any(pname=opname, aslist=True) else: tc = TC.Any(pname=opname, aslist=False) sw.serialize(obj, tc) else: sw.serialize(obj, requesttypecode) for i in soapheaders: sw.serialize_header(i) # # Determine the SOAP auth element. SOAP:Header element if self.auth_style & AUTH.zsibasic: sw.serialize_header(_AuthHeader(self.auth_user, self.auth_pass), _AuthHeader.typecode) # # Serialize WS-Address if self.wsAddressURI is not None: if self.soapaction and wsaction.strip('\'"') != self.soapaction: raise WSActionException, 'soapAction(%s) and WS-Action(%s) must match'\ %(self.soapaction,wsaction) self.address = Address(url, self.wsAddressURI) self.address.setRequest(endPointReference, wsaction) self.address.serialize(sw) # # WS-Security Signature Handler if self.sig_handler is not None: self.sig_handler.sign(sw) scheme, netloc, path, nil, nil, nil = urlparse.urlparse(url) transport = self.transport if transport is None and url is not None: if scheme == 'https': transport = self.defaultHttpsTransport elif scheme == 'http': transport = self.defaultHttpTransport else: raise RuntimeError, 'must specify transport or url startswith https/http' # Send the request. if issubclass(transport, httplib.HTTPConnection) is False: raise TypeError, 'transport must be a HTTPConnection' soapdata = str(sw) self.h = transport(netloc, None, **self.transdict) self.h.connect() self.SendSOAPData(soapdata, url, soapaction, **kw)