def testEchoDate (server, action, harsh): test = time.gmtime (time.time ()) server = server._sa (action % {'methodname': 'echoDate'}) if SOAP.Config.namespaceStyle == '1999': result = server.echoDate (inputDate = SOAP.timeInstantType (test)) else: result = server.echoDate (inputDate = SOAP.dateTimeType (test)) if not SOAP.Config.typed and type (result) in (type (''), type (u'')): p = SOAP.SOAPParser() result = p.convertDateTime(result, 'timeInstant') if result != test[:6]: raise Exception, "expected %s, got %s" % (repr (test), repr (result))
def testMustUnderstandEqualsOne (server, action, harsh): test = 42 server = server._sa (action % {'methodname': 'echoInteger'}) hd = SOAP.headerType () hd.MustUnderstandThis = SOAP.stringType ("This should fault because " "the mustUnderstand attribute is 1") hd.MustUnderstandThis._setMustUnderstand (1) server = server._hd (hd) try: result = server.echoInteger (inputInteger = test) except SOAP.faultType, e: if harsh and e.faultcode != 'SOAP-ENV:MustUnderstand': raise AttributeError, "unexpected faultcode %s" % e.faultcode return
def main(): host = DEFAULT_HOST port = DEFAULT_PORT try: opts, args = getopt.getopt(sys.argv[1:], '?h:p:', ['help', 'host', 'port']) for opt, arg in opts: if opt in ('-?', '--help'): usage() elif opt in ('-h', '--host'): host = arg elif opt in ('-p', '--port'): port = int(arg) else: raise AttributeError, \ "Recognized but unimplemented option `%s'" % opt except SystemExit: raise except: usage(sys.exc_info()[1]) server = SOAP.SOAPServer((host, port)) server.registerFunction(whichToolkit, namespace) server.registerFunction(countTheEntities) server.registerFunction(easyStructTest) server.registerFunction(echoStructTest) server.registerFunction(manyTypesTest) server.registerFunction(moderateSizeArrayCheck) server.registerFunction(nestedStructTest) server.registerFunction(simpleStructReturnTest) server.serve_forever()
def testMustUnderstandEqualsZero (server, action, harsh): test = 42 server = server._sa (action % {'methodname': 'echoInteger'}) hd = SOAP.headerType () hd.MustUnderstandThis = SOAP.stringType ("This shouldn't fault because " "the mustUnderstand attribute is 0") hd.MustUnderstandThis._setMustUnderstand (0) server = server._hd (hd) result = server.echoInteger (inputInteger = test) if not SOAP.Config.typed: result = int (result) if result != test: raise Exception, "expected %s, got %s" % (test, result)
def testActorShouldFail (server, action, harsh): test = 42 server = server._sa (action % {'methodname': 'echoInteger'}) hd = SOAP.headerType () hd.InteropTestHeader = SOAP.stringType ("This should fault because " "the mustUnderstand attribute is 1") hd.InteropTestHeader._setMustUnderstand (1) hd.InteropTestHeader._setActor ( 'http://schemas.xmlsoap.org/soap/actor/next') server = server._hd (hd) try: result = server.echoInteger (inputInteger = test) except SOAP.faultType, e: if harsh and e.faultcode != 'SOAP-ENV:MustUnderstand': raise AttributeError, "unexpected faultcode %s" % e.faultcode return
def main(): host = DEFAULT_HOST port = None ssl = 0 try: opts = '?h:p:' args = ['help', 'host', 'port'] if SOAP.Config.SSLserver: opts += 's' args += ['ssl'] opts, args = getopt.getopt(sys.argv[1:], opts, args) for opt, arg in opts: if opt in ('-?', '--help'): usage() elif opt in ('-h', '--host'): host = arg elif opt in ('-p', '--port'): port = int(arg) elif opt in ('-s', '--ssl'): ssl = 1 else: raise AttributeError, \ "Recognized but unimplemented option `%s'" % opt except SystemExit: raise except: usage(sys.exc_info()[1]) if port == None: port = [DEFAULT_HTTP_PORT, DEFAULT_HTTPS_PORT][ssl] if ssl: ssl_context = SSL.Context() ssl_context.load_cert('server.pem') else: ssl_context = None server = SOAP.SOAPServer((host, port), namespace=namespace, ssl_context=ssl_context) server.registerFunction(echoFloat) server.registerFunction(echoFloatArray) server.registerFunction(echoInteger) server.registerFunction(echoIntegerArray) server.registerFunction(echoString) server.registerFunction(echoStringArray) server.registerFunction(echoStruct) server.registerFunction(echoStructArray) server.registerFunction(echoVoid) server.registerFunction(echoDate) server.registerFunction(echoBase64) server.serve_forever()
def Buy(serv, sa, epname): import copy serv = serv._sa (sa % {'methodname':'Buy'}) billTo_d = {"name":"Buyer One", "address":"1 1st Street", "city":"New York", "state":"NY", "zipCode":"10000"} shipTo_d = {"name":"Buyer One ", "address":"1 1st Street ", "city":"New York ", "state":"NY ", "zipCode":"10000 "} for k,v in shipTo_d.items(): shipTo_d[k] = v[:-1] itemd1 = SOAP.structType( {"name":"widg1","quantity":200,"price":SOAP.decimalType(45.99), "_typename":"LineItem"}) itemd2 = SOAP.structType( {"name":"widg2","quantity":400,"price":SOAP.decimalType(33.45), "_typename":"LineItem"}) items_d = SOAP.arrayType( [itemd1, itemd2] ) items_d._ns = "http://www.soapinterop.org/Bid" po_d = SOAP.structType( data = {"poID":"myord","createDate":SOAP.dateTimeType(),"shipTo":shipTo_d, "billTo":billTo_d, "items":items_d}) try: # it's called PO by MST (MS SOAP Toolkit), JHawk (.NET Remoting), # Idoox WASP, Paul (SOAP::Lite), PranishK (ATL), GLUE, Aumsoft, # HP, EasySoap, and Jake (Frontier). [Actzero accepts either] return serv.Buy(PO=po_d) except: # called PurchaseOrder by KeithBa return serv.Buy(PurchaseOrder=po_d)
def testActorShouldPass (server, action, harsh): test = 42 server = server._sa (action % {'methodname': 'echoInteger'}) hd = SOAP.headerType () hd.InteropTestHeader = SOAP.stringType ("This shouldn't fault because " "the mustUnderstand attribute is 0") hd.InteropTestHeader._setMustUnderstand (0) hd.InteropTestHeader._setActor ( 'http://schemas.xmlsoap.org/soap/actor/next') server = server._hd (hd) result = server.echoInteger (inputInteger = test) if not SOAP.Config.typed: result = int (result) if result != test: raise Exception, "expected %s, got %s" % (test, result)
def testEchoBase64 (server, action, harsh): test = '\x00\x10\x20\x30\x40\x50\x60\x70\x80\x90\xa0\xb0\xc0\xd0\xe0\xf0' server = server._sa (action % {'methodname': 'echoBase64'}) result = server.echoBase64 (inputBase64 = SOAP.base64Type (test)) if not SOAP.Config.typed: import base64 result = base64.decodestring(result) if result != test: raise Exception, "expected %s, got %s" % (repr (test), repr (result))
def Buy(serv, sa, epname): import copy serv = serv._sa(sa % {'methodname': 'Buy'}) billTo_d = { "name": "Buyer One", "address": "1 1st Street", "city": "New York", "state": "NY", "zipCode": "10000" } shipTo_d = { "name": "Buyer One ", "address": "1 1st Street ", "city": "New York ", "state": "NY ", "zipCode": "10000 " } for k, v in list(shipTo_d.items()): shipTo_d[k] = v[:-1] itemd1 = SOAP.structType({ "name": "widg1", "quantity": 200, "price": SOAP.decimalType(45.99), "_typename": "LineItem" }) itemd2 = SOAP.structType({ "name": "widg2", "quantity": 400, "price": SOAP.decimalType(33.45), "_typename": "LineItem" }) items_d = SOAP.arrayType([itemd1, itemd2]) items_d._ns = "http://www.soapinterop.org/Bid" po_d = SOAP.structType( data={ "poID": "myord", "createDate": SOAP.dateTimeType(), "shipTo": shipTo_d, "billTo": billTo_d, "items": items_d }) try: # it's called PO by MST (MS SOAP Toolkit), JHawk (.NET Remoting), # Idoox WASP, Paul (SOAP::Lite), PranishK (ATL), GLUE, Aumsoft, # HP, EasySoap, and Jake (Frontier). [Actzero accepts either] return serv.Buy(PO=po_d) except: # called PurchaseOrder by KeithBa return serv.Buy(PurchaseOrder=po_d)
def array_to_dict_response(self, params): """ Convert the array element recieved by SOAP in a Dictionary . Param: params -- The array """ dict = {} rs = SOAP.simplify(params) if rs: for test in rs['item']: dict[test['key']] = test['value'] return dict else: return False
def RequestForQuote(ProductName, Quantity): # type-checks and makes sure Quantity >= 1 global NUMREQUESTS NUMREQUESTS += 1 if Quantity < 1: raise ValueError("must order at least 1") else: import whrandom mult = whrandom.random() times = 0 while mult > 0.25: mult = mult - 0.25 times += 1 mult += 0.5 mult = round(mult, 3) print(mult, times) return SOAP.doubleType(round(mult*int(Quantity),2))
def array_to_dict_response(self, params): """ Convert the array element recieved by SOAP in a Dictionary . Param: params -- The array """ dictionary = {} rs = SOAP.simplify(params) if isinstance(rs, list): for test in rs: dictionary[test['item']['key']] = test['item']['value'] return dictionary elif isinstance(rs, dict): for test in rs['item']: dictionary[test['key']] = test['value'] return dictionary else: return False
def echoDate(inputDate): return SOAP.dateTimeType(inputDate)
def echoBase64(inputBase64): return SOAP.binaryType(inputBase64)
#!/usr/bin/env python import time from SOAPpy import SOAP srv = SOAP.SOAPProxy('http://localhost:10080/') for p in ('good param', 'ok param'): ret = srv.badparam(p) if isinstance(ret, SOAP.faultType): print ret else: print 'ok' dt = SOAP.dateTimeType(time.localtime(time.time())) print srv.dt(dt)
methodnum = 1 try: opts, args = getopt.getopt(sys.argv[1:], 'p:m:', ['method', 'port']) for opt, arg in opts: if opt in ('-m', '--method'): if arg == '?': methodUsage() methodnum = int(arg) elif opt in ('-p', '--port'): port = int(arg) else: raise AttributeError, "Recognized but unimpl option '%s'" % opt except SystemExit: raise except: usage() ep = "http://208.177.157.221:%d/xmethodsInterop" % (port) sa = "urn:soapinterop" ns = "http://www.soapinterop.org/Bid" serv = SOAP.SOAPProxy(ep, namespace=ns, soapaction=sa) if methodnum == 1: print serv.Monitor(str="actzero") elif methodnum == 2: print serv.Clear(str="actzero") else: print "invalid methodnum" methodUsage()
def manyTypesTest(num, bool, state, doub, dat, bin): return [ num, SOAP.booleanType(bool), state, doub, SOAP.dateTimeType(dat), bin ]
def whichToolkit(): return SOAP.SOAPUserAgent()
def manyTypesTest (num, bool, state, doub, dat, bin): return [num, SOAP.booleanType (bool), state, doub, SOAP.dateTimeType (dat), bin]
def echoVoid(): return SOAP.voidType()
class MyRequestHandler(SOAP.SOAPRequestHandler): def do_GET(self): #print dir(self) print self.headers # look at "Accept: " lines and if they want html, then # redirect them to semwalker? Nah..... self.send_response(200) self.send_header("Content-type", "application/rdf+xml") self.end_headers() self.wfile.write("<!-- Run semwalker to look at this! -->") def do_HEAD(self): self.send_response(200) self.send_header("Content-type", "text/plain") self.send_header("X-Random-Message", "I love you!") self.end_headers() server = SOAP.SOAPServer(("localhost", 0), MyRequestHandler) port = server.socket.getsockname()[1] print '# waiting at port', port server.registerFunction(query) server.registerFunction(queryAbout) maitred.readyAtPort(port) server.serve_forever()
def RequestForQuote(ProductName, Quantity): # type-checks and makes sure Quantity >= 1 global NUMREQUESTS NUMREQUESTS += 1 if Quantity < 1: raise ValueError, "must order at least 1" else: import whrandom mult = whrandom.random() times = 0 while mult > 0.25: mult = mult - 0.25 times += 1 mult += 0.5 mult = round(mult, 3) print mult, times return SOAP.doubleType(round(mult*int(Quantity),2)) def Buy(**kw): global NUMBUYS NUMBUYS += 1 try: PurchaseOrder = kw["PurchaseOrder"] except: PurchaseOrder = kw["PO"] try: POkeys = PurchaseOrder['_keyord'] POkeys.sort() POkeys_expected = ["shipTo","billTo","items","poID","createDate"] POkeys_expected.sort()
def RequestForQuote(ProductName, Quantity): # type-checks and makes sure Quantity >= 1 global NUMREQUESTS NUMREQUESTS += 1 if Quantity < 1: raise ValueError, "must order at least 1" else: import whrandom mult = whrandom.random() times = 0 while mult > 0.25: mult = mult - 0.25 times += 1 mult += 0.5 mult = round(mult, 3) print mult, times return SOAP.doubleType(round(mult * int(Quantity), 2)) def Buy(**kw): global NUMBUYS NUMBUYS += 1 try: PurchaseOrder = kw["PurchaseOrder"] except: PurchaseOrder = kw["PO"] try: POkeys = PurchaseOrder['_keyord'] POkeys.sort() POkeys_expected = ["shipTo", "billTo", "items", "poID", "createDate"] POkeys_expected.sort()
#!/usr/bin/env python import sys from SOAPpy import SOAP # Uncomment to see outgoing HTTP headers and SOAP and incoming SOAP. SOAP.Config.debug = 1 SOAP.Config.BuildWithNoType = 0 SOAP.Config.BuildWithNoNamespacePrefix = 0 if len(sys.argv) > 1 and sys.argv[1] == '-s': server = SOAP.SOAPProxy("https://*****:*****@localhost:8080/", encoding=None) x = server.sopa() print(x)
def main (): stats = 1 total = 0 fail = 0 failok = 0 succeed = 0 exitonfailure = 0 harsh = 0 invert = 0 printtrace = 0 methodnums = None notimp = 0 output = 'f' servers = DEFAULT_SERVERS_FILE started = time.time () try: opts, args = getopt.getopt (sys.argv[1:], '?dehim:nNo:s:tT', ['help', 'debug', 'exit-on-failure', 'harsh', 'invert', 'method', 'no-stats', 'no-statistics', 'no-boring-statistics', 'no-boring-stats', 'output', 'servers=', 'stacktrace', 'always-stacktrace']) for opt, arg in opts: if opt in ('-?', '--help'): usage () elif opt in ('-d', '--debug'): SOAP.Config.debug = 1 elif opt in ('-h', '--harsh'): harsh = 1 elif opt in ('-i', '--invert'): invert = 1 elif opt in ('-e', '--exit-on-failure'): exitonfailure = 1 elif opt in ('-m', '--method'): if arg == '?': methodUsage () methodnums = str2list (arg) elif opt in ('-n', '--no-stats', '--no-statistics'): stats = 0 elif opt in ('-N', '--no-boring-stats', '--no-boring-statistics'): stats = -1 elif opt in ('-o', '--output'): output = arg elif opt in ('-s', '--servers'): servers = arg elif opt in ('-t', '--stacktrace'): printtrace = 1 elif opt in ('-T', '--always-stacktrace'): printtrace = 2 else: raise AttributeError, \ "Recognized but unimplemented option `%s'" % opt except SystemExit: raise except: usage (sys.exc_info ()[1]) if 'a' in output: output = 'fFns' servers = readServers (servers) if methodnums == None: methodnums = range (1, len (DEFAULT_METHODS) + 1) limitre = re.compile ('|'.join (args), re.IGNORECASE) for s in servers: if (not not limitre.match (s['name'])) == invert: continue try: typed = s['typed'] except: typed = 1 try: style = s['style'] except: style = 1999 SOAP.Config.typed = typed SOAP.Config.namespaceStyle = style server = SOAP.SOAPProxy (s['endpoint'], ("m", s['namespace'])) for num in (methodnums): if num > len (DEFAULT_METHODS): break total += 1 name = DEFAULT_METHODS[num - 1] title = '%s: %s (#%d)' % (s['name'], name, num) if SOAP.Config.debug: print "%s:" % title try: fn = globals ()['test' + name[0].upper () + name[1:]] except KeyboardInterrupt: raise except: if 'n' in output: print title, "test not yet implemented" notimp += 1 continue try: fn (server, s['soapaction'], harsh) if s['nonfunctional'].has_key (name): print title, \ "succeeded despite being marked nonfunctional" if 's' in output: print title, "succeeded" succeed += 1 except KeyboardInterrupt: raise except: fault = str (sys.exc_info ()[1]) if fault[-1] == '\n': fault = fault[:-1] if s['nonfunctional'].has_key (name): if 'F' in output: t = 'as expected' if s['nonfunctional'][name] != '': t += ', ' + s['nonfunctional'][name] print title, "failed (%s) -" % t, fault if printtrace > 1: traceback.print_exc () failok += 1 else: if 'f' in output: print title, "failed -", fault if printtrace: traceback.print_exc () fail += 1 if exitonfailure: return -1 if stats: print " Tests started at:", time.ctime (started) if stats > 0: print " Total tests: %d" % total print " Successes: %d (%3.2f%%)" % \ (succeed, 100.0 * succeed / total) if stats > 0 or fail > 0: print "Failed unexpectedly: %d (%3.2f%%)" % \ (fail, 100.0 * fail / total) if stats > 0: print " Failed as expected: %d (%3.2f%%)" % \ (failok, 100.0 * failok / total) if stats > 0 or notimp > 0: print " Not implemented: %d (%3.2f%%)" % \ (notimp, 100.0 * notimp / total) return fail + notimp
def main(): servers = DEFAULT_SERVERS_FILE methodnums = None output = 'f' invert = 0 succeed = 0 printtrace = 0 stats = 1 total = 0 fail = 0 failok = 0 notimp = 0 try: opts, args = getopt.getopt( sys.argv[1:], '?dm:io:s:t', ['help', 'method', 'debug', 'invert', 'output', 'servers=']) for opt, arg in opts: if opt in ('-?', '--help'): usage() elif opt in ('-d', '--debug'): SOAP.Config.debug = 1 elif opt in ('-i', '--invert'): invert = 1 elif opt in ('-m', '--method'): if arg == '?': methodUsage() methodnums = str2list(arg) elif opt in ('-o', '--output'): output = arg elif opt in ('-s', '--servers'): servers = arg else: raise AttributeError( "Recognized but unimplemented option `%s'" % opt) except SystemExit: raise except: usage(sys.exc_info()[1]) if 'a' in output: output = 'fFns' servers = readServers(servers) if methodnums == None: methodnums = list(range(1, len(DEFAULT_METHODS) + 1)) limitre = re.compile('|'.join(args), re.IGNORECASE) for s in servers: if (not not limitre.match(s['name'])) == invert: continue serv = SOAP.SOAPProxy(s['endpoint'], namespace=s['namespace']) for num in (methodnums): if num > len(DEFAULT_METHODS): break total += 1 name = DEFAULT_METHODS[num - 1] title = '%s: %s (#%d)' % (s['name'], name, num) try: fn = globals()[name] except KeyboardInterrupt: raise except: if 'n' in output: print(title, "test not yet implemented") notimp += 1 continue try: res = fn(serv, s['soapaction'], s['name']) if name in s['nonfunctional']: print(title, "succeeded despite marked nonfunctional") elif 's' in output: print(title, "succeeded ") succeed += 1 except KeyboardInterrupt: print("fail") raise except: if name in s['nonfunctional']: if 'F' in output: t = 'as expected' if s['nonfunctional'][name] != '': t += ', ' + s['nonfunctional'][name] print(title, "failed (%s) -" % t, sys.exc_info()[1]) failok += 1 else: if 'f' in output: print(title, "failed -", str(sys.exc_info()[1])) fail += 1 if stats: print(" Tests ended at:", time.ctime(time.time())) if stats > 0: print(" Total tests: %d" % total) print(" Successes: %d (%3.2f%%)" % \ (succeed, 100.0 * succeed / total)) if stats > 0 or fail > 0: print("Failed unexpectedly: %d (%3.2f%%)" % \ (fail, 100.0 * fail / total)) if stats > 0: print(" Failed as expected: %d (%3.2f%%)" % \ (failok, 100.0 * failok / total)) if stats > 0 or notimp > 0: print(" Not implemented: %d (%3.2f%%)" % \ (notimp, 100.0 * notimp / total)) return fail + notimp
NUMPINGS = 0 return "(Buys, RequestForQuote(s),SimpleBuy(s), Ping(s)) = " + \ repr( (NUMBUYS,NUMREQUESTS,NUMSIMPLEBUYS, NUMPINGS) ) else: raise ValueError("not the right string") if __name__ == "__main__": if len(sys.argv) > 1: try: port = int(sys.argv[1]) if port not in list(range(2000,15000)): raise ValueError except: print("port must be a number between 2000 and 15000") sys.exit(1) else: port = 9000 namespace = "http://www.soapinterop.org/Bid" server = SOAP.SOAPServer( ('zoo',port) ) server.registerKWFunction(SimpleBuy, namespace ) server.registerKWFunction(RequestForQuote, namespace ) server.registerKWFunction(Buy, namespace ) server.registerKWFunction(Ping, namespace ) server.registerKWFunction(Monitor, namespace ) server.registerKWFunction(Clear, namespace ) try: server.serve_forever() except KeyboardInterrupt: pass