def __init__(self, studyLocation, proxyStr, proxyUsr, proxyPass, isTrace): """Constructor """ self._logger = logging.getLogger(__name__) logging.config.fileConfig("logging.ini", disable_existing_loggers=False) proxies = None if proxyStr: proxies = pysimplesoap.client.parse_proxy(proxyStr) self._logger.info("OC Event SOAP services with proxies: " + str(proxies)) self._logger.info("OC Event SOAP services with auth: " + str(proxyUsr)) if proxies: self.client = SoapClient(location=studyLocation, namespace=STUDYNAMESPACE, action=STUDYACTION, soap_ns='soapenv', ns="v1", trace=isTrace, proxy=proxies, username=proxyUsr, password=proxyPass) else: self.client = SoapClient(location=studyLocation, namespace=STUDYNAMESPACE, action=STUDYACTION, soap_ns='soapenv', ns="v1", trace=isTrace, username=proxyUsr, password=proxyPass)
def test_validar(self): "Prueba de envío de un comprovante electrónico" WSDL = 'https://celcer.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantes?wsdl' # https://cel.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantes?wsdl client = SoapClient(wsdl=WSDL, ns="ec") ret = client.validarComprobante(xml="cid:1218403525359") self.assertEquals(ret, {'RespuestaRecepcionComprobante': {'comprobantes': [{'comprobante': {'mensajes': [{'mensaje': {'identificador': '35', 'mensaje': 'ARCHIVO NO CUMPLE ESTRUCTURA XML', 'informacionAdicional': 'Content is not allowed in prolog.', 'tipo': 'ERROR'}}], 'claveAcceso': 'N/A'}}], 'estado': 'DEVUELTA'}})
def test_validar(self): "Prueba de envío de un comprobante electrónico" WSDL = 'https://celcer.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantes?wsdl' # https://cel.sri.gob.ec/comprobantes-electronicos-ws/RecepcionComprobantes?wsdl client = SoapClient(wsdl=WSDL, ns="ec") ret = client.validarComprobante(xml='cid:1218403525359') print '>>> ', ret
def _send_ax(): client = SoapClient('http://uzak.audio.com.tr:88/AxIntegrations/AxService.asmx', action='http://tempuri.org/', namespace='http://tempuri.org/', ns='tem') files = os.listdir(AX_QUEUE_FOLDER) for name in files: try: path = os.path.join(AX_QUEUE_FOLDER, name) with open(path, 'r') as infile: data = json.load(infile) #data = dict([(k.encode('utf8'), v.encode('utf8')) for k, v in data.items()]) bilgi = Bilgi.objects.get(pk=int(name)) if bilgi.ax_code: raise Exception('Teklif %s already has an ax_code: %s, no duplicate allowed. %s' % (name, bilgi.ax_code, bilgi.tarih)) resp = client.call('AddWebQuotationForm', **data) ax_code = str(resp.AddWebQuotationFormResult) bilgi.ax_code = ax_code bilgi.save() except Exception as e: if isinstance(e, SoapFault) and e.faultcode == 'soap:Server': body = "%s\n\nRequest:\n\n%s\n\n\nResponse:\n\n%s\n" % (unicode(e).encode('utf8'), client.xml_request, client.xml_response) subject = 'Web Teklif Axapta Server Hatasi' audiomail('*****@*****.**', ['[email protected] '], subject, body) audiomail('*****@*****.**', ['*****@*****.**'], subject, body) logging.exception('hello') else: os.unlink(path)
def test_issue129(self): """Test RPC style (axis) messages (including parameter order)""" wsdl_url = 'file:tests/data/teca_server_wsdl.xml' client = SoapClient(wsdl=wsdl_url, soap_server='axis') client.help("contaVolumi") response = client.contaVolumi(user_id=1234, valoreIndice=["IDENTIFIER", ""]) self.assertEqual(response, {'contaVolumiReturn': 0})
def test_issue46(self): """Example for sending an arbitrary header using SimpleXMLElement""" # fake connection (just to test xml_request): client = SoapClient( location="https://localhost:666/", namespace='http://localhost/api' ) # Using WSDL, the equivalent is: # client['MyTestHeader'] = {'username': '******', 'password': '******'} headers = SimpleXMLElement("<Headers/>") my_test_header = headers.add_child("MyTestHeader") my_test_header['xmlns'] = "service" my_test_header.marshall('username', 'test') my_test_header.marshall('password', 'password') try: client.methodname(headers=headers) except: open("issue46.xml", "wb").write(client.xml_request) self.assert_('<soap:Header><MyTestHeader xmlns="service">' '<username>test</username>' '<password>password</password>' '</MyTestHeader></soap:Header>' in client.xml_request.decode(), "header not in request!")
def add_transaction_to_usaepay(self, token, usaepay_customer_id): if settings.TEST_MODE: return 123456 client = SoapClient(wsdl=settings.USAEPAY_WSDL, trace=True, ns=False) description = '' if self.autorefill and not self.company.blank_usaepay_description: description = 'Prepaid Phone recharge for %s' % self.autorefill.phone_number params = { u'Command': 'Sale', u'Details': { u'Amount': self.amount, u'Description': description, u'Invoice': '%s' % self.id, # u'OrderID': '', # u'PONum': '', } } response = client.runCustomerTransaction(Token=token, CustNum=usaepay_customer_id, PaymentMethodID=0, Parameters=params) result_code = response['runCustomerTransactionReturn']['ResultCode'] if 'A' == result_code: result = response['runCustomerTransactionReturn']['RefNum'] return result elif 'D' == result_code: self.atransaction = response['runCustomerTransactionReturn']['RefNum'] self.save() raise Exception('Transaction Declined: %s' % response['runCustomerTransactionReturn']['Error']) else: self.atransaction = response['runCustomerTransactionReturn']['RefNum'] self.save() raise Exception('Transaction Error: %s' % response['runCustomerTransactionReturn']['Error'])
def call_wsaa(cms, wsdl=WSDL, proxy=None, cache=None, wrapper="", trace=False): "Call the RPC method with the CMS to get the authorization ticket (TA)" # create the webservice client client = SoapClient( location = wsdl[:-5], #location, use wsdl, cache = cache, #proxy = parse_proxy(proxy), #cacert = cacert, timeout = TIMEOUT, ns = "ejb", # TODO: find a better method to not include ns prefix in children: # (wsdl parse should detect qualification instead of server dialect) soap_server = "jetty", namespace = "http://ejb.server.wsaa.dna.gov.py/", soap_ns = "soapenv", trace = trace) # fix the wrong location (192.4.1.39:8180 in the WDSL) ##ws = client.services['WsaaServerBeanService'] ##location = ws['ports']['WsaaServerBeanPort']['location'] ##location = location.replace("192.4.1.39:8180", "secure.aduana.gov.py") ##ws['ports']['WsaaServerBeanPort']['location'] = wsdl[:-5] #location # call the remote method try: results = client.loginCms(arg0=str(cms)) except: # save sent and received messages for debugging: open("request.xml", "w").write(client.xml_request) open("response.xml", "w").write(client.xml_response) raise # extract the result: ta = results['return'].encode("utf-8") return ta
def test_autorizar(self): WSDL = 'https://cel.sri.gob.ec/comprobantes-electronicos-ws/AutorizacionComprobantes?wsdl' # https://cel.sri.gob.ec/comprobantes-electronicos-ws/AutorizacionComprobantes?wsdl client = SoapClient(wsdl=WSDL, ns="ec") ret = client.autorizacionComprobante(claveAccesoComprobante="1702201205176001321000110010030001000011234567816") self.assertEquals(ret, {'RespuestaAutorizacionComprobante': {'autorizaciones': [], 'claveAccesoConsultada': '1702201205176001321000110010030001000011234567816', 'numeroComprobantes': '0'}})
def get_hostname(ip): #enable 5 second timeout socket.setdefaulttimeout(5) #query agent by SOAP client=SoapClient(location = "http://"+ip+":8008/",action = "http://"+ip+":8008/", namespace = "http://example.com/sample.wsdl",soap_ns='soap',ns = False) rs=str(client.get_value(number=11,com=xml['network']['commands']['hostname']['@com'],args=xml['network']['commands']['hostname']['#text']).resultaat) return rs.rstrip()
def send_msg_to_bpel(self, callback_method_id, msg): """ To send a SOAP message to BPEL :param address: :param namespace: :param method: :param params: :param result_names: :return: """ rospy.loginfo("===== Prepare a SOAP client =====") rospy.loginfo("Address: %s" % self.callback_bpel_method_map[callback_method_id]['address']) rospy.loginfo("NS: %s" % self.callback_bpel_method_map[callback_method_id]['namespace']) rospy.loginfo("=================================") callback_method = self.callback_bpel_method_map[callback_method_id] client = SoapClient( location = callback_method['address'], # "http://localhost:8080/ode/processes/A2B" namespace = callback_method['namespace'], # "http://smartylab.co.kr/bpel/a2b" soap_ns='soap') rospy.loginfo("Sending the message to BPEL... %s(%s)" % (callback_method['name'], msg)) # response = client.call(method, **(simplejson.loads(params))) param_dict = dict() param_dict[callback_method['param']] = msg response = client.call(callback_method['name'], **param_dict) rospy.loginfo("The message is sent.")
def test_buscar_personas_raw(self): url = "http://www.testgobi.dpi.sfnet/licencias/web/soap.php" client = SoapClient(location=url, ns="web", namespace="http://wwwdesagobi.dpi.sfnet:8080/licencias/web/", action=url) # load dummy response (for testing) client.http = DummyHTTP(self.xml) client['AuthHeaderElement'] = {'username': '******', 'password': '******'} response = client.PersonaSearch(persona=(('numero_documento', '99999999'), ('apellido_paterno', ''), ('apellido_materno', ''), ('nombres', ''), )) # the raw response is a SimpleXmlElement object: self.assertEqual(str(response.result.item[0]("xsd:string")[0]), "resultado") self.assertEqual(str(response.result.item[0]("xsd:string")[1]), "true") self.assertEqual(str(response.result.item[1]("xsd:string")[0]), "codigo") self.assertEqual(str(response.result.item[1]("xsd:string")[1]), "WS01-01") self.assertEqual(str(response.result.item[2]("xsd:string")[0]), "mensaje") self.assertEqual(str(response.result.item[2]("xsd:string")[1]), "Se encontraron 1 personas.") self.assertEqual(str(response.result.item[2]("xsd:string")[0]), "mensaje") self.assertEqual(str(response.result.item[2]("xsd:string")[1]), "Se encontraron 1 personas.") self.assertEqual(str(response.result.item[3]("xsd:anyType")[0]), "datos") self.assertEqual(str(response.result.item[3]("xsd:anyType")[1]("ns2:Map").item[0].key), "lic_ps_ext_id") self.assertEqual(str(response.result.item[3]("xsd:anyType")[1]("ns2:Map").item[0].value), "123456") self.assertEqual(str(response.result.item[3]("xsd:anyType")[1]("ns2:Map").item[10].key), "fecha_nacimiento") self.assertEqual(str(response.result.item[3]("xsd:anyType")[1]("ns2:Map").item[10].value), "1985-10-02 00:00:00")
def test_issue127(self): """Test relative schema locations in imports""" client = SoapClient(wsdl = 'https://eisoukr.musala.com:9443/IrmInboundMediationWeb/sca/MTPLPolicyWSExport/WEB-INF/wsdl/wsdl/IrmInboundMediation_MTPLPolicyWSExport.wsdl') try: resp = client.voidMTPLPolicy() except Exception as e: self.assertIn('InvalidSecurity', e.faultcode)
def test_wsfexv1_getcmp(self): """Test Argentina AFIP Electronic Invoice WSFEXv1 GetCMP method""" # create the proxy and parse the WSDL client = SoapClient( wsdl="https://wswhomo.afip.gov.ar/wsfexv1/service.asmx?WSDL", cache=None ) # load saved xml xml = open(os.path.join(TEST_DIR, "wsfexv1_getcmp.xml")).read() client.http = DummyHTTP(xml) # call RPC ret = client.FEXGetCMP( Auth={'Token': "", 'Sign': "", 'Cuit': "0"}, Cmp={ 'Cbte_tipo': "19", 'Punto_vta': "3", 'Cbte_nro': "38", }) # analyze result result = ret['FEXGetCMPResult'] self.assertEqual(result['FEXErr']['ErrCode'], 0) self.assertEqual(result['FEXErr']['ErrMsg'], 'OK') self.assertEqual(result['FEXEvents']['EventCode'], 0) resultget = result['FEXResultGet'] self.assertEqual(resultget['Obs'], None) self.assertEqual(resultget['Cae'], '61473001385110') self.assertEqual(resultget['Fch_venc_Cae'], '20111202') self.assertEqual(resultget['Fecha_cbte'], '20111122') self.assertEqual(resultget['Punto_vta'], 3) self.assertEqual(resultget['Resultado'], "A") self.assertEqual(resultget['Cbte_nro'], 38) self.assertEqual(resultget['Imp_total'], Decimal('130.21')) self.assertEqual(resultget['Cbte_tipo'], 19)
def test_issue129(self): """Test RPC style (axis) messages (including parameter order)""" wsdl_url = 'http://62.94.212.138:8081/teca/services/tecaServer?wsdl' client = SoapClient(wsdl=wsdl_url, soap_server='axis') client.help("contaVolumi") response = client.contaVolumi(user_id=1234, valoreIndice=["IDENTIFIER", ""]) self.assertEqual(response, {'contaVolumiReturn': 0})
def test_issue49(self): """Test netsuite wsdl""" client = SoapClient(wsdl="https://webservices.netsuite.com/wsdl/v2011_2_0/netsuite.wsdl") try: response = client.login(passport=dict(email="*****@*****.**", password="******", account='hello', role={'name': 'joe'})) except Exception as e: # It returns "This document you requested has moved temporarily." pass
def atest_issue80(self): """Test Issue in sending a webservice request with soap12""" client = SoapClient(wsdl="http://testserver:7007/testapp/services/testService?wsdl", soap_ns='soap12', trace=False, soap_server='oracle') try: result = client.hasRole(userId='test123', role='testview') except httplib2.ServerNotFoundError: pass
def atest_wsaa_exception(self): "Test WSAA for SoapFault" WSDL = "https://wsaa.afip.gov.ar/ws/services/LoginCms?wsdl" client = SoapClient(wsdl=WSDL, ns="web") try: resultado = client.loginCms('31867063') except SoapFault, e: self.assertEqual(e.faultcode, 'ns1:cms.bad')
def test_issue57(self): """Test SalesForce wsdl""" # open the attached sfdc_enterprise_v20.wsdl to the issue in googlecode client = SoapClient(wsdl="https://pysimplesoap.googlecode.com/issues/attachment?aid=570000001&name=sfdc_enterprise_v20.wsdl&token=dnnjZu-x1aF5gV0bYfM6K6hpAIM%3A1390359396946") try: response = client.login(username="******", password="******") except Exception as e: # It returns "This document you requested has moved temporarily." self.assertEqual(e.faultcode, u'INVALID_LOGIN')
def test_issue139(self): """Test MKS wsdl (extension)""" # open the attached Integrity_10_2Service to the issue in googlecode client = SoapClient(wsdl="https://pysimplesoap.googlecode.com/issues/attachment?aid=1390000000&name=Integrity_10_2.wsdl&token=3VG47As2K-EupP9GgotYckgb0Bc%3A1399064656814") #print client.help("getItemsByCustomQuery") try: response = client.getItemsByCustomQuery(arg0={'Username': '******', 'Password' : 'pass', 'InputField' : 'ID', 'QueryDefinition' : 'query'}) except httplib2.ServerNotFoundError: pass
def test_issue57(self): """Test SalesForce wsdl""" # open the attached sfdc_enterprise_v20.wsdl to the issue in googlecode client = SoapClient(wsdl="https://pysimplesoap.googlecode.com/issues/attachment?aid=570000001&name=sfdc_enterprise_v20.wsdl&token=bD6VTXMx8p4GJQHGhlQI1ISorSA%3A1399085346613") try: response = client.login(username="******", password="******") except Exception as e: # It returns "This document you requested has moved temporarily." self.assertEqual(e.faultcode, 'INVALID_LOGIN')
def refund_transaction_from_usaepay(self, token): if settings.TEST_MODE: return 'TEST' client = SoapClient(wsdl=settings.USAEPAY_WSDL, trace=True, ns=False) response = client.refundTransaction(Token=token, RefNum=self.atransaction, Amount=self.amount) return response['refundTransactionReturn']['Result']
def test_wsmtxca_dummy(self): """Test Argentina AFIP Electronic Invoice WSMTXCA dummy method""" client = SoapClient( wsdl="https://fwshomo.afip.gov.ar/wsmtxca/services/MTXCAService?wsdl", cache=None, ns='ser' ) result = client.dummy() self.assertEqual(result['appserver'], "OK") self.assertEqual(result['dbserver'], "OK") self.assertEqual(result['authserver'], "OK")
def test_wscoc_dummy(self): """Test Argentina AFIP Foreign Exchange Control WSCOC dummy method""" client = SoapClient( wsdl="https://fwshomo.afip.gov.ar/wscoc/COCService?wsdl", cache=None, ns='ser' ) result = client.dummy()['dummyReturn'] self.assertEqual(result['appserver'], "OK") self.assertEqual(result['dbserver'], "OK") self.assertEqual(result['authserver'], "OK")
def atest_issue80(self): """Test Issue in sending a webservice request with soap12""" client = SoapClient( wsdl="http://testserver:7007/testapp/services/testService?wsdl", soap_ns='soap12', trace=False, soap_server='oracle') try: result = client.hasRole(userId='test123', role='testview') except httplib2.ServerNotFoundError: pass
def test_create(self): real = SoapClient( location="http://localhost:8008/", action='http://localhost:8008/', # SOAPAction namespace="http://example.com/sample.wsdl", soap_ns='soap', trace=True, ns=False) real.Create = Mock(return_value='Document has not been created.') real.Create(doc_name='test', doc_content='<asd>No<asd>') real.Create.assert_called_with(doc_name='test', doc_content='<asd>No<asd>')
def validateTCKimlikNo(tckimlikno, name, surname, year): try: client = SoapClient(wsdl=TCKIMLIK_SORGULAMA_WS, trace=False) response = client.TCKimlikNoDogrula( TCKimlikNo=tckimlikno, Ad=name.replace('i', 'İ').decode('utf-8').upper(), Soyad=surname.replace('i', 'İ').decode('utf-8').upper(), DogumYili=year) return response['TCKimlikNoDogrulaResult'] except: return -1
def test_wsmtxca_dummy(self): """Test Argentina AFIP Electronic Invoice WSMTXCA dummy method""" client = SoapClient( wsdl= "https://fwshomo.afip.gov.ar/wsmtxca/services/MTXCAService?wsdl", cache=None, ns='ser') result = client.dummy() self.assertEqual(result['appserver'], "OK") self.assertEqual(result['dbserver'], "OK") self.assertEqual(result['authserver'], "OK")
def streaming_sentiment_analysis(input_dict, widget, stream=None): import pickle from pysimplesoap.client import SoapClient, SoapFault import pysimplesoap client = SoapClient(location="http://95.87.154.167:8088/", action='http://95.87.154.167:8088/', namespace="http://example.com/tweetsentiment.wsdl", soap_ns='soap', trace=False, ns=False) pysimplesoap.client.TIMEOUT = 60 try: input_dict['lang'] except: input_dict['lang'] = "en" #list_of_tweets = input_dict['ltw'] new_list_of_tweets = [] new_list_of_tweets.append({ 'id': 0, 'text': input_dict['text'], 'language': input_dict['lang'] }) #for tweet in list_of_tweets: # new_list_of_tweets.append({'id':tweet['id'],'text':tweet['text'],'language':tweet['lang']}) pickled_list_of_tweets = pickle.dumps(new_list_of_tweets) response = client.TweetSentimentService(tweets=pickled_list_of_tweets) new_ltw = pickle.loads(str(response.TweetSentimentResult)) output_dict = {} #i=0 for new_tweet in new_ltw: output_dict['sentiment'] = new_tweet['sentiment'] output_dict['language'] = new_tweet['language'] output_dict['reliability'] = new_tweet['reliability'] #list_of_tweets[i]['sentiment']=new_tweet['sentiment'] #list_of_tweets[i]['lang']=new_tweet['language'] #list_of_tweets[i]['reliability']=new_tweet['reliability'] #i = i + 1 #output_dict = {} #output_dict['ltw'] = list_of_tweets return output_dict
def test_issue143(self): """Test webservice.vso.dunes.ch wsdl (array sub-element)""" wsdl_url = 'file:tests/data/vco.wsdl' try: vcoWS = SoapClient(wsdl=wsdl_url, soap_server="axis", trace=False) workflowInputs = [{'name': 'vmName', 'type': 'string', 'value': 'VMNAME'}] workflowToken = vcoWS.executeWorkflow(workflowId='my_uuid', username="******", password="******", workflowInputs=workflowInputs) except httplib2.ServerNotFoundError: #import pdb;pdb.set_trace() print vcoWS.xml_response pass
def test_issue123(self): """Basic test for WSDL lacking service tag """ wsdl = "http://www.onvif.org/onvif/ver10/device/wsdl/devicemgmt.wsdl" client = SoapClient(wsdl=wsdl) client.help("CreateUsers") client.help("GetServices") # this is not a real webservice (just specification) catch HTTP error try: client.GetServices(IncludeCapability=True) except Exception as e: self.assertEqual(str(e), "RelativeURIError: Only absolute URIs are allowed. uri = ")
def webservice(keypoint): client = SoapClient(wsdl="http://127.0.0.1:8000/TG/webservice/call/soap?WSDL") response = client.getKeyPointPerson(auth= '0DDEE29FAA57CF9DBEE480986E7B0686', person_data={'keypoints':keypoint}) try: result = response except SoapFault as e: result = e return dict(xml_request=client.xml_request, xml_response=client.xml_response,result=result)
def test_obtener_token(self): # Concetarse al webservice (en producción, ver cache y otros parametros): WSDL = "http://pruebas.ecodex.com.mx:2044/ServicioSeguridad.svc?wsdl" client = SoapClient(wsdl=WSDL, ns="ns0", soap_ns="soapenv") # llamo al método remoto: retval = client.ObtenerToken(RFC="AAA010101AAA", TransaccionID=1234) # muestro los resultados: self.assertIsInstance(retval['Token'], basestring) self.assertIsInstance(retval['TransaccionID'], long)
def void_transaction_from_usaepay(self, token): if settings.TEST_MODE: return 'TEST' result = '' if token: client = SoapClient(wsdl=settings.USAEPAY_WSDL, trace=False, ns=False) response = client.voidTransaction(Token=token, RefNum=self.atransaction) result = response['voidTransactionReturn'] return result
def test_wsbfe_dummy(self): "Test Argentina AFIP Electronic Invoice WSBFE dummy method" client = SoapClient( wsdl="https://wswhomo.afip.gov.ar/wsbfe/service.asmx?WSDL", trace=TRACE, cache=None, ) result = client.BFEDummy()['BFEDummyResult'] self.assertEqual(result['AppServer'], "OK") self.assertEqual(result['DbServer'], "OK") self.assertEqual(result['AuthServer'], "OK")
def main(): global outfile input_file = sys.argv[1] output_file_name = sys.argv[2] # create a SOAP client client = SoapClient( wsdl="http://mu2py.biocomp.unibo.it/mempype/rpc/call/soap?WSDL") outfile = open(output_file_name, "w") infile = open(input_file, "r") inlines = infile.readlines() infile.close() for inline in inlines: inline = inline.strip() if (inline != ''): bits = inline.split(":::::") this_id = bits[0] this_fastaid = bits[1] this_seq = bits[2] this_seq_hashlib = hashlib.sha1() this_seq_hashlib.update(this_seq) this_seq_hashlib_string = this_seq_hashlib.hexdigest() print this_seq_hashlib_string print # call SOAP method #response = client.get_prediction_results( seqhash='ce90a8c334a89b821ca6da78ce089eb88b4ec842' ) # <== this works, is the example given by [email protected] #response = client.get_prediction_results( seqhash=this_seq_hashlib_string ) #response = client.get_prediction_results( seqhash='4eaf2077845b24165649d6f5ad1bcf8c23738ac5' ) # <== this doesn't work, is the sha1 hash for my sequence, is not in their database? this_seq_hashlib_string = 'ce90a8c334a89b821ca6da78ce089eb88b4ec842' response = client.get_prediction_results( seqhash=this_seq_hashlib_string) print response # {'signal_peptide': u'1-32', 'prediction_status': u'Done', 'prediction_summary': u'Cell Membrane, Globular', 'cytoplasmic_region': u'NO', 'memloci_cell_membrane_score': u'99%', 'memloci_organellar_membrane_score': u'-88%', 'non_cytoplasmic_region': u'NO', 'memloci_internal_membrane_score': u'-21%', 'transmembrane_region': u'NO', 'GPI-anchor': u'NO'} #try: # status = response['status'] # print dict(xml_request=client.xml_request, xml_response=client.xml_response, status = status ) #except SoapFault, e: # print dict(xml_request=client.xml_request, xml_response=client.xml_response, error=str(e)) #output_line = output_line + "\r\n" #outfile.write( output_line ) outfile.close()
def test_buscar_personas_raw(self): url = "http://www.testgobi.dpi.sfnet/licencias/web/soap.php" client = SoapClient( location=url, ns="web", namespace="http://wwwdesagobi.dpi.sfnet:8080/licencias/web/", action=url) # load dummy response (for testing) client.http = DummyHTTP(self.xml) client['AuthHeaderElement'] = { 'username': '******', 'password': '******' } response = client.PersonaSearch(persona=( ('numero_documento', '99999999'), ('apellido_paterno', ''), ('apellido_materno', ''), ('nombres', ''), )) # the raw response is a SimpleXmlElement object: self.assertEqual(str(response.result.item[0]("xsd:string")[0]), "resultado") self.assertEqual(str(response.result.item[0]("xsd:string")[1]), "true") self.assertEqual(str(response.result.item[1]("xsd:string")[0]), "codigo") self.assertEqual(str(response.result.item[1]("xsd:string")[1]), "WS01-01") self.assertEqual(str(response.result.item[2]("xsd:string")[0]), "mensaje") self.assertEqual(str(response.result.item[2]("xsd:string")[1]), "Se encontraron 1 personas.") self.assertEqual(str(response.result.item[2]("xsd:string")[0]), "mensaje") self.assertEqual(str(response.result.item[2]("xsd:string")[1]), "Se encontraron 1 personas.") self.assertEqual(str(response.result.item[3]("xsd:anyType")[0]), "datos") self.assertEqual( str(response.result.item[3]("xsd:anyType")[1]( "ns2:Map").item[0].key), "lic_ps_ext_id") self.assertEqual( str(response.result.item[3]("xsd:anyType")[1]( "ns2:Map").item[0].value), "123456") self.assertEqual( str(response.result.item[3]("xsd:anyType")[1]( "ns2:Map").item[10].key), "fecha_nacimiento") self.assertEqual( str(response.result.item[3]("xsd:anyType")[1]( "ns2:Map").item[10].value), "1985-10-02 00:00:00")
def test_issue128(self): "" client = SoapClient( wsdl = "https://apiapac.lumesse-talenthub.com/HRIS/SOAP/Candidate?WSDL", location = "https://apiapac.lumesse-talenthub.com/HRIS/SOAP/Candidate?api_key=azhmc6m8sq2gf2jqwywa37g4", ns = True ) # basic test as no test case was provided try: resp = client.getContracts() except: self.assertEqual(client.xml_response, '<h1>Gateway Timeout</h1>')
def __init__(self, udn, location): self._udn = udn #self._name = name self._location = location scheme, netloc, _, _, _, _ = urllib2.urlparse.urlparse(location) self._address = '{0}://{1}'.format(scheme, netloc) # ToDo: get correct ControlLocation from the XML file self._contentDirectory = SoapClient( location='{0}/cd/Control'.format(self._address), action='urn:schemas-upnp-org:service:ContentDirectory:1#', namespace='http://schemas.xmlsoap.org/soap/envelope/', soap_ns='soap', ns='s', exceptions=False)
def test_consultar(self): "consulta ao resultado do processamento dos arquivos de cupons fiscai" # create the client webservice client = SoapClient(wsdl=WSDL, soap_ns="soap12env") # set user login credentials in the soap header: client['Autenticacao'] = SimpleXMLElement( HEADER_XML % ("user", "password", "fed_tax_num", 1)) # call the webservice response = client.Consultar(Protocolo="") self.assertEqual( response['ConsultarResult'], u'999|O protocolo informado n\xe3o \xe9 um n\xfamero v\xe1lido')
def test_issue57(self): """Test SalesForce wsdl""" # open the attached sfdc_enterprise_v20.wsdl to the issue in googlecode client = SoapClient( wsdl= "https://pysimplesoap.googlecode.com/issues/attachment?aid=570000001&name=sfdc_enterprise_v20.wsdl&token=bD6VTXMx8p4GJQHGhlQI1ISorSA%3A1399085346613" ) try: response = client.login(username="******", password="******") except Exception as e: # It returns "This document you requested has moved temporarily." self.assertEqual(e.faultcode, 'INVALID_LOGIN')
def test_wscoc_dummy(self): "Test Argentina AFIP Foreign Exchange Control WSCOC dummy method" client = SoapClient( wsdl="https://fwshomo.afip.gov.ar/wscoc/COCService?wsdl", trace=TRACE, cache=None, ns='ser', ) result = client.dummy()['dummyReturn'] self.assertEqual(result['appserver'], "OK") self.assertEqual(result['dbserver'], "OK") self.assertEqual(result['authserver'], "OK")
def test_issue109bis(self): """Test string arrays not defined in the wsdl (but sent in the response)""" WSDL = 'http://globe-meta.ifh.de:8080/axis/services/ILDG_MDC?wsdl' client = SoapClient(wsdl=WSDL, soap_server='axis') response = client.doEnsembleURIQuery("Xpath", "/markovChain", 0, -1) ret = response['doEnsembleURIQueryReturn'] self.assertIsInstance(ret['numberOfResults'], int) self.assertIsInstance(ret['results'], list) self.assertIsInstance(ret['results'][0], basestring)
def createOrUpdateClientEx(target): client = SoapClient(location="http://aboweb.com/aboweb/ClientService?wsdl",trace=False) client['wsse:Security'] = { 'wsse:UsernameToken': { 'wsse:Username': '******', 'wsse:Password': '******', } } target = SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><ges:createOrUpdateClientEx xmlns:ges="http://www.gesmag.com/">'+ repr(target) +'</ges:createOrUpdateClientEx>') client.call('createOrUpdateClientEx',target) xml = SimpleXMLElement(client.xml_response) return xml
def void_transaction_from_usaepay(self): if settings.TEST_MODE: return 'TEST' token = self.company.usaepay_authorization() result = '' if token: client = SoapClient(wsdl=settings.USAEPAY_WSDL, trace=False, ns=False) response = client.voidTransaction(Token=token, RefNum=self.atransaction) result = response['voidTransactionReturn'] return result
def test_issue128(self): "" client = SoapClient( wsdl= "https://apiapac.lumesse-talenthub.com/HRIS/SOAP/Candidate?WSDL", location= "https://apiapac.lumesse-talenthub.com/HRIS/SOAP/Candidate?api_key=azhmc6m8sq2gf2jqwywa37g4", ns=True) # basic test as no test case was provided try: resp = client.getContracts() except: self.assertEqual(client.xml_response, '<h1>Gateway Timeout</h1>')
def test_wsaa_exception(self): """Test WSAA for SoapFault""" WSDL = "https://wsaa.afip.gov.ar/ws/services/LoginCms?wsdl" client = SoapClient(wsdl=WSDL, trace=False, ns="web") try: resultado = client.loginCms('31867063') except SoapFault as e: self.assertEqual(e.faultcode, 'ns1:cms.bad') try: resultado = client.loginCms(in0='31867063') except SoapFault as e: self.assertEqual(e.faultcode, 'ns1:cms.bad')
def test_issue49(self): """Test netsuite wsdl""" client = SoapClient( wsdl="https://webservices.netsuite.com/wsdl/v2011_2_0/netsuite.wsdl" ) try: response = client.login(passport=dict(email="*****@*****.**", password="******", account='hello', role={'name': 'joe'})) except Exception as e: # It returns "This document you requested has moved temporarily." pass
def __init__(self, testing=False): self._testing = testing if testing: location = 'https://webpay3gint.transbank.cl/webpayserver/wswebpay/OneClickPaymentService' else: location = 'https://webpay3g.transbank.cl:443/webpayserver/wswebpay/OneClickPaymentService' self.client = SoapClient( soap_ns='soap11', location=location, namespace="http://webservices.webpayserver.transbank.com/", timeout=20, trace=True)
def getwandsllink(fritzbox, port, debug): location = 'http://'+fritzbox+':'+port+'/igd2upnp/control/WANIPv6Firewall1' namespace = 'urn:schemas-upnp-org:service:WANIPv6FirewallControl:1' action = 'urn:schemas-upnp-org:service:WANIPv6FirewallControl:1#' client = SoapClient(location, action, namespace, trace=debug) gfs = client.GetFirewallStatus() FirewallEnabled = str(gfs.FirewallEnabled) InboundPinholeAllowed = str(gfs.InboundPinholeAllowed) msg = "FirewallEnabled="+str(FirewallEnabled)+" InboundPinholeAllowed="+str(InboundPinholeAllowed) return msg
def getClient(codeClient): client = SoapClient(location="http://aboweb.com/aboweb/ClientService?wsdl",trace=False) client['wsse:Security'] = { 'wsse:UsernameToken': { 'wsse:Username': '******', 'wsse:Password': '******', # 'wsse:Password': '******', } } params = SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><ges:getClient xmlns:ges="http://www.gesmag.com/"><codeClient>'+codeClient+'</codeClient></ges:getClient>'); result = client.call("getClient",params) xml = SimpleXMLElement(client.xml_response) return xml.children().children().children()
def test_input_parameter(self): client = SoapClient(wsdl="http://localhost:9323/EmployeeService?singleWsdl") pprint(client.services) result = client.InsertManager(manager={ "PersonId": "Person123", "EmployeeId": "Employee123", "ManagerId": "Manager123", "Contacts": {"Contact": [{"ContactId": "Contact222", "PersonId": "Person222"}, {"ContactId": "Contact333", "PersonId": "Person333"}] } } ) self.assertEqual(result['InsertManagerResult'], True)
def authenticateByEmail(username,password): # wsdl = "http://dev.aboweb.com/aboweb/ClientService?wsdl" client = SoapClient(location = "http://aboweb.com/aboweb/ClientService",trace=False) client['wsse:Security'] = { 'wsse:UsernameToken': { 'wsse:Username': '******', # 'wsse:Password': '******', 'wsse:Password': '******', } } params = SimpleXMLElement('<?xml version="1.0" encoding="UTF-8"?><ges:authenticateByEmail xmlns:ges="http://www.gesmag.com/"><email>'+username+'</email><encryptedPassword>'+ b64encode(sha1(password).digest()) +'</encryptedPassword></ges:authenticateByEmail>') response = client.call("authenticateByEmail",params) xml = SimpleXMLElement(client.xml_response) return str(xml('result'))
def _load(self): if self._device.unr.remoteCommands is None: if not self._device.unr.isFunctionSupported( self._device.unr.getRemoteCommandList): print "'getRemoteCommandList' not supported" raise NotSupportedError() self._device.unr.getRemoteCommandList() if self._client is None and self._device.unr.remoteCommands: self._client = SoapClient(location=self._controlUrl, action=SONY_UPNP_URN_IRCC, namespace=SONY_UPNP_URN_IRCC, soap_ns='soap', ns=False)
def test_issue47_wsdl(self): "Separate Header message WSDL (carizen)" client = SoapClient(wsdl="https://api.clarizen.com/v1.0/Clarizen.svc") session = client['Session'] = {'ID': '1234'} try: client.Logout() except: open("issue47_wsdl.xml", "wb").write(client.xml_request) self.assertTrue( """<soap:Header><Session><ID>1234</ID></Session></soap:Header>""" in client.xml_request, "Session header not in request!")
def test_issue109(self): """Test multirefs and string arrays""" WSDL = 'http://usqcd.jlab.org/mdc-service/services/ILDGMDCService?wsdl' client = SoapClient(wsdl=WSDL, soap_server='axis') response = client.doEnsembleURIQuery("Xpath", "/markovChain", 0, -1) ret = response['doEnsembleURIQueryReturn'] self.assertIsInstance(ret['numberOfResults'], int) self.assertIsInstance(ret['results'], list) self.assertIsInstance(ret['results'][0], basestring) self.assertIsInstance(ret['queryTime'], basestring) self.assertEqual(ret['statusCode'], "MDC_SUCCESS")
def test_issue123(self): """Basic test for WSDL lacking service tag """ wsdl = "http://www.onvif.org/onvif/ver10/device/wsdl/devicemgmt.wsdl" client = SoapClient(wsdl=wsdl) # this could cause infinite recursion (TODO: investigate) #client.help("CreateUsers") #client.help("GetServices") # this is not a real webservice (just specification) catch HTTP error try: client.GetServices(IncludeCapability=True) except Exception as e: self.assertEqual( str(e), "RelativeURIError: Only absolute URIs are allowed. uri = ")
def test_timbrado(self): # this tests "infinite recursion" issues # Concetarse al webservice (en producción, ver cache y otros parametros): WSDL = "https://digitalinvoicecfdi.com.mx/WS_WSDI/DigitalInvoice.WebServices.WSDI.Timbrado.svc?wsdl" #WSDL = "federico.wsdl" client = SoapClient(wsdl=WSDL, ns="ns0", soap_ns="soapenv") # llamo al método remoto: try: retval = client.TimbrarTest(comprobanteBytesZipped="1234") except SoapFault as sf: self.assertIn("verifying security for the message", str(sf.faultstring))
class InterviewSoapClient: def __init__(self): self.client = SoapClient( location=os.getenv("SOAP_SERVICE_HOST"), http_headers={'Authorization': os.getenv("SOAP_SERVICE_TOKEN")}) def call(self, service, action, args={}): params = {'service': service, 'action': action, 'args': args} self.client.handle(request=json.dumps(params)) res = xmltodict.parse(self.client.xml_response) body = res['SOAP-ENV:Envelope']['SOAP-ENV:Body'] return json.dumps(body['ns1:handleResponse']['return']['#text'])
def test_issue94(self): """Test wather forecast web service.""" client = SoapClient( wsdl= 'http://www.restfulwebservices.net/wcf/WeatherForecastService.svc?wsdl' ) ret = client.GetCitiesByCountry('korea') for d in ret['GetCitiesByCountryResult']: #print d['string'] self.assertEquals(d.keys()[0], 'string') self.assertEquals(len(ret['GetCitiesByCountryResult']), 53) self.assertEquals(len(ret['GetCitiesByCountryResult'][0]), 1) self.assertEquals(ret['GetCitiesByCountryResult'][0]['string'], 'KWANGJU')