def _call_submission(settings: CzNiaAppSettings, transport: Transport, assertion, message: NiaMessage) -> bytes: """Call Submission service and return the body.""" plugins = [] history = None if settings.DEBUG: history = HistoryPlugin() plugins.append(history) client = Client(settings.PUBLIC_WSDL, wsse=SAMLTokenSignature(assertion), settings=SETTINGS, transport=transport, plugins=plugins) # Prepare the Body bodies_type = client.get_type( QName(NiaNamespaces.SUBMISSION.value, 'ArrayOfBodyPart')) body_part_type = client.get_type( QName(NiaNamespaces.SUBMISSION.value, 'BodyPart')) # Call the service service = client.bind('Public', 'Token') try: response = service.Submit( message.action, bodies_type(body_part_type(Body={'_value_1': message.pack()})), '') except (Error, XmlsecError, RequestException) as err: _log_history(history, settings, 'Submission', success=False) raise NiaException(err) _log_history(history, settings, 'Submission') return b64decode(response.BodyBase64XML)
def exportPDF(): # InDesign JSX script to do the export exportScriptPath = os.getcwd() + "\export_pdf.jsx" # soap client = IDS host client running on a soap port client = Client('http://localhost:12345?wsdl') # Create SOAP call params object, based on IDS wsdl # For details go to http://localhost:12345?wsdl RunScriptParameters = client.get_type('ns0:RunScriptParameters') IDSP_ScriptArg = client.get_type('ns0:IDSP-ScriptArg') # Get editorial contents from database # this example returns a dictionary{} of editorial data editorialContents = { 'arg1': 'Electric Cars', 'arg2': 'An electric car is an automobile that is propelled by one or more electric motors, using energy stored in rechargeable batteries.', 'arg3': 'The first practical electric cars were produced in the 1880s' } # pass the data to RunScript so you can access them from your .jsx file like so: app.scriptArgs.getValue("frontTitle"); params = RunScriptParameters("", "javascript", exportScriptPath, [ IDSP_ScriptArg(key, value) for key, value in editorialContents.items() ]) result = client.service.RunScript(params) return redirect(url_for('index'))
def get_rtvListZugeordneteIKAdressen(self, pid): client = Client(self.BASE_URL + RUL_SERVICE, transport=self.transport) request_type = client.get_type('ns0:rtvListZugeordneteIKAdressen') constraint = client.get_type('ns1:listConstraint')(start=1, max=10, isOverflowAllowed=True) result = client.service.rtvListZugeordneteIKAdressen( sessionToken=self.session_token, versfallID=pid, listConstraint=constraint) return result
def idmquery(wsdlurl, begintime, endtime, pagenum, systemid, idmid, clientsrv): try: history = HistoryPlugin() client = Client(wsdl=wsdlurl, plugins=[history]) querydto_type = client.get_type('ns0:queryDto') header_type = client.get_type('ns2:Header') querydto = querydto_type(beginDate=begintime, endDate=endtime, pageNo=pagenum, pageRowNo='100', systemID=systemid) header = header_type(BIZTRANSACTIONID=idmid, COUNT='', CONSUMER='', SRVLEVEL='', ACCOUNT='idmadmin', PASSWORD='******') if clientsrv == 'idmorg': residmquery = client.service.PUBLIC_SUNAC_301_queryIdmOrgData( queryDto=querydto, _soapheaders={'parameters2': header}) if clientsrv == 'idmuser': residmquery = client.service.PUBLIC_SUNAC_300_queryIdmUserData( queryDto=querydto, _soapheaders={'parameters2': header}) debuglog_sys(history.last_sent) debuglog_sys(history.last_received) except Exception as e: errlog_sys(e) return residmquery
def send_method(self): if self.integration_id.method_id == self.env.ref( 'l10n_es_facturae_face.integration_face'): invoice = self.integration_id.invoice_id cert = crypto.load_pkcs12( base64.b64decode(invoice.company_id.facturae_cert), invoice.company_id.facturae_cert_password ) cert.set_ca_certificates(None) client = Client( wsdl=self.env["ir.config_parameter"].get_param( "account.invoice.face.server", default=None), wsse=MemorySignature( cert.export(), base64.b64decode( self.env.ref( 'l10n_es_facturae_face.face_certificate').datas ) ) ) invoice_file = client.get_type('ns0:FacturaFile')( self.integration_id.attachment_id.datas, self.integration_id.attachment_id.datas_fname, self.integration_id.attachment_id.mimetype ) anexos_list = [] if self.integration_id.attachment_ids: for attachment in self.attachment_ids: anexo = client.get_type('ns0:AnexoFile')( attachment.datas, attachment.datas_fname, attachment.mimetype ) anexos_list.append(anexo) anexos = client.get_type('ns0:ArrayOfAnexoFile')( anexos_list ) invoice_call = client.get_type('ns0:EnviarFacturaRequest')( invoice.company_id.face_email, invoice_file, anexos ) response = client.service.enviarFactura( invoice_call ) self.result_code = response.resultado.codigo self.log = response.resultado.descripcion if self.result_code == '0': self.state = 'sent' integ = self.integration_id integ.register_number = response.factura.numeroRegistro integ.state = 'sent' integ.can_cancel = True integ.can_update = True integ.can_send = False else: self.integration_id.state = 'failed' self.state = 'failed' return return super(AccountInvoiceIntegration, self).send_method()
def test_factory_no_reference(): client = Client("tests/wsdl_files/soap.wsdl") obj_1 = client.get_type("ns0:ArrayOfAddress")() obj_1.Address.append({"NameFirst": "J", "NameLast": "Doe"}) obj_2 = client.get_type("ns0:ArrayOfAddress")() assert len(obj_2.Address) == 0
def read_multiple_soap_records(self, soap_object, filter_field_string, filter_type_string, filter_data=[{ 'property': '', 'value': '' }]): session = Session() session.auth = HTTPBasicAuth(self.nav_user, self.nav_password) soap_service_url = self.nav_soap_service + self.nav_company + "/Page/" + soap_object client = Client(soap_service_url, transport=Transport(session=session, cache=SqliteCache())) filter_field = client.get_type(f"ns0:{filter_field_string}") filter_type = client.get_type(f"ns0:{filter_type_string}") # Build the search filters from the filter_data # Notice the default values for the filter_data arguement are empty # so we bring back all of the records as a default filters = [ filter_type(filter_field(item['property']), item['value']) for item in filter_data ] # setService tells the service how many records to return soap_response = client.service.ReadMultiple(filter=filters, setSize=0) serialized_response = serialize_object(soap_response) return serialized_response
def _l10n_mx_edi_finkok_cancel_service(self, uuid, company, credentials): ''' Cancel the CFDI document with PAC: finkok. Does not depend on a recordset ''' certificates = company.l10n_mx_edi_certificate_ids certificate = certificates.sudo().get_valid_certificate() cer_pem = certificate.get_pem_cer(certificate.content) key_pem = certificate.get_pem_key(certificate.key, certificate.password) try: transport = Transport(timeout=20) client = Client(credentials['cancel_url'], transport=transport) uuid_type = client.get_type('ns1:UUID')() uuid_type.UUID = uuid uuid_type.FolioSustitucion = self._context.get( 'cancel_replace_folio') or "" if not self._context.get('cancel_reason_code'): raise UserError("reason not defined") uuid_type.Motivo = self._context.get('cancel_reason_code') docs_list = client.get_type('ns1:UUIDS')(uuid_type) response = client.service.cancel( docs_list, credentials['username'], credentials['password'], company.vat, cer_pem, key_pem, ) except Exception as e: return { 'errors': [ _( "The Finkok service failed to cancel with the following error: %s", str(e)) ], } if not getattr(response, 'Folios', None): code = getattr(response, 'CodEstatus', None) msg = _("Cancelling got an error") if code else _( 'A delay of 2 hours has to be respected before to cancel') else: code = getattr(response.Folios.Folio[0], 'EstatusUUID', None) cancelled = code in ('201', '202' ) # cancelled or previously cancelled # no show code and response message if cancel was success code = '' if cancelled else code msg = '' if cancelled else _("Cancelling got an error") errors = [] if code: errors.append(_("Code : %s") % code) if msg: errors.append(_("Message : %s") % msg) if errors: return {'errors': errors} return {'success': True}
def test_factory_no_reference(): client = Client('tests/wsdl_files/soap.wsdl') obj_1 = client.get_type('ns0:ArrayOfAddress')() obj_1.Address.append({ 'NameFirst': 'J', 'NameLast': 'Doe', }) obj_2 = client.get_type('ns0:ArrayOfAddress')() assert len(obj_2.Address) == 0
def do_web_payment(merchant_id, access_key, contract_number, return_url, cancel_url, notification_url, amount, reference, currency=978, mode='CPT', action=101): session = Session() session.auth = HTTPBasicAuth(merchant_id, access_key) client = Client(WSDL, transport=Transport(session=session)) service = client.create_service( '{http://impl.ws.payline.experian.com}WebPaymentAPISoapBinding', 'https://services.payline.com/V4/services/WebPaymentAPI') payment_type = client.get_type('ns1:payment') payment = payment_type(amount=amount, currency=currency, action=action, mode=mode, contractNumber=contract_number) date_str = datetime.datetime.now().strftime('%d/%m/%Y %H:%M') order_type = client.get_type('ns1:order') order = order_type(ref=reference, country='PT', amount=amount, currency=currency, date=date_str) contractlist_type = client.get_type('ns1:selectedContractList') contractlist = contractlist_type(contract_number) privatedatalist_type = client.get_type('ns1:privateDataList') privatedata_type = client.get_type('ns1:privateData') privatedata = privatedata_type(key='order_id', value=reference) privatedatalist = privatedatalist_type(privatedata) response = service.doWebPayment(version=4, payment=payment, returnURL=return_url, cancelURL=cancel_url, order=order, notificationURL=notification_url, selectedContractList=contractlist, privateDataList=privatedatalist, languageCode='pt') return serialize_object(response)
def _l10n_mx_edi_finkok_cancel(self, pac_info): '''CANCEL for Finkok. ''' url = pac_info['url'] username = pac_info['username'] password = pac_info['password'] for inv in self: uuid = inv.l10n_mx_edi_cfdi_uuid certificate_ids = inv.company_id.l10n_mx_edi_certificate_ids certificate_id = certificate_ids.sudo().get_valid_certificate() company_id = self.company_id cer_pem = certificate_id.get_pem_cer(certificate_id.content) key_pem = certificate_id.get_pem_key(certificate_id.key, certificate_id.password) cancelled = False code = False try: transport = Transport(timeout=20) client = Client(url, transport=transport) # uuid_type = client.get_type('ns0:stringArray')() # uuid_type.string = [uuid] # invoices_list = client.get_type('ns1:UUIDS')(uuid_type) ##################################### uuid_type = client.get_type('ns1:UUID')() uuid_type.UUID = uuid uuid_type.FolioSustitucion = inv.replace_folio or '' if not inv.edi_cancel_reason_id: raise UserError("reason not defined") uuid_type.Motivo = inv.edi_cancel_reason_id.code invoices_list = client.get_type('ns1:UUIDS')(uuid_type) ##################################### response = client.service.cancel(invoices_list, username, password, company_id.vat, cer_pem, key_pem) except Exception as e: inv.l10n_mx_edi_log_error(str(e)) continue if not getattr(response, 'Folios', None): code = getattr(response, 'CodEstatus', None) msg = _("Cancelling got an error") if code else _( 'A delay of 2 hours has to be respected before to cancel') else: code = getattr(response.Folios.Folio[0], 'EstatusUUID', None) cancelled = code in ('201', '202' ) # cancelled or previously cancelled # no show code and response message if cancel was success code = '' if cancelled else code msg = '' if cancelled else _("Cancelling got an error") inv._l10n_mx_edi_post_cancel_process(cancelled, code, msg)
class CardService: def __init__(self, server, user, password, company_id, user_id, process_id=None): self.url = '%s/webdesk/CardService?wsdl' % server self.client = Client(self.url) self.user = user self.password = password self.company_id = company_id self.user_id = user_id self.process_id = process_id def __get_card_data(self, data): """Transforma o dicionário em parâmetros.""" if bool(data): # Obtém classes do webservice. try: cf_dto_array = self.client.get_type('ns0:cardFieldDtoArray') cf_dto = self.client.get_type('ns0:cardFieldDto') except: cf_dto_array = self.client.get_type('ns1:cardFieldDtoArray') cf_dto = self.client.get_type('ns1:cardFieldDto') fields = [] for k, v in data.items(): field = cf_dto(field=k, value=v) fields.append(field) # Transforma o dicionário recebido nos objetos do webservice. parametros = cf_dto_array(item=fields) return parametros else: return {} def update_card_data(self, card_id, card_data): """Retorna o byte do arquivo físico de um documento, caso o usuário tenha permissão para acessá-lo.""" result = self.client.service.updateCardData( self.company_id, self.user, self.password, card_id, cardData=self.__get_card_data(card_data)) return result
def test_efact_sending(self): self._activate_certificate() client = Client( wsdl=self.env.ref("l10n_es_facturae_face.face_webservice").url) integration_code = "1234567890" response_ok = client.get_type("ns0:EnviarFacturaResponse")( client.get_type("ns0:Resultado")(codigo="0", descripcion="OK"), client.get_type("ns0:EnviarFactura")( numeroRegistro=integration_code), ) self.assertFalse(self.move.exchange_record_ids) with mock.patch("zeep.client.ServiceProxy") as mock_client: mock_client.return_value = DemoService(response_ok) self.move.with_context(force_edi_send=True).action_post() self.move.refresh() self.assertTrue(self.move.exchange_record_ids) exchange_record = self.move.exchange_record_ids self.assertEqual(exchange_record.edi_exchange_state, "output_pending") exchange_record.backend_id.exchange_send(exchange_record) self.assertEqual(exchange_record.edi_exchange_state, "output_sent_and_processed") # We force it to be efact just for a test, that should never happen for new # invoices exchange_record.write({ "backend_id": self.env.ref("l10n_es_facturae_efact.efact_backend").id, "exchange_filename": "0123456789012345678901@" "0123456789012345678901@R_0001", "external_identifier": False, }) exchange_record.flush() with mock.patch(patch_class) as mock_backend: mock_backend.return_value = TestConnection( bytes( tools.file_open( "result.xml", subdir="addons/l10n_es_facturae_efact/tests").read(). encode("utf-8")), exchange_record.exchange_filename + "@001", ) self.env["edi.exchange.record"].efact_check_history() exchange_record.flush() self.assertEqual(exchange_record.external_identifier, "12") self.assertFalse(exchange_record.exchange_error) self.assertEqual(self.move.l10n_es_facturae_status, "efact-DELIVERED")
class NrClient(object): def __init__(self, token, uri): ''' Object constructs with access token from site. ''' self.client = Client(uri) accesskey_type = self.client.get_type('ns0:AccessToken') self.token = accesskey_type(TokenValue=token) def get_fastest_departures(self, origin, destination, offset): ''' query api for the fastest departures from origin to destination, offset in minutes. ''' return self.client.service.GetFastestDepartures( crs=origin, filterList=destination, timeOffset=offset, timeWindow=120, _soapheaders={'AccessToken': self.token}) def get_arrival_board_with_details(self, target, filterCode=None, filtertype=None): ''' Method gets the arrival board, for the target with the filter type being to or from. FilterCode is the station code of the filter, by default None.''' return self.client.service.GetArrBoardWithDetails( numRows=10, crs=target, filterCrs=filterCode, filterType=filtertype, _soapheaders={'AccessToken': self.token})
def send_otp_soap(mobile, otp): time.sleep(10) client = Client('http://api.kavenegar.com/soap/v1.asmx?WSDL') receptor = [mobile, ] empty_array_placeholder = client.get_type('ns0:ArrayOfString') receptors = empty_array_placeholder() for item in receptor: receptors['string'].append(item) api_key = Kavenegar_API message = 'Your OTP is {}'.format(otp) sender = '' # status = 0 status_message = '' result = client.service.SendSimpleByApikey(api_key, sender, message, receptors, 0, 1, status, status_message) print(result) print('OTP: ', otp)
def test_parse_soap_wsdl(): client = Client( 'tests/wsdl_files/soap.wsdl', transport=Transport(), ) response = """ <?xml version="1.0"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:stoc="http://example.com/stockquote.xsd"> <soapenv:Header/> <soapenv:Body> <stoc:TradePrice> <price>120.123</price> </stoc:TradePrice> </soapenv:Body> </soapenv:Envelope> """.strip() client.set_ns_prefix('stoc', 'http://example.com/stockquote.xsd') with requests_mock.mock() as m: m.post('http://example.com/stockquote', text=response) account_type = client.get_type('stoc:account') account = account_type(id=100) account.user = '******' country = client.get_element('stoc:country').type() country.name = 'The Netherlands' country.code = 'NL' result = client.service.GetLastTradePrice(tickerSymbol='foobar', account=account, country=country) assert result == 120.123 request = m.request_history[0] # Compare request body expected = """ <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:stoc="http://example.com/stockquote.xsd"> <soap-env:Body> <stoc:TradePriceRequest> <tickerSymbol>foobar</tickerSymbol> <account> <id>100</id> <user>mvantellingen</user> </account> <stoc:country> <name>The Netherlands</name> <code>NL</code> </stoc:country> </stoc:TradePriceRequest> </soap-env:Body> </soap-env:Envelope> """ assert_nodes_equal(expected, request.body)
def _mx_pac_edi_finkok_cancel(self, move, credentials, cfdi): uuid = move.mx_pac_edi_cfdi_uuid certificates = move.company_id.mx_pac_edi_certificate_ids certificate = certificates.sudo().get_valid_certificate() company = move.company_id cer_pem = certificate.get_pem_cer(certificate.content) key_pem = certificate.get_pem_key(certificate.key, certificate.password) try: transport = Transport(timeout=20) client = Client(credentials['cancel_url'], transport=transport) uuid_type = client.get_type('ns0:stringArray')() uuid_type.string = [uuid] invoices_list = client.get_type('ns1:UUIDS')(uuid_type) response = client.service.cancel( invoices_list, credentials['username'], credentials['password'], company.vat, cer_pem, key_pem, ) except Exception as e: return { 'errors': [_("The Finkok service failed to cancel with the following error: %s", str(e))], } if not getattr(response, 'Folios', None): code = getattr(response, 'CodEstatus', None) msg = _("Cancelling got an error") if code else _('A delay of 2 hours has to be respected before to cancel') else: code = getattr(response.Folios.Folio[0], 'EstatusUUID', None) cancelled = code in ('201', '202') # cancelled or previously cancelled # no show code and response message if cancel was success code = '' if cancelled else code msg = '' if cancelled else _("Cancelling got an error") errors = [] if code: errors.append(_("Code : %s") % code) if msg: errors.append(_("Message : %s") % msg) if errors: return {'errors': errors} return {'success': True}
def test_parse_soap_wsdl(): client = Client('tests/wsdl_files/soap.wsdl', transport=Transport(),) response = """ <?xml version="1.0"?> <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:stoc="http://example.com/stockquote.xsd"> <soapenv:Header/> <soapenv:Body> <stoc:TradePrice> <price>120.123</price> </stoc:TradePrice> </soapenv:Body> </soapenv:Envelope> """.strip() client.set_ns_prefix('stoc', 'http://example.com/stockquote.xsd') with requests_mock.mock() as m: m.post('http://example.com/stockquote', text=response) account_type = client.get_type('stoc:account') account = account_type(id=100) account.user = '******' country = client.get_element('stoc:country').type() country.name = 'The Netherlands' country.code = 'NL' result = client.service.GetLastTradePrice( tickerSymbol='foobar', account=account, country=country) assert result == 120.123 request = m.request_history[0] # Compare request body expected = """ <soap-env:Envelope xmlns:soap-env="http://schemas.xmlsoap.org/soap/envelope/" xmlns:stoc="http://example.com/stockquote.xsd"> <soap-env:Body> <stoc:TradePriceRequest> <tickerSymbol>foobar</tickerSymbol> <account> <id>100</id> <user>mvantellingen</user> </account> <stoc:country> <name>The Netherlands</name> <code>NL</code> </stoc:country> </stoc:TradePriceRequest> </soap-env:Body> </soap-env:Envelope> """ assert_nodes_equal(expected, request.body)
def call_api_with_get_type(): def create_query(word): ns0_merge_option = client.get_type('ns0:MergeOption') ns0_match_option = client.get_type('ns0:MatchOption') query = client.get_type('ns0:Query')( Words=xsd_string(word), ScopeID=xsd_string('HEADWORD'), MatchOption=ns0_match_option('EXACT'), MergeOption=ns0_merge_option('OR') ) return query client = Client(str(WSDL)) xsd_string = client.get_type('xsd:string') xsd_unsigned_int = client.get_type('xsd:unsignedInt') ns1_guid = client.get_type('ns1:guid') guid_list = get_guid_list_from_api() guids = client.get_type('ns0:ArrayOfGuid')([ ns1_guid(guid_list[0]), ns1_guid(guid_list[1]), ]) queries = client.get_type('ns0:ArrayOfQuery')([ create_query('apple'), create_query('america'), ]) response = client.service.SearchDicItem( AuthTicket=xsd_string(''), DicIDList=guids, QueryList=queries, SortOrderID=xsd_string(''), ItemStartIndex=xsd_unsigned_int('0'), ItemCount=xsd_unsigned_int('2'), CompleteItemCount=xsd_unsigned_int('2'), ) for r in response['ItemList']['DicItem']: print(r['Title']['_value_1'].text) print(dir(r['Title']['_value_1'])) print('=' * 5)
class GeniusSOAPClient: def __init__(self, credentials: GeniusCredentials): self.client = Client(settings.GENIUS_MERCHANT_TRANSPORT_SERVICE_WSDL) self.creds = credentials def get_data_type(self, type: str, data: object): """Get construct object from data structure defined in the WSDL document""" return self.client.get_type(type)(**data.__dict__) @property def merchant_credentials(self): ds = self.creds.get_merchant_credentials_ds() return self.get_data_type("ns0:MerchantCredentials", ds)
def update_soap_record(self, soap_object, data): session = Session() session.auth = HTTPBasicAuth(self.nav_user, self.nav_password) soap_service_url = self.nav_soap_service + \ self.nav_company + '/Page/' + soap_object client = Client(soap_service_url, transport=Transport(session=session, cache=SqliteCache())) complex_type = client.get_type(f'ns0:{soap_object}') record = complex_type(**data) serialized_response = client.service.Update(record) return serialized_response
def _l10n_mx_edi_finkok_cancel(self, pac_info, cfdi): """CANCEL for Finkok. """ url = pac_info['url'] username = pac_info['username'] password = pac_info['password'] invoice_obj = self.env['account.move'] xml_string = base64.b64decode(cfdi) xml = objectify.fromstring(xml_string) uuid = invoice_obj.l10n_mx_edi_get_tfd_etree(xml).get('UUID', '') if not uuid: return {} company_id = self.config_id.company_id certificate_ids = company_id.l10n_mx_edi_certificate_ids certificate_id = certificate_ids.sudo().get_valid_certificate() cer_pem = base64.b64encode( certificate_id.get_pem_cer(certificate_id.content)).decode('UTF-8') key_pem = base64.b64encode( certificate_id.get_pem_key( certificate_id.key, certificate_id.password)).decode('UTF-8') cancelled = False code = False try: transport = Transport(timeout=20) client = Client(url, transport=transport) uuid_type = client.get_type("ns0:stringArray") invoices_list = uuid_type([uuid]) response = client.service.cancel(invoices_list, username, password, company_id.vat, cer_pem, key_pem) except BaseException as e: self.l10n_mx_edi_log_error(str(e)) return {} if not getattr(response, 'Folios', None): code = getattr(response, 'CodEstatus', None) msg = _("Cancelling got an error") if code else _( 'A delay of 2 hours has to be respected before to cancel') else: code = getattr(response.Folios[0][0], 'EstatusUUID', None) # cancelled or previously cancelled cancelled = code in ('201', '202') # no show code and response message if cancel was success code = '' if cancelled else code msg = '' if cancelled else _("Cancelling got an error") return {'cancelled': cancelled, 'code': code, 'msg': msg}
def __valid_quote__(cls, data=None): error = '' for name in [ 'esFrecuencia', 'esLista', 'esPaquete', 'datosOrigen', 'datosDestino' ]: if name not in data: error += name + ', ' if error is not '': raise EstafetaWrongData('Fields \"{}\" are mandatory'.format( error[:-2])) if data['esPaquete']: for name in ['alto', 'largo', 'ancho', 'peso']: if name not in data: error += name + ', ' if error is not '': raise EstafetaWrongData( 'When \'esPaquete\' is True, fields \"{}\" ara mandatory'. format(error[:-2])) else: for name in ['alto', 'largo', 'ancho', 'peso']: data[name] = 0 instance = EstafetaClient() transport = Transport() transport.session.verify = False client = Client(instance.url_quote, transport=transport) data['tipoEnvio'] = client.get_type("ns0:TipoEnvio")( EsPaquete=data.pop('esPaquete'), Largo=data.pop('largo'), Alto=data.pop('alto'), Ancho=data.pop('ancho'), Peso=data.pop('peso'), ) return data
def _l10n_mx_edi_finkok_cancel(self, pac_info): '''CANCEL for Finkok. ''' url = pac_info['url'] username = pac_info['username'] password = pac_info['password'] for inv in self: uuid = inv.l10n_mx_edi_cfdi_uuid certificate_ids = inv.company_id.l10n_mx_edi_certificate_ids certificate_id = certificate_ids.sudo().get_valid_certificate() company_id = self.company_id cer_pem = certificate_id.get_pem_cer(certificate_id.content) key_pem = certificate_id.get_pem_key(certificate_id.key, certificate_id.password) cancelled = False code = False try: transport = Transport(timeout=20) client = Client(url, transport=transport) uuid_type = client.get_type("ns0:stringArray") invoices_list = uuid_type([uuid]) response = client.service.cancel(invoices_list, username, password, company_id.vat, cer_pem.replace('\n', ''), key_pem) except Exception as e: inv.l10n_mx_edi_log_error(str(e)) continue if not (hasattr(response, 'Folios') and response.Folios): msg = _( 'A delay of 2 hours has to be respected before to cancel') else: code = getattr(response.Folios[0][0], 'EstatusUUID', None) cancelled = code in ('201', '202' ) # cancelled or previously cancelled # no show code and response message if cancel was success code = '' if cancelled else code msg = '' if cancelled else _("Cancelling got an error") inv._l10n_mx_edi_post_cancel_process(cancelled, code, msg)
class Client: def __init__( self, empresa: str, priv_key: str, priv_key_passphrase: str, demo: bool = False, ): self.empresa = empresa try: self._pkey = crypto.load_privatekey( crypto.FILETYPE_PEM, priv_key, priv_key_passphrase.encode('ascii'), ) except crypto.Error: raise InvalidPassphrase if demo: wsdl = DEMO_WSDL else: wsdl = PROD_WSDL self.soap_client = SoapClient(wsdl) def soap_orden(self, orden: Orden) -> 'zeep.objects.ordenPagoWS': SoapOrden = self.soap_client.get_type('ns0:ordenPagoWS') soap_orden = SoapOrden(**dataclasses.asdict(orden)) soap_orden.empresa = self.empresa return soap_orden def registrar_orden(self, orden: Orden) -> 'zeep.objects.speiServiceResponse': soap_orden = self.soap_orden(orden) joined_fields = join_fields(soap_orden) soap_orden.firma = compute_signature(self._pkey, joined_fields) resp = self.soap_client.service['registraOrden'](soap_orden) if 'descripcionError' in resp and resp.descripcionError: raise StpmexException(**resp.__values__) return resp
def __call__(self, request): """Makes a SoftLayer API call against the SOAP endpoint. :param request request: Request object """ zeep_settings = Settings(strict=False, xml_huge_tree=True) zeep_transport = Transport(cache=SqliteCache(timeout=86400)) client = Client(f"{self.endpoint_url}/{request.service}?wsdl", settings=zeep_settings, transport=zeep_transport, plugins=[self.history]) # print(client.wsdl.dump()) # print("=============== WSDL ==============") # Must define headers like this because otherwise the objectMask header doesn't work # because it isn't sent in with a namespace. xsd_userauth = xsd.Element( f"{{{self.soapns}}}authenticate", xsd.ComplexType([ xsd.Element(f'{{{self.soapns}}}username', xsd.String()), xsd.Element(f'{{{self.soapns}}}apiKey', xsd.String()) ])) # factory = client.type_factory(f"{self.soapns}") the_mask = client.get_type(f"{{{self.soapns}}}SoftLayer_ObjectMask") xsd_mask = xsd.Element(f"{{{self.soapns}}}SoftLayer_ObjectMask", the_mask) # Object Filter filter_type = client.get_type( f"{{{self.soapns}}}{request.service}ObjectFilter") xsd_filter = xsd.Element( f"{{{self.soapns}}}{request.service}ObjectFilter", filter_type) # Result Limit xsd_resultlimit = xsd.Element( f"{{{self.soapns}}}resultLimit", xsd.ComplexType([ xsd.Element('limit', xsd.String()), xsd.Element('offset', xsd.String()), ])) # Might one day want to support unauthenticated requests, but for now assume user auth. headers = [ xsd_userauth(username=request.transport_user, apiKey=request.transport_password), ] if request.limit: headers.append( xsd_resultlimit(limit=request.limit, offset=request.offset)) if request.mask: headers.append(xsd_mask(mask=request.mask)) if request.filter: # The ** here forces python to treat this dict as properties headers.append(xsd_filter(**request.filter)) if request.identifier: init_param = f"{request.service}InitParameters" init_paramtype = client.get_type(f"{{{self.soapns}}}{init_param}") xsdinit_param = xsd.Element(f"{{{self.soapns}}}{init_param}", init_paramtype) # Might want to check if its an id or globalIdentifier at some point, for now only id. headers.append(xsdinit_param(id=request.identifier)) # NEXT Add params... maybe try: method = getattr(client.service, request.method) except AttributeError as ex: message = f"{request.service}::{request.method}() does not exist in {self.soapns}{request.service}?wsdl" raise exceptions.TransportError(404, message) from ex result = method(_soapheaders=headers) # NEXT GET A WAY TO FIND TOTAL ITEMS try: method_return = f"{request.method}Return" serialize = serialize_object(result) if serialize.get('body'): return serialize['body'][method_return] else: # Some responses (like SoftLayer_Account::getObject) don't have a body? return serialize except KeyError as ex: message = f"Error serializeing response\n{result}\n{ex}" raise exceptions.TransportError(500, message)
app = Flask(__name__) #cas = CAS(app, '/test') app.config['CAS_SERVER'] = 'https://www-test.sante-martinique.fr/ideosso' app.config['CAS_SERVICE'] = 'http://172.25.10.72:5000' @app.route('/') def route_root(): st = request.args.get('ticket') r = requests.get('%s/serviceValidate' % app.config['CAS_SERVER'],params=dict(service=app.config['CAS_SERVICE'],ticket=st)) return json.dumps(xmltodict.parse(r.content)) @app.route('/login') def login(): return redirect('%s/login?service=%s' % (app.config['CAS_SERVER'],app.config['CAS_SERVICE'])) app.secret_key = 'A0Zr98j/3yX R~XHH!jmN]LWX/,?RT' nsmap={'wsse':'http://docs.oasis-open.org/wss/2004/01/oasis-200401-wss-wssecurity-secext-1.0.xsd'} from lxml import etree from zeep import Client from zeep.wsse.username import UsernameToken client = Client('https://www-test.sante-martinique.fr/ideodirectory.services/IdeoDirectoryManagerSecure?wsdl',wsse=UsernameToken(username='', password='',use_digest=True)) #node = client.create_message(client.service, 'getPersonneInfos') #usernametoken = node.xpath('//wsse:UsernameToken',namespaces=nsmap)[0] #usernametoken.set('{http://docs.oasis-open.org/wss/2004/01/oasis-200401-wsswssecurity-utility-1.0.xsd}Id','Id') gur_type=client.get_type('{com.sqli.sante.ideoldap.remoting}GetUserRequest') gur = gur_type(idCompte="test") print client.service.getUserInfos(gur) if __name__ == '__main__': app.run(debug=True,host='0.0.0.0')
def test_facturae_face(self): class DemoService(object): def __init__(self, value): self.value = value def enviarFactura(self, *args): return self.value def anularFactura(self, *args): return self.value def consultarFactura(self, *args): return self.value main_company = self.env.ref('base.main_company') with self.assertRaises(exceptions.ValidationError): main_company.face_email = 'test' main_company.face_email = '*****@*****.**' self.invoice.action_integrations() integration = self.env['account.invoice.integration'].search([ ('invoice_id', '=', self.invoice.id) ]) self.assertEqual(integration.method_id.code, "FACe") self.assertEqual(integration.can_send, True) client = Client( wsdl=self.env["ir.config_parameter"].get_param( "account.invoice.face.server", default=None) ) integration.send_action() self.assertEqual(integration.state, 'failed') integration_code = '1234567890' response_ok = client.get_type('ns0:EnviarFacturaResponse')( client.get_type('ns0:Resultado')( codigo='0', descripcion='OK' ), client.get_type('ns0:EnviarFactura')( numeroRegistro=integration_code ) ) with mock.patch('zeep.client.ServiceProxy') as mock_client: mock_client.return_value = DemoService(response_ok) integration.send_action() self.assertEqual(integration.register_number, integration_code) self.assertEqual(integration.state, 'sent') response_update = client.get_type('ns0:ConsultarFacturaResponse')( client.get_type('ns0:Resultado')( codigo='0', descripcion='OK' ), client.get_type('ns0:ConsultarFactura')( '1234567890', client.get_type('ns0:EstadoFactura')( '1200', 'DESC', 'MOTIVO' ), client.get_type('ns0:EstadoFactura')( '4100', 'DESC', 'MOTIVO' ) ) ) with mock.patch('zeep.client.ServiceProxy') as mock_client: mock_client.return_value = DemoService(response_update) integration.update_action() self.assertEqual(integration.integration_status, 'face-1200') response_cancel = client.get_type('ns0:ConsultarFacturaResponse')( client.get_type('ns0:Resultado')( '0', 'OK' ), client.get_type('ns0:AnularFactura')( '1234567890', 'ANULADO' ) ) with mock.patch('zeep.client.ServiceProxy') as mock_client: mock_client.return_value = DemoService(response_cancel) cancel = self.env['account.invoice.integration.cancel'].create({ 'integration_id': integration.id, 'motive': 'Anulacion' }) cancel.cancel_integration() self.assertEqual(integration.state, 'cancelled')
class FriendlyACS(): __metaclass__ = LoggerMeta log = "" log_calls = "" model = "friendly_acs_soap" def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs self.username = self.kwargs['username'] self.password = self.kwargs['password'] self.ipaddr = self.kwargs['ipaddr'] self.wsdl = "http://" + self.kwargs[ 'ipaddr'] + "/ftacsws/acsws.asmx?WSDL" self.client = Client(wsdl=self.wsdl, wsse=UsernameToken(self.username, self.password)) self.port = self.kwargs.get('port', '80') self.log = "" name = "acs_server" def __str__(self): return "FriendlyACS" def close(self): pass def get(self, cpeid, param, source=0): # source = 0 (CPE), source = 1 (DB) ret = self.client.service.FTGetDeviceParameters(devicesn=cpeid, source=source, arraynames=[param]) if None == ret['Params']: return None else: return ret['Params']['ParamWSDL'][0]['Value'] def set(self, cpeid, attr, value): array_of_param = self.client.get_type( '{http://www.friendly-tech.com}ArrayOfParam') arr = array_of_param([{'Name': attr, 'Value': value}]) # TODO: investigate push, endsession, reprovision, priority to make sure they are what we want self.client.service.FTSetDeviceParameters(devicesn=cpeid, \ arrayparams=arr, \ push=True, \ endsession=False, \ priority=0) def rpc(self, cpeid, name, content): ''' Invoke custom RPC on specific CM''' ret = self.client.service.FTRPCInvoke(devicesn=cpeid, rpcname=name, soapcontent=content) return xmltodict.parse(ret['Response']) def rpc_GetParameterAttributes(self, cpeid, name): content = '<cwmp:GetParameterAttributes xmlns:cwmp="urn:dslforum-org:cwmp-1-0"> <ParameterNames arrayType-="xsd:string[1]"> <string>%s</string> </ParameterNames> </cwmp:GetParameterAttributes>' % name ret = self.rpc(cpeid, name, content) return ret['cwmp:GetParameterAttributesResponse']['ParameterList'][ 'ParameterAttributeStruct'] def rpc_GetParameterValues(self, cpeid, name): content = '<cwmp:GetParameterValues xmlns:cwmp="urn:dslforum-org:cwmp-1-0"> <ParameterNames arrayType="xsd:string[1]"> <string>%s</string> </ParameterNames> </cwmp:GetParameterValues>' % name ret = self.rpc(cpeid, name, content) return ret['cwmp:GetParameterValuesResponse']['ParameterList'][ 'ParameterValueStruct']['Value']['#text'] def getcurrent(self, cpeid, param, source=0): self.client.service.FTGetDeviceParameters(devicesn=cpeid, source=source, arraynames=[param + '.']) def rpc_SetParameterAttributes(self, cpeid, name, set_value): content = '<cwmp:SetParameterAttributes xmlns:cwmp="urn:dslforum-org:cwmp-1-0"> <ParameterList arrayType="cwmp:SetParameterAttributesStruct[1]"> <SetParameterAttributesStruct> <Name>%s</Name> <NotificationChange>1</NotificationChange> <Notification>%s</Notification> <AccessListChange>0</AccessListChange> <AccessList></AccessList> </SetParameterAttributesStruct> </ParameterList> </cwmp:SetParameterAttributes>' % ( name, set_value) self.rpc(cpeid, name, content) def rpc_AddObject(self, cpeid, obj_name): content = '<cwmp:AddObject xmlns:cwmp="urn:dslforum-org:cwmp-1-0"> <ObjectName>%s.</ObjectName> <ParameterKey></ParameterKey> </cwmp:AddObject>' % obj_name self.rpc(cpeid, obj_name, content) def rpc_DeleteObject(self, cpeid, obj_name): content = '<cwmp:DeleteObject xmlns:cwmp="urn:dslforum-org:cwmp-1-0"> <ObjectName>%s.</ObjectName> <ParameterKey></ParameterKey> </cwmp:DeleteObject>' % obj_name self.rpc(cpeid, obj_name, content) def is_online(self, cpeid): ret = self.client.service.FTCPEStatus(devicesn=cpeid) return ret['Online'] def delete_cpe(self, cpeid): print("WARN: not impl for this class") pass
class TestZeep(unittest.TestCase): def setUp(self): from spyne.test.interop._test_soap_client_base import run_server run_server('http') self.client = Client("http://localhost:9754/?wsdl") self.ns = "spyne.test.interop.server" def get_inst(self, what): return self.client.get_type(what)() def test_echo_datetime(self): # ZEEP doesn't support microseconds val = datetime.now().replace(microsecond=0) ret = self.client.service.echo_datetime(val) assert val == ret def test_echo_datetime_with_invalid_format(self): # ZEEP doesn't support microseconds val = datetime.now().replace(microsecond=0) ret = self.client.service.echo_datetime_with_invalid_format(val) assert val == ret def test_echo_date(self): val = datetime.now().date() ret = self.client.service.echo_date(val) assert val == ret def test_echo_date_with_invalid_format(self): val = datetime.now().date() ret = self.client.service.echo_date_with_invalid_format(val) assert val == ret def test_echo_time(self): # ZEEP doesnt support microseconds val = datetime.now().replace(microsecond=0).time() ret = self.client.service.echo_time(val) assert val == ret def test_echo_time_with_invalid_format(self): # ZEEP doesnt support microseconds val = datetime.now().replace(microsecond=0).time() ret = self.client.service.echo_time_with_invalid_format(val) assert val == ret def test_echo_simple_boolean_array(self): val = [False, False, False, True] ret = self.client.service.echo_simple_boolean_array(val) assert val == ret def test_echo_boolean(self): val = True ret = self.client.service.echo_boolean(val) self.assertEquals(val, ret) val = False ret = self.client.service.echo_boolean(val) self.assertEquals(val, ret) def test_enum(self): val = self.client.get_type("{%s}DaysOfWeekEnum" % self.ns)('Monday') ret = self.client.service.echo_enum(val) assert val == ret def test_bytearray(self): val = b"\x00\x01\x02\x03\x04" ret = self.client.service.echo_bytearray(val) assert val == ret def test_validation(self): non_nillable_class = self.client.get_type("{hunk.sunk}NonNillableClass")() non_nillable_class.i = 6 non_nillable_class.s = None try: self.client.service.non_nillable(non_nillable_class) except ZeepError as e: pass else: raise Exception("must fail") def test_echo_integer_array(self): ia = self.client.get_type('{%s}integerArray' % self.ns)() ia.integer.extend([1, 2, 3, 4, 5]) self.client.service.echo_integer_array(ia) # FIXME: Figure how this is supposed to work def _test_echo_in_header(self): in_header = self.client.get_type('{%s}InHeader' % self.ns)() in_header.s = 'a' in_header.i = 3 self.client.set_options(soapheaders=in_header) ret = self.client.service.echo_in_header() self.client.set_options(soapheaders=None) print(ret) self.assertEquals(in_header.s, ret.s) self.assertEquals(in_header.i, ret.i) # FIXME: Figure how this is supposed to work def _test_echo_in_complex_header(self): in_header = self.client.get_type('{%s}InHeader' % self.ns)() in_header.s = 'a' in_header.i = 3 in_trace_header = self.client.get_type('{%s}InTraceHeader' % self.ns)() in_trace_header.client = 'suds' in_trace_header.callDate = datetime(year=2000, month=1, day=1, hour=0, minute=0, second=0, microsecond=0) self.client.set_options(soapheaders=(in_header, in_trace_header)) ret = self.client.service.echo_in_complex_header() self.client.set_options(soapheaders=None) print(ret) self.assertEquals(in_header.s, ret[0].s) self.assertEquals(in_header.i, ret[0].i) self.assertEquals(in_trace_header.client, ret[1].client) self.assertEquals(in_trace_header.callDate, ret[1].callDate) def test_send_out_header(self): out_header = self.client.get_type('{%s}OutHeader' % self.ns)() out_header.dt = datetime(year=2000, month=1, day=1) out_header.f = 3.141592653 ret = self.client.service.send_out_header() self.assertEquals(ret.header.OutHeader.dt, out_header.dt) self.assertEquals(ret.header.OutHeader.f, out_header.f) def test_send_out_complex_header(self): out_header = self.client.get_type('{%s}OutHeader' % self.ns)() out_header.dt = datetime(year=2000, month=1, day=1) out_header.f = 3.141592653 out_trace_header = self.client.get_type('{%s}OutTraceHeader' % self.ns)() out_trace_header.receiptDate = datetime(year=2000, month=1, day=1, hour=1, minute=1, second=1, microsecond=1) out_trace_header.returnDate = datetime(year=2000, month=1, day=1, hour=1, minute=1, second=1, microsecond=100) ret = self.client.service.send_out_complex_header() self.assertEquals(ret.header.OutHeader.dt, out_header.dt) self.assertEquals(ret.header.OutHeader.f, out_header.f) self.assertEquals(ret.header.OutTraceHeader.receiptDate, out_trace_header.receiptDate) self.assertEquals(ret.header.OutTraceHeader.returnDate, out_trace_header.returnDate) def test_echo_string(self): test_string = "OK" ret = self.client.service.echo_string(test_string) self.assertEquals(ret, test_string) def __get_xml_test_val(self): return { "test_sub": { "test_subsub1": { "test_subsubsub1": ["subsubsub1 value"] }, "test_subsub2": ["subsub2 value 1", "subsub2 value 2"], "test_subsub3": [ { "test_subsub3sub1": ["subsub3sub1 value"] }, { "test_subsub3sub2": ["subsub3sub2 value"] }, ], "test_subsub4": [], "test_subsub5": ["x"], } } def test_echo_simple_class(self): val = self.client.get_type("{%s}SimpleClass" % self.ns)() val.i = 45 val.s = "asd" # why val loses all its data after being passed to service request? # it doesn't work without deepcopy! ret = self.client.service.echo_simple_class(deepcopy(val)) assert ret.i == val.i assert ret.s == val.s def test_echo_class_with_self_reference(self): val = self.client.get_type("{%s}ClassWithSelfReference" % self.ns)() val.i = 45 val.sr = self.client.get_type("{%s}ClassWithSelfReference" % self.ns)() val.sr.i = 50 val.sr.sr = None # why val loses all its data after being passed to service request? # it doesn't work without deepcopy! ret = self.client.service.echo_class_with_self_reference(deepcopy(val)) assert ret.i == val.i assert ret.sr.i == val.sr.i def test_echo_nested_class(self): val = self.client.get_type("{punk.tunk}NestedClass")() val.i = 45 val.s = "asd" val.f = 12.34 val.ai = self.client.get_type("{%s}integerArray" % self.ns)() val.ai.integer.extend([1, 2, 3, 45, 5, 3, 2, 1, 4]) val.simple = self.client.get_type("{%s}SimpleClassArray" % self.ns)() val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass[0].i = 45 val.simple.SimpleClass[0].s = "asd" val.simple.SimpleClass[1].i = 12 val.simple.SimpleClass[1].s = "qwe" val.other = self.client.get_type("{%s}OtherClass" % self.ns)() # ZEEP doesn't support microseconds val.other.dt = datetime.now().replace(microsecond=0) val.other.d = 123.456 val.other.b = True # why val loses all its data after being passed to service request? # it doesn't work without deepcopy! ret = self.client.service.echo_nested_class(deepcopy(val)) self.assertEquals(ret.i, val.i) self.assertEqual(ret.ai.integer, val.ai.integer) self.assertEqual(ret.ai.integer[0], val.ai.integer[0]) self.assertEquals(ret.simple.SimpleClass[0].s, val.simple.SimpleClass[0].s) self.assertEqual(ret.other.dt, val.other.dt) def test_huge_number(self): self.assertEquals(self.client.service.huge_number(), 2 ** int(1e5)) def test_long_string(self): self.assertEquals(self.client.service.long_string(), ('0123456789abcdef' * 16384)) def test_empty(self): self.client.service.test_empty() def test_echo_extension_class(self): val = self.client.get_type("{bar}ExtensionClass")() val.i = 45 val.s = "asd" val.f = 12.34 val.simple = self.client.get_type("{%s}SimpleClassArray" % self.ns)() val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass[0].i = 45 val.simple.SimpleClass[0].s = "asd" val.simple.SimpleClass[1].i = 12 val.simple.SimpleClass[1].s = "qwe" val.other = self.client.get_type("{%s}OtherClass" % self.ns)() # ZEEP doesn't support microseconds val.other.dt = datetime.now().replace(microsecond=0) val.other.d = 123.456 val.other.b = True val.p = self.client.get_type("{hunk.sunk}NonNillableClass")() val.p.dt = datetime(2010, 6, 2) val.p.i = 123 val.p.s = "punk" val.l = datetime(2010, 7, 2) val.q = 5 # why val loses all its data after being passed to service request? # it doesn't work without deepcopy! ret = self.client.service.echo_extension_class(deepcopy(val)) print(ret) self.assertEquals(ret.i, val.i) self.assertEquals(ret.s, val.s) self.assertEquals(ret.f, val.f) self.assertEquals(ret.simple.SimpleClass[0].i, val.simple.SimpleClass[0].i) self.assertEquals(ret.other.dt, val.other.dt) self.assertEquals(ret.p.s, val.p.s) def test_python_exception(self): try: self.client.service.python_exception() raise Exception("must fail") except ZeepError as e: pass def test_soap_exception(self): try: self.client.service.soap_exception() raise Exception("must fail") except ZeepError as e: pass def test_complex_return(self): ret = self.client.service.complex_return() self.assertEquals(ret.resultCode, 1) self.assertEquals(ret.resultDescription, "Test") self.assertEquals(ret.transactionId, 123) self.assertEquals(ret.roles.RoleEnum[0], "MEMBER") def test_return_invalid_data(self): try: self.client.service.return_invalid_data() raise Exception("must fail") except: pass def test_custom_messages(self): ret = self.client.service.custom_messages("test") assert ret == 'test' def test_echo_simple_bare(self): ret = self.client.service.echo_simple_bare("test") assert ret == 'test' # # This test is disabled because zeep does not create the right request # object. Opening the first <ns0:string> tag below is wrong. # #<SOAP-ENV:Envelope xmlns:ns0="spyne.test.interop.server" # xmlns:xs="http://www.w3.org/2001/XMLSchema" # xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" # xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" # xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> # <SOAP-ENV:Header/> # <ns1:Body> # <ns0:echo_complex_bare> # <ns0:string> # <ns0:string>abc</ns0:string> # <ns0:string>def</ns0:string> # </ns0:string> # </ns0:echo_complex_bare> # </ns1:Body> #</SOAP-ENV:Envelope> # # The right request looks like this: # # <ns0:echo_complex_bare> # <ns0:string>abc</ns0:string> # <ns0:string>def</ns0:string> # </ns0:echo_complex_bare> # def _test_echo_complex_bare(self): val = ['abc','def'] ia = self.client.get_type('{%s}stringArray' % self.ns)() ia.string.extend(val) ret = self.client.service.echo_complex_bare(ia) assert ret == val
class AxirosACS(): model = "axiros_acs_soap" def __init__(self, *args, **kwargs): self.args = args self.kwargs = kwargs self.username = self.kwargs['username'] self.password = self.kwargs['password'] self.ipaddr = self.kwargs['ipaddr'] self.port = self.kwargs.get('port', None) if self.port is not None: target = self.ipaddr + ":" + self.port else: target = self.ipaddr self.wsdl = "http://" + target + "/live/CPEManager/DMInterfaces/soap/getWSDL" session = Session() session.auth = HTTPBasicAuth(self.username, self.password) self.client = Client(wsdl=self.wsdl, transport=Transport(session=session), wsse=UsernameToken(self.username, self.password)) name = "acs_server" def __str__(self): return "AxirosACS" def close(self): pass def get(self, serial_number, param): GetParameterValuesParametersClassArray_type = self.client.get_type( 'ns0:GetParameterValuesParametersClassArray') GetParameterValuesParametersClassArray_data = GetParameterValuesParametersClassArray_type( [param]) CommandOptionsTypeStruct_type = self.client.get_type( 'ns0:CommandOptionsTypeStruct') CommandOptionsTypeStruct_data = CommandOptionsTypeStruct_type() CPEIdentifierClassStruct_type = self.client.get_type( 'ns0:CPEIdentifierClassStruct') CPEIdentifierClassStruct_data = CPEIdentifierClassStruct_type( cpeid=serial_number) # get raw soap response (parsing error with zeep) with self.client.settings(raw_response=True): response = self.client.service.GetParameterValues( GetParameterValuesParametersClassArray_data, CommandOptionsTypeStruct_data, CPEIdentifierClassStruct_data) ticketid = None root = ElementTree.fromstring(response.content) for value in root.iter('ticketid'): ticketid = value.text break if ticketid is None: return None return self.Axiros_GetTicketValue(ticketid) def getcurrent(self, serial_number, param): self.get(serial_number, param + '.') # TODO: note: verified ticket was sent to ACS with all the results in the param namespace # however the get above does not pull the results so we can't check them here but that's # not a major issue since the API does not do that for the current implementation def set(self, serial_number, attr, value): SetParameterValuesParametersClassArray_type = self.client.get_type( 'ns0:SetParameterValuesParametersClassArray') SetParameterValuesParametersClassArray_data = SetParameterValuesParametersClassArray_type( [{ 'key': attr, 'value': value }]) CommandOptionsTypeStruct_type = self.client.get_type( 'ns0:CommandOptionsTypeStruct') CommandOptionsTypeStruct_data = CommandOptionsTypeStruct_type() CPEIdentifierClassStruct_type = self.client.get_type( 'ns0:CPEIdentifierClassStruct') CPEIdentifierClassStruct_data = CPEIdentifierClassStruct_type( cpeid=serial_number) # get raw soap response (parsing error with zeep) with self.client.settings(raw_response=True): response = self.client.service.SetParameterValues( SetParameterValuesParametersClassArray_data, CommandOptionsTypeStruct_data, CPEIdentifierClassStruct_data) ticketid = None root = ElementTree.fromstring(response.content) for value in root.iter('ticketid'): ticketid = value.text break if ticketid is None: return None return self.Axiros_GetTicketValue(ticketid) def Axiros_GetListOfCPEs(self): CPESearchOptionsClassStruct_type = self.client.get_type( 'ns0:CPESearchOptionsClassStruct') CPESearchOptionsClassStruct_data = CPESearchOptionsClassStruct_type() CommandOptionsForCPESearchStruct_type = self.client.get_type( 'ns0:CommandOptionsForCPESearchStruct') CommandOptionsForCPESearchStruct_data = CommandOptionsForCPESearchStruct_type( ) response = self.client.service.GetListOfCPEs( CPESearchOptionsClassStruct_data, CommandOptionsForCPESearchStruct_data) if response['code'] != 200: return None return response def Axiros_GetTicketResponse(self, ticketid): response = self.client.service.get_generic_sb_result(ticketid) if response['code'] != 200: return None return response['code'] def Axiros_GetTicketValue(self, ticketid): for i in range(8): time.sleep(1) with self.client.settings(raw_response=True): ticket_resp = self.client.service.get_generic_sb_result( ticketid) root = ElementTree.fromstring(ticket_resp.content) for value in root.iter('code'): break if (value.text != '200'): continue for value in root.iter('value'): return value.text return None
class TestZeep(unittest.TestCase): def setUp(self): from spyne.test.interop._test_soap_client_base import run_server run_server('http') self.client = Client("http://localhost:9754/?wsdl") self.ns = "spyne.test.interop.server" def get_inst(self, what): return self.client.get_type(what)() def test_echo_datetime(self): # ZEEP doesn't support microseconds val = datetime.now().replace(microsecond=0) ret = self.client.service.echo_datetime(val) assert val == ret def test_echo_datetime_with_invalid_format(self): # ZEEP doesn't support microseconds val = datetime.now().replace(microsecond=0) ret = self.client.service.echo_datetime_with_invalid_format(val) assert val == ret def test_echo_date(self): val = datetime.now().date() ret = self.client.service.echo_date(val) assert val == ret def test_echo_date_with_invalid_format(self): val = datetime.now().date() ret = self.client.service.echo_date_with_invalid_format(val) assert val == ret def test_echo_time(self): # ZEEP doesnt support microseconds val = datetime.now().replace(microsecond=0).time() ret = self.client.service.echo_time(val) assert val == ret def test_echo_time_with_invalid_format(self): # ZEEP doesnt support microseconds val = datetime.now().replace(microsecond=0).time() ret = self.client.service.echo_time_with_invalid_format(val) assert val == ret def test_echo_simple_boolean_array(self): val = [False, False, False, True] ret = self.client.service.echo_simple_boolean_array(val) assert val == ret def test_echo_boolean(self): val = True ret = self.client.service.echo_boolean(val) self.assertEquals(val, ret) val = False ret = self.client.service.echo_boolean(val) self.assertEquals(val, ret) def test_enum(self): val = self.client.get_type("{%s}DaysOfWeekEnum" % self.ns)('Monday') ret = self.client.service.echo_enum(val) assert val == ret def test_bytearray(self): val = b"\x00\x01\x02\x03\x04" ret = self.client.service.echo_bytearray(val) assert val == ret def test_validation(self): non_nillable_class = self.client.get_type( "{hunk.sunk}NonNillableClass")() non_nillable_class.i = 6 non_nillable_class.s = None try: self.client.service.non_nillable(non_nillable_class) except ZeepError as e: pass else: raise Exception("must fail") def test_echo_integer_array(self): ia = self.client.get_type('{%s}integerArray' % self.ns)() ia.integer.extend([1, 2, 3, 4, 5]) self.client.service.echo_integer_array(ia) # FIXME: Figure how this is supposed to work def _test_echo_in_header(self): in_header = self.client.get_type('{%s}InHeader' % self.ns)() in_header.s = 'a' in_header.i = 3 self.client.set_options(soapheaders=in_header) ret = self.client.service.echo_in_header() self.client.set_options(soapheaders=None) print(ret) self.assertEquals(in_header.s, ret.s) self.assertEquals(in_header.i, ret.i) # FIXME: Figure how this is supposed to work def _test_echo_in_complex_header(self): in_header = self.client.get_type('{%s}InHeader' % self.ns)() in_header.s = 'a' in_header.i = 3 in_trace_header = self.client.get_type('{%s}InTraceHeader' % self.ns)() in_trace_header.client = 'suds' in_trace_header.callDate = datetime(year=2000, month=1, day=1, hour=0, minute=0, second=0, microsecond=0) self.client.set_options(soapheaders=(in_header, in_trace_header)) ret = self.client.service.echo_in_complex_header() self.client.set_options(soapheaders=None) print(ret) self.assertEquals(in_header.s, ret[0].s) self.assertEquals(in_header.i, ret[0].i) self.assertEquals(in_trace_header.client, ret[1].client) self.assertEquals(in_trace_header.callDate, ret[1].callDate) def test_send_out_header(self): out_header = self.client.get_type('{%s}OutHeader' % self.ns)() out_header.dt = datetime(year=2000, month=1, day=1) out_header.f = 3.141592653 ret = self.client.service.send_out_header() self.assertEquals(ret.header.OutHeader.dt, out_header.dt) self.assertEquals(ret.header.OutHeader.f, out_header.f) def test_send_out_complex_header(self): out_header = self.client.get_type('{%s}OutHeader' % self.ns)() out_header.dt = datetime(year=2000, month=1, day=1) out_header.f = 3.141592653 out_trace_header = self.client.get_type('{%s}OutTraceHeader' % self.ns)() out_trace_header.receiptDate = datetime(year=2000, month=1, day=1, hour=1, minute=1, second=1, microsecond=1) out_trace_header.returnDate = datetime(year=2000, month=1, day=1, hour=1, minute=1, second=1, microsecond=100) ret = self.client.service.send_out_complex_header() self.assertEquals(ret.header.OutHeader.dt, out_header.dt) self.assertEquals(ret.header.OutHeader.f, out_header.f) self.assertEquals(ret.header.OutTraceHeader.receiptDate, out_trace_header.receiptDate) self.assertEquals(ret.header.OutTraceHeader.returnDate, out_trace_header.returnDate) def test_echo_string(self): test_string = "OK" ret = self.client.service.echo_string(test_string) self.assertEquals(ret, test_string) def __get_xml_test_val(self): return { "test_sub": { "test_subsub1": { "test_subsubsub1": ["subsubsub1 value"] }, "test_subsub2": ["subsub2 value 1", "subsub2 value 2"], "test_subsub3": [ { "test_subsub3sub1": ["subsub3sub1 value"] }, { "test_subsub3sub2": ["subsub3sub2 value"] }, ], "test_subsub4": [], "test_subsub5": ["x"], } } def test_echo_simple_class(self): val = self.client.get_type("{%s}SimpleClass" % self.ns)() val.i = 45 val.s = "asd" # why val loses all its data after being passed to service request? # it doesn't work without deepcopy! ret = self.client.service.echo_simple_class(deepcopy(val)) assert ret.i == val.i assert ret.s == val.s def test_echo_class_with_self_reference(self): val = self.client.get_type("{%s}ClassWithSelfReference" % self.ns)() val.i = 45 val.sr = self.client.get_type("{%s}ClassWithSelfReference" % self.ns)() val.sr.i = 50 val.sr.sr = None # why val loses all its data after being passed to service request? # it doesn't work without deepcopy! ret = self.client.service.echo_class_with_self_reference(deepcopy(val)) assert ret.i == val.i assert ret.sr.i == val.sr.i def test_echo_nested_class(self): val = self.client.get_type("{punk.tunk}NestedClass")() val.i = 45 val.s = "asd" val.f = 12.34 val.ai = self.client.get_type("{%s}integerArray" % self.ns)() val.ai.integer.extend([1, 2, 3, 45, 5, 3, 2, 1, 4]) val.simple = self.client.get_type("{%s}SimpleClassArray" % self.ns)() val.simple.SimpleClass.append( self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass.append( self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass[0].i = 45 val.simple.SimpleClass[0].s = "asd" val.simple.SimpleClass[1].i = 12 val.simple.SimpleClass[1].s = "qwe" val.other = self.client.get_type("{%s}OtherClass" % self.ns)() # ZEEP doesn't support microseconds val.other.dt = datetime.now().replace(microsecond=0) val.other.d = 123.456 val.other.b = True # why val loses all its data after being passed to service request? # it doesn't work without deepcopy! ret = self.client.service.echo_nested_class(deepcopy(val)) self.assertEquals(ret.i, val.i) self.assertEqual(ret.ai.integer, val.ai.integer) self.assertEqual(ret.ai.integer[0], val.ai.integer[0]) self.assertEquals(ret.simple.SimpleClass[0].s, val.simple.SimpleClass[0].s) self.assertEqual(ret.other.dt, val.other.dt) def test_huge_number(self): self.assertEquals(self.client.service.huge_number(), 2**int(1e5)) def test_long_string(self): self.assertEquals(self.client.service.long_string(), ('0123456789abcdef' * 16384)) def test_empty(self): self.client.service.test_empty() def test_echo_extension_class(self): val = self.client.get_type("{bar}ExtensionClass")() val.i = 45 val.s = "asd" val.f = 12.34 val.simple = self.client.get_type("{%s}SimpleClassArray" % self.ns)() val.simple.SimpleClass.append( self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass.append( self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass[0].i = 45 val.simple.SimpleClass[0].s = "asd" val.simple.SimpleClass[1].i = 12 val.simple.SimpleClass[1].s = "qwe" val.other = self.client.get_type("{%s}OtherClass" % self.ns)() # ZEEP doesn't support microseconds val.other.dt = datetime.now().replace(microsecond=0) val.other.d = 123.456 val.other.b = True val.p = self.client.get_type("{hunk.sunk}NonNillableClass")() val.p.dt = datetime(2010, 6, 2) val.p.i = 123 val.p.s = "punk" val.l = datetime(2010, 7, 2) val.q = 5 # why val loses all its data after being passed to service request? # it doesn't work without deepcopy! ret = self.client.service.echo_extension_class(deepcopy(val)) print(ret) self.assertEquals(ret.i, val.i) self.assertEquals(ret.s, val.s) self.assertEquals(ret.f, val.f) self.assertEquals(ret.simple.SimpleClass[0].i, val.simple.SimpleClass[0].i) self.assertEquals(ret.other.dt, val.other.dt) self.assertEquals(ret.p.s, val.p.s) def test_python_exception(self): try: self.client.service.python_exception() raise Exception("must fail") except ZeepError as e: pass def test_soap_exception(self): try: self.client.service.soap_exception() raise Exception("must fail") except ZeepError as e: pass def test_complex_return(self): ret = self.client.service.complex_return() self.assertEquals(ret.resultCode, 1) self.assertEquals(ret.resultDescription, "Test") self.assertEquals(ret.transactionId, 123) self.assertEquals(ret.roles.RoleEnum[0], "MEMBER") def test_return_invalid_data(self): try: self.client.service.return_invalid_data() raise Exception("must fail") except: pass def test_custom_messages(self): ret = self.client.service.custom_messages("test") assert ret == 'test' def test_echo_simple_bare(self): ret = self.client.service.echo_simple_bare("test") assert ret == 'test' # # This test is disabled because zeep does not create the right request # object. Opening the first <ns0:string> tag below is wrong. # #<SOAP-ENV:Envelope xmlns:ns0="spyne.test.interop.server" # xmlns:xs="http://www.w3.org/2001/XMLSchema" # xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" # xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" # xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> # <SOAP-ENV:Header/> # <ns1:Body> # <ns0:echo_complex_bare> # <ns0:string> # <ns0:string>abc</ns0:string> # <ns0:string>def</ns0:string> # </ns0:string> # </ns0:echo_complex_bare> # </ns1:Body> #</SOAP-ENV:Envelope> # # The right request looks like this: # # <ns0:echo_complex_bare> # <ns0:string>abc</ns0:string> # <ns0:string>def</ns0:string> # </ns0:echo_complex_bare> # def _test_echo_complex_bare(self): val = ['abc', 'def'] ia = self.client.get_type('{%s}stringArray' % self.ns)() ia.string.extend(val) ret = self.client.service.echo_complex_bare(ia) assert ret == val
# Main # # Consume WSDL and generate soap structures try: session = Session() if (args.nosslverify): session.verify = False session.sslverify = False transport = DebugTransport(cache=SqliteCache(), session=session) wudetails = Client(wudetailsservice_wsdl_url, transport=transport) except: logging.critical ('Unable to obtain WSDL from ' +wudetailsservice_wsdl_url) raise try: scopeFilter = wudetails.get_type('ns0:WUScopeFilter') nestedFilter = wudetails.get_type('ns0:WUNestedFilter') propertiesToReturn = wudetails.get_type('ns0:WUPropertiesToReturn') scopeOptions = wudetails.get_type('ns0:WUScopeOptions') propertyOptions = wudetails.get_type('ns0:WUPropertyOptions') extraProperties = wudetails.get_type('ns0:WUExtraProperties') except: logging.critical ('WSDL different from expected') raise # Generate Test cases testCase = namedtuple('testCase', ['ScopeFilter', 'NestedFilter', 'PropertiesToReturn', 'ScopeOptions',
class TestZeep(unittest.TestCase): def setUp(self): from spyne.test.interop._test_soap_client_base import run_server run_server('http') transport = Transport(cache=False) self.client = Client("http://localhost:9754/?wsdl", transport=transport) self.ns = "spyne.test.interop.server" def get_inst(self, what): return self.client.get_type(what)() def test_echo_datetime(self): val = datetime.now() ret = self.client.service.echo_datetime(val) assert val == ret def test_echo_datetime_with_invalid_format(self): val = datetime.now() ret = self.client.service.echo_datetime_with_invalid_format(val) assert val == ret def test_echo_date(self): val = datetime.now().date() ret = self.client.service.echo_date(val) assert val == ret def test_echo_date_with_invalid_format(self): val = datetime.now().date() ret = self.client.service.echo_date_with_invalid_format(val) assert val == ret def test_echo_time(self): val = datetime.now().time() ret = self.client.service.echo_time(val) assert val == ret def test_echo_time_with_invalid_format(self): val = datetime.now().time() ret = self.client.service.echo_time_with_invalid_format(val) assert val == ret def test_echo_simple_boolean_array(self): val = [False, False, False, True] ret = self.client.service.echo_simple_boolean_array(val) assert val == ret def test_echo_boolean(self): val = True ret = self.client.service.echo_boolean(val) self.assertEquals(val, ret) val = False ret = self.client.service.echo_boolean(val) self.assertEquals(val, ret) def test_enum(self): val = self.client.get_type("{%s}DaysOfWeekEnum" % self.ns)('Monday') ret = self.client.service.echo_enum(val) assert val == ret def test_bytearray(self): val = b"\x00\x01\x02\x03\x04" ret = self.client.service.echo_bytearray(val) assert val == ret def test_validation(self): non_nillable_class = self.client.get_type("{hunk.sunk}NonNillableClass")() non_nillable_class.i = 6 non_nillable_class.s = None try: self.client.service.non_nillable(non_nillable_class) except ZeepError as e: pass else: raise Exception("must fail") def test_echo_integer_array(self): ia = self.client.get_type('{%s}integerArray' % self.ns)() ia.integer.extend([1, 2, 3, 4, 5]) self.client.service.echo_integer_array(ia) def test_echo_in_header(self): in_header = self.client.get_type('{%s}InHeader' % self.ns)() in_header.s = 'a' in_header.i = 3 ret = self.client.service.echo_in_header(_soapheaders={ 'InHeader': in_header, }) print(ret) out_header = ret.body.echo_in_headerResult self.assertEquals(in_header.s, out_header.s) self.assertEquals(in_header.i, out_header.i) def test_echo_in_complex_header(self): in_header = self.client.get_type('{%s}InHeader' % self.ns)() in_header.s = 'a' in_header.i = 3 in_trace_header = self.client.get_type('{%s}InTraceHeader' % self.ns)() in_trace_header.client = 'suds' in_trace_header.callDate = datetime(year=2000, month=1, day=1, hour=0, minute=0, second=0, microsecond=0) ret = self.client.service.echo_in_complex_header(_soapheaders={ 'InHeader': in_header, 'InTraceHeader': in_trace_header }) print(ret) out_header = ret.body.echo_in_complex_headerResult0 out_trace_header = ret.body.echo_in_complex_headerResult1 self.assertEquals(in_header.s, out_header.s) self.assertEquals(in_header.i, out_header.i) self.assertEquals(in_trace_header.client, out_trace_header.client) self.assertEquals(in_trace_header.callDate, out_trace_header.callDate) def test_send_out_header(self): out_header = self.client.get_type('{%s}OutHeader' % self.ns)() out_header.dt = datetime(year=2000, month=1, day=1) out_header.f = 3.141592653 ret = self.client.service.send_out_header() self.assertEquals(ret.header.OutHeader.dt, out_header.dt) self.assertEquals(ret.header.OutHeader.f, out_header.f) def test_send_out_complex_header(self): out_header = self.client.get_type('{%s}OutHeader' % self.ns)() out_header.dt = datetime(year=2000, month=1, day=1) out_header.f = 3.141592653 out_trace_header = self.client.get_type('{%s}OutTraceHeader' % self.ns)() out_trace_header.receiptDate = datetime(year=2000, month=1, day=1, hour=1, minute=1, second=1, microsecond=1) out_trace_header.returnDate = datetime(year=2000, month=1, day=1, hour=1, minute=1, second=1, microsecond=100) ret = self.client.service.send_out_complex_header() self.assertEquals(ret.header.OutHeader.dt, out_header.dt) self.assertEquals(ret.header.OutHeader.f, out_header.f) self.assertEquals(ret.header.OutTraceHeader.receiptDate, out_trace_header.receiptDate) self.assertEquals(ret.header.OutTraceHeader.returnDate, out_trace_header.returnDate) def test_echo_string(self): test_string = "OK" ret = self.client.service.echo_string(test_string) self.assertEquals(ret, test_string) def __get_xml_test_val(self): return { "test_sub": { "test_subsub1": { "test_subsubsub1": ["subsubsub1 value"] }, "test_subsub2": ["subsub2 value 1", "subsub2 value 2"], "test_subsub3": [ { "test_subsub3sub1": ["subsub3sub1 value"] }, { "test_subsub3sub2": ["subsub3sub2 value"] }, ], "test_subsub4": [], "test_subsub5": ["x"], } } def test_echo_simple_class(self): val = self.client.get_type("{%s}SimpleClass" % self.ns)() val.i = 45 val.s = "asd" ret = self.client.service.echo_simple_class(val) assert ret.i == val.i assert ret.s == val.s def test_echo_class_with_self_reference(self): val = self.client.get_type("{%s}ClassWithSelfReference" % self.ns)() val.i = 45 val.sr = self.client.get_type("{%s}ClassWithSelfReference" % self.ns)() val.sr.i = 50 val.sr.sr = None ret = self.client.service.echo_class_with_self_reference(val) assert ret.i == val.i assert ret.sr.i == val.sr.i def test_echo_nested_class(self): val = self.client.get_type("{punk.tunk}NestedClass")() val.i = 45 val.s = "asd" val.f = 12.34 val.ai = self.client.get_type("{%s}integerArray" % self.ns)() val.ai.integer.extend([1, 2, 3, 45, 5, 3, 2, 1, 4]) val.simple = self.client.get_type("{%s}SimpleClassArray" % self.ns)() val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass[0].i = 45 val.simple.SimpleClass[0].s = "asd" val.simple.SimpleClass[1].i = 12 val.simple.SimpleClass[1].s = "qwe" val.other = self.client.get_type("{%s}OtherClass" % self.ns)() val.other.dt = datetime.now() val.other.d = 123.456 val.other.b = True ret = self.client.service.echo_nested_class(val) self.assertEquals(ret.i, val.i) self.assertEqual(ret.ai.integer, val.ai.integer) self.assertEqual(ret.ai.integer[0], val.ai.integer[0]) self.assertEquals(ret.simple.SimpleClass[0].s, val.simple.SimpleClass[0].s) self.assertEqual(ret.other.dt, val.other.dt) def test_huge_number(self): self.assertEquals(self.client.service.huge_number(), 2 ** int(1e5)) def test_long_string(self): self.assertEquals(self.client.service.long_string(), ('0123456789abcdef' * 16384)) def test_empty(self): self.client.service.test_empty() def test_echo_extension_class(self): val = self.client.get_type("{bar}ExtensionClass")() val.i = 45 val.s = "asd" val.f = 12.34 val.simple = self.client.get_type("{%s}SimpleClassArray" % self.ns)() val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass.append(self.client.get_type("{%s}SimpleClass" % self.ns)()) val.simple.SimpleClass[0].i = 45 val.simple.SimpleClass[0].s = "asd" val.simple.SimpleClass[1].i = 12 val.simple.SimpleClass[1].s = "qwe" val.other = self.client.get_type("{%s}OtherClass" % self.ns)() val.other.dt = datetime.now() val.other.d = 123.456 val.other.b = True val.p = self.client.get_type("{hunk.sunk}NonNillableClass")() val.p.dt = datetime(2010, 6, 2) val.p.i = 123 val.p.s = "punk" val.l = datetime(2010, 7, 2) val.q = 5 ret = self.client.service.echo_extension_class(val) print(ret) self.assertEquals(ret.i, val.i) self.assertEquals(ret.s, val.s) self.assertEquals(ret.f, val.f) self.assertEquals(ret.simple.SimpleClass[0].i, val.simple.SimpleClass[0].i) self.assertEquals(ret.other.dt, val.other.dt) self.assertEquals(ret.p.s, val.p.s) def test_python_exception(self): try: self.client.service.python_exception() raise Exception("must fail") except ZeepError as e: pass def test_soap_exception(self): try: self.client.service.soap_exception() raise Exception("must fail") except ZeepError as e: pass def test_complex_return(self): ret = self.client.service.complex_return() self.assertEquals(ret.resultCode, 1) self.assertEquals(ret.resultDescription, "Test") self.assertEquals(ret.transactionId, 123) self.assertEquals(ret.roles.RoleEnum[0], "MEMBER") def test_return_invalid_data(self): try: self.client.service.return_invalid_data() raise Exception("must fail") except: pass def test_custom_messages(self): ret = self.client.service.custom_messages("test") assert ret == 'test' def test_echo_simple_bare(self): ret = self.client.service.echo_simple_bare("test") assert ret == 'test' def test_echo_complex_bare(self): val = ['abc','def'] ret = self.client.service.echo_complex_bare(val) assert ret == val