def test_soap_input_header_order(self): """ Tests supports for input headers whose elements are provided in different order than that defined in rpc declaration _in_header parameter. """ server = ServerBase(self.app) initial_ctx = MethodContext(server, MethodContext.SERVER) initial_ctx.in_string = [ '<senv:Envelope xmlns:tns="tns" ' 'xmlns:wsa="http://www.w3.org/2005/08/addressing" ' 'xmlns:senv="http://schemas.xmlsoap.org/soap/envelope/">' '<senv:Header>' '<wsa:MessageID>SomeMessageID</wsa:MessageID>' '<wsa:RelatesTo>SomeRelatesToID</wsa:RelatesTo>' '<wsa:Action>/SomeAction</wsa:Action>' '</senv:Header>' '<senv:Body>' '<tns:someRequest>' '<tns:status>OK</tns:status>' '</tns:someRequest>' '</senv:Body>' '</senv:Envelope>' ] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) self.assertEquals(ctx.in_header[0], '/SomeAction') self.assertEquals(ctx.in_header[1], 'SomeMessageID') self.assertEquals(ctx.in_header[2], 'SomeRelatesToID')
def test_soap_input_header(self): server = ServerBase(self.app) initial_ctx = MethodContext(server, MethodContext.SERVER) initial_ctx.in_string = [ '<senv:Envelope xmlns:tns="tns" ' 'xmlns:wsa="http://www.w3.org/2005/08/addressing" ' 'xmlns:senv="http://schemas.xmlsoap.org/soap/envelope/">' '<senv:Header>' '<wsa:Action>/SomeAction</wsa:Action>' '<wsa:MessageID>SomeMessageID</wsa:MessageID>' '<wsa:RelatesTo>SomeRelatesToID</wsa:RelatesTo>' '</senv:Header>' '<senv:Body>' '<tns:someRequest>' '<tns:status>OK</tns:status>' '</tns:someRequest>' '</senv:Body>' '</senv:Envelope>' ] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) self.assertEquals(ctx.in_header[0], '/SomeAction') self.assertEquals(ctx.in_header[1], 'SomeMessageID') self.assertEquals(ctx.in_header[2], 'SomeRelatesToID')
def test_soap_input_header(self): server = ServerBase(self.app) initial_ctx = MethodContext(server) initial_ctx.in_string = [ '<senv:Envelope xmlns:tns="tns"' 'xmlns:wsa="http://www.w3.org/2005/08/addressing"' 'xmlns:senv="http://schemas.xmlsoap.org/soap/envelope/">' '<senv:Header>' '<wsa:Action>/SomeAction</wsa:Action>' '<wsa:MessageID>SomeMessageID</wsa:MessageID>' '<wsa:RelatesTo>SomeRelatesToID</wsa:RelatesTo>' '</senv:Header>' '<senv:Body>' '<tns:someRequest>' '<tns:status>OK</tns:status>' '</tns:someRequest>' '</senv:Body>' '</senv:Envelope>' ] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) self.assertEquals(ctx.in_header[0], '/SomeAction') self.assertEquals(ctx.in_header[1], 'SomeMessageID') self.assertEquals(ctx.in_header[2], 'SomeRelatesToID')
def test_soap_input_header_order_and_missing(self): """ Test that header ordering logic also works when an input header element is missing. Confirm that it returns None for the missing parameter. """ server = ServerBase(self.app) initial_ctx = MethodContext(server, MethodContext.SERVER) initial_ctx.in_string = [ '<senv:Envelope xmlns:tns="tns" ' 'xmlns:wsa="http://www.w3.org/2005/08/addressing" ' 'xmlns:senv="http://schemas.xmlsoap.org/soap/envelope/">' '<senv:Header>' '<wsa:MessageID>SomeMessageID</wsa:MessageID>' '<wsa:Action>/SomeAction</wsa:Action>' '</senv:Header>' '<senv:Body>' '<tns:someRequest>' '<tns:status>OK</tns:status>' '</tns:someRequest>' '</senv:Body>' '</senv:Envelope>' ] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) self.assertEquals(ctx.in_header[0], '/SomeAction') self.assertEquals(ctx.in_header[1], 'SomeMessageID') self.assertEquals(ctx.in_header[2], None)
def test_basic(self): class SomeService(ServiceBase): @srpc(String(pattern='a')) def some_method(s): pass application = Application([SomeService], in_protocol=Soap11(validator='soft'), out_protocol=Soap11(), name='Service', tns='tns', ) server = ServerBase(application) ctx = MethodContext(server) ctx.in_string = [u""" <SOAP-ENV:Envelope xmlns:ns0="tns" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Body> <ns0:some_method> <ns0:s>OK</ns0:s> </ns0:some_method> </SOAP-ENV:Body> </SOAP-ENV:Envelope> """] ctx, = server.generate_contexts(ctx) server.get_in_object(ctx) self.assertEquals(isinstance(ctx.in_error, ValidationError), True)
def test_soap_input_header_order_and_missing(self): """ Test that header ordering logic also works when an input header element is missing. Confirm that it returns None for the missing parameter. """ server = ServerBase(self.app) initial_ctx = MethodContext(server) initial_ctx.in_string = [ '<senv:Envelope xmlns:tns="tns"' 'xmlns:wsa="http://www.w3.org/2005/08/addressing"' 'xmlns:senv="http://schemas.xmlsoap.org/soap/envelope/">' '<senv:Header>' '<wsa:MessageID>SomeMessageID</wsa:MessageID>' '<wsa:Action>/SomeAction</wsa:Action>' '</senv:Header>' '<senv:Body>' '<tns:someRequest>' '<tns:status>OK</tns:status>' '</tns:someRequest>' '</senv:Body>' '</senv:Envelope>' ] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) self.assertEquals(ctx.in_header[0], '/SomeAction') self.assertEquals(ctx.in_header[1], 'SomeMessageID') self.assertEquals(ctx.in_header[2], None)
def test_soap_input_header_order(self): """ Tests supports for input headers whose elements are provided in different order than that defined in rpc declaration _in_header parameter. """ server = ServerBase(self.app) initial_ctx = MethodContext(server) initial_ctx.in_string = [ '<senv:Envelope xmlns:tns="tns"' 'xmlns:wsa="http://www.w3.org/2005/08/addressing"' 'xmlns:senv="http://schemas.xmlsoap.org/soap/envelope/">' '<senv:Header>' '<wsa:MessageID>SomeMessageID</wsa:MessageID>' '<wsa:RelatesTo>SomeRelatesToID</wsa:RelatesTo>' '<wsa:Action>/SomeAction</wsa:Action>' '</senv:Header>' '<senv:Body>' '<tns:someRequest>' '<tns:status>OK</tns:status>' '</tns:someRequest>' '</senv:Body>' '</senv:Envelope>' ] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) self.assertEquals(ctx.in_header[0], '/SomeAction') self.assertEquals(ctx.in_header[1], 'SomeMessageID') self.assertEquals(ctx.in_header[2], 'SomeRelatesToID')
def test_basic(self): class SomeService(ServiceBase): @srpc(String(pattern='a')) def some_method(s): pass application = Application( [SomeService], in_protocol=Soap11(validator='soft'), out_protocol=Soap11(), name='Service', tns='tns', ) server = ServerBase(application) ctx = MethodContext(server) ctx.in_string = [ u""" <SOAP-ENV:Envelope xmlns:ns0="tns" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/"> <SOAP-ENV:Body> <ns0:some_method> <ns0:s>OK</ns0:s> </ns0:some_method> </SOAP-ENV:Body> </SOAP-ENV:Envelope> """ ] ctx, = server.generate_contexts(ctx) server.get_in_object(ctx) self.assertEquals(isinstance(ctx.in_error, ValidationError), True)
def __init__(self, app, app_url, wsdl_url=None): ServerBase.__init__(self, app) self.app_url = app_url self.wsdl_url = wsdl_url self.zmq_socket = context.socket(zmq.REP) self.zmq_socket.bind(app_url)
def __init__(self, app, chunked=False, max_content_length=2 * 1024 * 1024, block_length=8 * 1024): ServerBase.__init__(self, app) self.chunked = chunked self.max_content_length = max_content_length self.block_length = block_length
def __init__(self, db, app, consumer_id): ServerBase.__init__(self, app) self.session = sessionmaker(bind=db)() self.id = consumer_id if self.session.query(WorkerStatus).get(self.id) is None: self.session.add(WorkerStatus(worker_id=self.id)) self.session.commit()
def __init__(self, app, chunked=False, max_content_length=2 * 1024 * 1024, block_length=8 * 1024): ServerBase.__init__(self, app) self._allowed_http_verbs = app.in_protocol.allowed_http_verbs self.chunked = chunked self.max_content_length = max_content_length self.block_length = block_length
def test_decimal(self): d = decimal.Decimal('1e100') class SomeService(ServiceBase): @srpc(Decimal(120,4), _returns=Decimal) def some_call(p): print(p) print(type(p)) assert type(p) == decimal.Decimal assert d == p return p app = Application([SomeService], "tns", in_protocol=XmlDocument(), out_protocol=XmlDocument()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = ['<some_call xmlns="tns"><p>%s</p></some_call>' % d] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) elt = etree.fromstring(''.join(ctx.out_string)) print(etree.tostring(elt, pretty_print=True)) target = elt.xpath('//tns:some_callResult/text()', namespaces=app.interface.nsmap)[0] assert target == str(d)
def _dry_me(services, d, ignore_wrappers=False, complex_as=dict, just_ctx=False, just_in_object=False, validator=None, polymorphic=False): app = Application( services, 'tns', in_protocol=_DictDocumentChild( ignore_wrappers=ignore_wrappers, complex_as=complex_as, polymorphic=polymorphic, validator=validator, ), out_protocol=_DictDocumentChild(ignore_wrappers=ignore_wrappers, complex_as=complex_as, polymorphic=polymorphic), ) server = ServerBase(app) initial_ctx = MethodContext(server, MethodContext.SERVER) initial_ctx.in_string = [serializer.dumps(d, **dumps_kwargs)] ctx, = server.generate_contexts(initial_ctx) if not just_ctx: server.get_in_object(ctx) if not just_in_object: server.get_out_object(ctx) server.get_out_string(ctx) return ctx
def test_generate_empty_http(self): """ Test that empty HTTP message is generated when setting output message name to 'EmptyHttp' """ cpe_string = b'' server = ServerBase(self.app) ctx = MethodContext(server, MethodContext.SERVER) ctx.in_string = [cpe_string] ctx, = server.generate_contexts(ctx) server.get_in_object(ctx) if ctx.in_error is not None: raise ctx.in_error server.get_out_object(ctx) if ctx.out_error is not None: raise ctx.out_error ctx.descriptor.out_message.Attributes.sub_name = 'EmptyHttp' ctx.out_object = [models.AcsToCpeRequests()] server.get_out_string(ctx) self.assertEqual(b''.join(ctx.out_string), b'')
def test_attribute_ns(self): class a(ComplexModel): b = Unicode c = XmlAttribute(Unicode, ns="spam", attribute_of="b") class SomeService(ServiceBase): @srpc(_returns=a) def some_call(): return a(b="foo",c="bar") app = Application([SomeService], "tns", in_protocol=XmlDocument(), out_protocol=XmlDocument()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = ['<some_call xmlns="tns"/>'] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) elt = etree.fromstring(''.join(ctx.out_string)) target = elt.xpath('//s0:b', namespaces=app.interface.nsmap)[0] print(etree.tostring(elt, pretty_print=True)) assert target.attrib['{%s}c' % app.interface.nsmap["s1"]] == "bar"
def test_acs_manager_exception(self): """ Test that an unexpected exception from the ACS SM manager will result in an empty response. """ self.enb_acs_manager.handle_tr069_message = mock.MagicMock( side_effect=Exception('mock exception') ) # stop the patcher because we want to use the above MagicMock self.p.stop() server = ServerBase(self.app) ctx = MethodContext(server, MethodContext.SERVER) ctx.in_string = [b''] ctx, = server.generate_contexts(ctx) server.get_in_object(ctx) self.assertIsNone(ctx.in_error) server.get_out_object(ctx) self.assertIsNone(ctx.out_error) server.get_out_string(ctx) self.assertEqual(b''.join(ctx.out_string), b'') # start the patcher otherwise the p.stop() in tearDown will complain self.p.start()
def __init__(self, db, app, consumer_id): ServerBase.__init__(self, app) self.session = sessionmaker(bind=db)() self.id = consumer_id worker_status = self.session.query(WorkerStatus).filter_by(worker_id=self.id).first() if worker_status is None: self.session.add(WorkerStatus(worker_id=self.id, task_id=0)) self.session.commit()
def __init__(self, db, app, consumer_id): ServerBase.__init__(self, app) self.session = sessionmaker(bind=db)() self.id = consumer_id try: self.session.query(WorkerStatus) \ .filter_by(worker_id=self.id).one() except NoResultFound: self.session.add(WorkerStatus(worker_id=self.id, task_id=0)) self.session.commit()
def deserialize_request_string(string, app): """Deserialize request string using in_protocol in application definition. Returns the corresponding native python object. """ server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = [string] ctx = server.generate_contexts(initial_ctx)[0] server.get_in_object(ctx) return ctx.in_object
def test_invalid_input(self): class SomeService(ServiceBase): @srpc() def yay(): pass app = Application([SomeService], 'tns', JsonObject(), JsonObject(), Wsdl11()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = ['{"some_call": {"yay": ]}}'] ctx, = server.generate_contexts(initial_ctx) assert ctx.in_error.faultcode == 'Client.JsonDecodeError'
def __init__(self, db, app, consumer_id): ServerBase.__init__(self, app) self.session = sessionmaker(bind=db)() self.id = consumer_id worker_status = self.session.query(WorkerStatus) \ .filter_by(worker_id=self.id).first() if worker_status is None: self.session.add(WorkerStatus(worker_id=self.id, task_id=0)) self.session.commit()
def _dry_me(services, d, ignore_wrappers=False, complex_as=dict, just_ctx=False, just_in_object=False, validator=None, polymorphic=False): app = Application(services, 'tns', in_protocol=_DictDocumentChild( ignore_wrappers=ignore_wrappers, complex_as=complex_as, polymorphic=polymorphic, validator=validator, ), out_protocol=_DictDocumentChild( ignore_wrappers=ignore_wrappers, complex_as=complex_as, polymorphic=polymorphic), ) server = ServerBase(app) initial_ctx = MethodContext(server, MethodContext.SERVER) in_string = serializer.dumps(d, **dumps_kwargs) if not isinstance(in_string, bytes): in_string = in_string.encode('utf8') initial_ctx.in_string = [in_string] ctx, = server.generate_contexts(initial_ctx, in_string_charset='utf8') if not just_ctx: server.get_in_object(ctx) if not just_in_object: server.get_out_object(ctx) server.get_out_string(ctx) return ctx
def test_primitive_only(self): class SomeComplexModel(ComplexModel): i = Integer s = String class SomeService(ServiceBase): @srpc(SomeComplexModel, _returns=SomeComplexModel) def some_call(scm): return SomeComplexModel(i=5, s='5x') app = Application([SomeService], 'tns', in_protocol=_DictObjectChild(), out_protocol=_DictObjectChild()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = [serializer.dumps({"some_call":[]})] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) assert list(ctx.out_string) == [serializer.dumps( {"some_callResponse": {"some_callResult": {"i": 5, "s": "5x"}}})]
def test_complex(self): class CM(ComplexModel): i = Integer s = String class CCM(ComplexModel): c = CM i = Integer s = String class SomeService(ServiceBase): @srpc(CCM, _returns=CCM) def some_call(ccm): return CCM(c=ccm.c, i=ccm.i, s=ccm.s) app = Application([SomeService], 'tns', in_protocol=_DictObjectChild(), out_protocol=_DictObjectChild()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = [serializer.dumps({"some_call":{"ccm": {"c":{"i":3, "s": "3x"}, "i":4, "s": "4x"}}})] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) ret = serializer.loads(''.join(ctx.out_string)) print(ret) assert ret['some_callResponse']['some_callResult']['i'] == 4 assert ret['some_callResponse']['some_callResult']['s'] == '4x' assert ret['some_callResponse']['some_callResult']['c']['i'] == 3 assert ret['some_callResponse']['some_callResult']['c']['s'] == '3x'
def test_invalid_input(self): class SomeService(ServiceBase): pass app = Application([SomeService], 'tns', in_protocol=JsonDocument(), out_protocol=JsonDocument()) server = ServerBase(app) initial_ctx = MethodContext(server, MethodContext.SERVER) initial_ctx.in_string = [b'{'] ctx, = server.generate_contexts(initial_ctx, in_string_charset='utf8') assert ctx.in_error.faultcode == 'Client.JsonDecodeError'
def test_invalid_input(self): class SomeService(ServiceBase): @srpc() def yay(): pass app = Application([SomeService], "tns", in_protocol=JsonDocument(), out_protocol=JsonDocument()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = ["{"] ctx, = server.generate_contexts(initial_ctx) assert ctx.in_error.faultcode == "Client.JsonDecodeError"
def test_xml_data(self): class C(ComplexModel): a = XmlData(Unicode) b = XmlAttribute(Unicode) class SomeService(ServiceBase): @srpc(C, _returns=C) def some_call(c): assert c.a == "a" assert c.b == "b" return c app = Application( [SomeService], "tns", name="test_xml_data", in_protocol=XmlDocument(), out_protocol=XmlDocument() ) server = ServerBase(app) initial_ctx = MethodContext(server, MethodContext.SERVER) initial_ctx.in_string = [b'<some_call xmlns="tns">' b'<c b="b">a</c>' b"</some_call>"] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) print(ctx.out_string) pprint(app.interface.nsmap) ret = etree.fromstring(b"".join(ctx.out_string)).xpath( "//tns:some_call" + RESULT_SUFFIX, namespaces=app.interface.nsmap )[0] print(etree.tostring(ret, pretty_print=True)) assert ret.text == "a" assert ret.attrib["b"] == "b"
def test_invalid_request(self): class SomeService(ServiceBase): @srpc(Integer, String, DateTime) def yay(i,s,d): print(i,s,d) pass app = Application([SomeService], 'tns', JsonObject(validator='soft'), JsonObject(), Wsdl11()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = ['{"some_call": {"yay": []}}'] ctx, = server.generate_contexts(initial_ctx) print(ctx.in_error) assert ctx.in_error.faultcode == 'Client.ResourceNotFound' print()
def test_invalid_input(self): class SomeService(ServiceBase): @srpc() def yay(): pass app = Application([SomeService], 'tns', in_protocol=_DictObjectChild(), out_protocol=_DictObjectChild()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = ['{"some_call": {"yay": ]}}'] ctx, = server.generate_contexts(initial_ctx) assert ctx.in_error.faultcode == decode_error
def test_mandatory_element_attributes(self): class C(ComplexModel): bar = XmlAttribute(M(Unicode)) class SomeService(ServiceBase): @srpc(C.customize(min_occurs=1), _returns=Unicode) def some_call(c): assert c is not None assert hasattr(c, 'foo') assert c.foo == 'hello' return c.foo app = Application( [SomeService], "tns", name="test_mandatory_element_attributes", in_protocol=XmlDocument(validator='lxml'), out_protocol=XmlDocument()) server = ServerBase(app) ctx = self._get_ctx(server, [ '<some_call xmlns="tns">' # no mandatory elements at all... '</some_call>' ]) self.assertRaises(SchemaValidationError, server.get_out_object, ctx) ctx = self._get_ctx(server, [ '<some_call xmlns="tns">' '<c>' # no mandatory elements here... '</c>' '</some_call>' ]) self.assertRaises(SchemaValidationError, server.get_out_object, ctx)
def test_invalid_input(self): class SomeService(ServiceBase): @srpc() def yay(): pass app = Application([SomeService], 'tns', in_protocol=MessagePackDocument(), out_protocol=MessagePackDocument()) server = ServerBase(app) initial_ctx = MethodContext(server, MethodContext.SERVER) initial_ctx.in_string = ['\xdf'] # Invalid input ctx, = server.generate_contexts(initial_ctx) assert ctx.in_error.faultcode == 'Client.MessagePackDecodeError'
def __init__(self, app, bookkeep=False, _clients=None): self.app = app self.transport = ServerBase(app) self.bookkeep = bookkeep self._clients = _clients if _clients is None: self._clients = {}
def test_invalid_input(self): class SomeService(Service): @srpc() def yay(): pass app = Application([SomeService], 'tns', in_protocol=MessagePackDocument(), out_protocol=MessagePackDocument()) server = ServerBase(app) initial_ctx = MethodContext(server, MethodContext.SERVER) initial_ctx.in_string = [b'\xdf'] # Invalid input ctx, = server.generate_contexts(initial_ctx) assert ctx.in_error.faultcode == 'Client.MessagePackDecodeError'
def test_invalid_number(self): class SomeService(ServiceBase): @srpc(Integer, String, DateTime) def yay(i,s,d): print(i,s,d) pass app = Application([SomeService], 'tns', JsonObject(validator='soft'), JsonObject(), Wsdl11()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = ['{"yay": ["s", "B"]}'] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) assert ctx.in_error.faultcode == 'Client.ValidationError'
def test_invalid_input(self): class SomeService(ServiceBase): @srpc() def yay(): pass app = Application([SomeService], 'tns', in_protocol=YamlDocument(), out_protocol=YamlDocument()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = ['{'] ctx, = server.generate_contexts(initial_ctx) assert ctx.in_error.faultcode == 'Client.YamlDecodeError'
def test_invalid_string(self): class SomeService(ServiceBase): @srpc(Integer, String, DateTime) def yay(i,s,d): print(i,s,d) pass app = Application([SomeService], 'tns', in_protocol=_DictObjectChild(validator='soft'), out_protocol=_DictObjectChild()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = [serializer.dumps({"yay": {"s": 1}})] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) assert ctx.in_error.faultcode == 'Client.ValidationError'
def test_parse_empty_http(self): """ Test that empty HTTP message gets correctly mapped to 'EmptyHttp' function call """ cpe_string = b'' server = ServerBase(self.app) ctx = MethodContext(server, MethodContext.SERVER) ctx.in_string = [cpe_string] ctx, = server.generate_contexts(ctx) if ctx.in_error is not None: print('In error: %s' % ctx.in_error) self.assertEqual(ctx.in_error, None) self.assertEqual(ctx.function, AutoConfigServer.empty_http)
def reinitialize(self): from spyne.server import ServerBase server = ServerBase(self) aux_memo = set() for s, d in self.interface.method_id_map.values(): if d.aux is not None and not id(d.aux) in aux_memo: d.aux.initialize(server) aux_memo.add(id(d.aux))
def test_missing_value(self): class SomeService(ServiceBase): @srpc(Integer, String, Mandatory.DateTime) def yay(i,s,d): print(i,s,d) pass app = Application([SomeService], 'tns', JsonObject(validator='soft'), JsonObject(), Wsdl11()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = ['{"yay": [1, "B"]}'] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) print(ctx.in_error.faultstring) assert ctx.in_error.faultcode == 'Client.ValidationError' assert ctx.in_error.faultstring.endswith("frequency constraints.")
def test_parse_fault_response(self): """ Tests that a fault response from CPE is correctly parsed. """ # Example CPE->ACS fault response. Copied from: # http://djuro82.blogspot.com/2011/05/tr-069-cpe-provisioning.html cpe_string = b''' <soapenv:Envelope soapenv:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:soap="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:cwmp="urn:dslforum-org:cwmp-1-0"> <soapenv:Header> <cwmp:ID soapenv:mustUnderstand="1">1031422463</cwmp:ID> </soapenv:Header> <soapenv:Body> <soapenv:Fault> <faultcode>Client</faultcode> <faultstring>CWMP fault</faultstring> <detail> <cwmp:Fault> <FaultCode>9003</FaultCode> <FaultString>Invalid arguments</FaultString> <SetParameterValuesFault> <ParameterName>InternetGatewayDevice.WANDevice.1.WANConnectionDevice.3.WANPPPConnection.1.Password</ParameterName> <FaultCode>9003</FaultCode> <FaultString>Invalid arguments</FaultString> </SetParameterValuesFault> <SetParameterValuesFault> <ParameterName>InternetGatewayDevice.WANDevice.1.WANConnectionDevice.3.WANPPPConnection.1.Username</ParameterName> <FaultCode>9003</FaultCode> <FaultString>Invalid arguments</FaultString> </SetParameterValuesFault> </cwmp:Fault> </detail> </soapenv:Fault> </soapenv:Body> </soapenv:Envelope> ''' server = ServerBase(self.app) ctx = MethodContext(server, MethodContext.SERVER) ctx.in_string = [cpe_string] ctx, = server.generate_contexts(ctx) server.get_in_object(ctx) if ctx.in_error is not None: raise ctx.in_error # Calls function to receive and process message server.get_out_object(ctx) output_msg = ctx.out_object[0] self.assertEqual(type(output_msg), models.Fault) self.assertEqual(output_msg.FaultCode, 9003) self.assertEqual(output_msg.FaultString, 'Invalid arguments') self.assertEqual( output_msg.SetParameterValuesFault[1].ParameterName, 'InternetGatewayDevice.WANDevice.1.WANConnectionDevice.3.WANPPPConnection.1.Username', ) self.assertEqual(output_msg.SetParameterValuesFault[1].FaultCode, 9003) self.assertEqual( output_msg.SetParameterValuesFault[1].FaultString, 'Invalid arguments', )
def test_invalid_request(self): class SomeService(ServiceBase): @srpc(Integer, String, DateTime) def yay(i,s,d): print(i,s,d) pass app = Application([SomeService], 'tns', in_protocol=_DictDocumentChild(validator='soft'), out_protocol=_DictDocumentChild()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = [serializer.dumps({"some_call": {"yay": []}})] ctx, = server.generate_contexts(initial_ctx) print(ctx.in_error) assert ctx.in_error.faultcode == 'Client.ResourceNotFound' print()
def test_attribute_of_multi(self): class C(ComplexModel): e = Unicode(max_occurs='unbounded') a = XmlAttribute(Unicode, attribute_of="e") class SomeService(ServiceBase): @srpc(C, _returns=C) def some_call(c): assert c.e == ['e0', 'e1'] assert c.a == ['a0', 'a1'] return c app = Application([SomeService], "tns", name="test_attribute_of", in_protocol=XmlDocument(), out_protocol=XmlDocument()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.method_request_string = '{test_attribute_of}some_call' initial_ctx.in_string = [ '<some_call xmlns="tns">' '<c>' '<e a="a0">e0</e>' '<e a="a1">e1</e>' '</c>' '</some_call>' ] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) ret = etree.fromstring(''.join(ctx.out_string)).xpath( '//s0:e', namespaces=app.interface.nsmap) print(etree.tostring(ret[0], pretty_print=True)) print(etree.tostring(ret[1], pretty_print=True)) assert ret[0].text == "e0" assert ret[0].attrib['a'] == "a0" assert ret[1].text == "e1" assert ret[1].attrib['a'] == "a1"
def test_mandatory_elements(self): class SomeService(ServiceBase): @srpc(M(Unicode), _returns=Unicode) def some_call(s): assert s == 'hello' return s app = Application([SomeService], "tns", name="test_mandatory_elements", in_protocol=XmlDocument(validator='lxml'), out_protocol=XmlDocument()) server = ServerBase(app) # Valid call with all mandatory elements in ctx = self._get_ctx(server, [ '<some_call xmlns="tns">' '<s>hello</s>' '</some_call>' ]) server.get_out_object(ctx) server.get_out_string(ctx) ret = etree.fromstring(''.join(ctx.out_string)).xpath( '//tns:some_call%s/text()' % RESULT_SUFFIX, namespaces=app.interface.nsmap)[0] assert ret == 'hello' # Invalid call ctx = self._get_ctx(server, [ '<some_call xmlns="tns">' # no mandatory elements here... '</some_call>' ]) self.assertRaises(SchemaValidationError, server.get_out_object, ctx)
def test_multiple_dict_complex_array(self): class CM(ComplexModel): i = Integer s = String class CCM(ComplexModel): c = CM i = Integer s = String class ECM(CCM): d = DateTime class SomeService(ServiceBase): @srpc(Iterable(ECM), _returns=Iterable(ECM)) def some_call(ecm): return ecm app = Application([SomeService], 'tns', in_protocol=_DictObjectChild(), out_protocol=_DictObjectChild()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = [serializer.dumps( {"some_call": {"ecm": [{ "c": {"i":3, "s": "3x"}, "i":4, "s": "4x", "d": "2011-12-13T14:15:16Z" }] }})] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) print(ctx.in_object) server.get_out_string(ctx) ret = serializer.loads(''.join(ctx.out_string)) print(ret) assert ret['some_callResponse'] assert ret['some_callResponse']['some_callResult'] assert ret['some_callResponse']['some_callResult']['ECM'] assert ret['some_callResponse']['some_callResult']['ECM'][0] assert ret['some_callResponse']['some_callResult']['ECM'][0]["c"] assert ret['some_callResponse']['some_callResult']['ECM'][0]["c"]["i"] == 3 assert ret['some_callResponse']['some_callResult']['ECM'][0]["c"]["s"] == "3x" assert ret['some_callResponse']['some_callResult']['ECM'][0]["i"] == 4 assert ret['some_callResponse']['some_callResult']['ECM'][0]["s"] == "4x" assert ret['some_callResponse']['some_callResult']['ECM'][0]["d"] == "2011-12-13T14:15:16+00:00"
def test_attribute_of(self): class C(ComplexModel): a = Unicode b = XmlAttribute(Unicode, attribute_of="a") class SomeService(ServiceBase): @srpc(C, _returns=C) def some_call(c): assert c.a == 'a' assert c.b == 'b' return c app = Application([SomeService], "tns", name="test_attribute_of", in_protocol=XmlDocument(), out_protocol=XmlDocument()) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = [ '<some_call xmlns="tns">' '<c>' '<a b="b">a</a>' '</c>' '</some_call>' ] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) ret = ''.join(ctx.out_string) print(ret) ret = etree.fromstring(ret) ret = ret.xpath('//s0:a', namespaces=app.interface.nsmap)[0] print(etree.tostring(ret, pretty_print=True)) assert ret.text == "a" assert ret.attrib['b'] == "b"
def test_parse_inform(self): cpe_string = b'''<?xml version="1.0" encoding="UTF-8"?> <SOAP-ENV:Envelope xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/" xmlns:SOAP-ENC="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:cwmp="urn:dslforum-org:cwmp-1-0"> <SOAP-ENV:Header> <cwmp:ID SOAP-ENV:mustUnderstand="1">CPE_1002</cwmp:ID> </SOAP-ENV:Header> <SOAP-ENV:Body SOAP-ENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/"> <cwmp:Inform> <Event xsi:type="SOAP-ENC:Array" SOAP-ENC:arrayType="cwmp:EventStruct[1]"> <EventStruct> <EventCode>0 BOOTSTRAP</EventCode> <CommandKey></CommandKey> </EventStruct> </Event> <MaxEnvelopes>1</MaxEnvelopes> <CurrentTime>1970-01-02T00:01:05.021239+00:00</CurrentTime> <RetryCount>2</RetryCount> </cwmp:Inform> </SOAP-ENV:Body> </SOAP-ENV:Envelope> ''' server = ServerBase(self.app) ctx = MethodContext(server, MethodContext.SERVER) ctx.in_string = [cpe_string] ctx, = server.generate_contexts(ctx) if ctx.in_error is not None: print('In error: %s' % ctx.in_error) self.assertEqual(ctx.in_error, None) server.get_in_object(ctx) self.assertEqual(ctx.in_object.Event.EventStruct[0].EventCode, '0 BOOTSTRAP')
def test_xml_data(self): class C(ComplexModel): a = XmlData(Unicode) b = XmlAttribute(Unicode) class SomeService(ServiceBase): @srpc(C, _returns=C) def some_call(c): assert c.a == 'a' assert c.b == 'b' return c app = Application([SomeService], "tns", name="test_xml_data", in_protocol=XmlDocument(), out_protocol=XmlDocument()) server = ServerBase(app) initial_ctx = MethodContext(server, MethodContext.SERVER) initial_ctx.in_string = [ b'<some_call xmlns="tns">' b'<c b="b">a</c>' b'</some_call>' ] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) print(ctx.out_string) pprint(app.interface.nsmap) ret = etree.fromstring(b''.join( ctx.out_string)).xpath('//tns:some_call' + RESULT_SUFFIX, namespaces=app.interface.nsmap)[0] print(etree.tostring(ret, pretty_print=True)) assert ret.text == "a" assert ret.attrib['b'] == "b"
def test_fault_to_dict(self): class SomeService(ServiceBase): @srpc(_returns=String) def some_call(): raise Fault() app = Application([SomeService], 'tns', in_protocol=_DictObjectChild(), out_protocol=_DictObjectChild(skip_depth=2)) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = serializer.dumps({"some_call":[]}) ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx)
def _dry_me(services, d, skip_depth=0, just_ctx=False, just_in_object=False, validator=None): app = Application( services, 'tns', in_protocol=_DictDocumentChild(validator=validator), out_protocol=_DictDocumentChild(skip_depth=skip_depth)) server = ServerBase(app) initial_ctx = MethodContext(server) initial_ctx.in_string = [serializer.dumps(d)] ctx, = server.generate_contexts(initial_ctx) if not just_ctx: server.get_in_object(ctx) if not just_in_object: server.get_out_object(ctx) server.get_out_string(ctx) return ctx
def test_multiple_attribute_of_multiple_rpc(self): """ Tests the following: 1. Support for multiple attributes on a single element. 2. Correctness of attribute definition -- extension applied to correct 'attribute_of' element. 3. Another class/rpc with same element/attribute name works correctly. """ class CMA(ComplexModel): a = Unicode ab = XmlAttribute(Unicode, attribute_of="a") ac = XmlAttribute(Unicode, attribute_of="a") ad = XmlAttribute(Integer, attribute_of="a") b = Integer bb = XmlAttribute(Unicode, attribute_of="b") class CMB(ComplexModel): b = Integer bb = XmlAttribute(Unicode, attribute_of="b") class SomeService(ServiceBase): @srpc(CMA, _returns=CMA) def some_call(cma): assert cma.a == 'a' assert cma.ab == 'b' assert cma.ac == 'c' assert cma.ad == 5 assert cma.b == 9 assert cma.bb == "attrib bb" return cma @srpc(CMB, _returns=CMB) def another_call(cmb): assert cmb.b == 9 assert cmb.bb == 'attrib bb' return cmb app = Application([SomeService], "tns", name="test_multiple_attribute_of", in_protocol=XmlDocument(), out_protocol=XmlDocument()) server = ServerBase(app) # test some_call(CMA) initial_ctx = MethodContext(server) initial_ctx.in_string = [ '<some_call xmlns="tns">' '<cma>' '<a ab="b" ac="c" ad="5">a</a>' '<b bb="attrib bb">9</b>' '</cma>' '</some_call>' ] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) ret = ''.join(ctx.out_string) print(ret) ret = etree.fromstring(ret) ret = ret.xpath('//s0:a', namespaces=app.interface.nsmap)[0] print(etree.tostring(ret, pretty_print=True)) assert ret.text == "a" assert ret.attrib['ab'] == "b" assert ret.attrib['ac'] == "c" assert int(ret.attrib['ad']) == 5 ret = ret.xpath('//s0:b', namespaces=app.interface.nsmap)[0] print(etree.tostring(ret, pretty_print=True)) assert ret.text == "9" assert ret.attrib['bb'] == "attrib bb" # test another_call(CMB) initial_ctx = MethodContext(server) initial_ctx.in_string = [ '<another_call xmlns="tns">' '<cmb>' '<b bb="attrib bb">9</b>' '</cmb>' '</another_call>' ] ctx, = server.generate_contexts(initial_ctx) server.get_in_object(ctx) server.get_out_object(ctx) server.get_out_string(ctx) ret = ''.join(ctx.out_string) print(ret) ret = etree.fromstring(ret) ret = ret.xpath('//s0:b', namespaces=app.interface.nsmap)[0] print(etree.tostring(ret, pretty_print=True)) assert ret.text == "9" assert ret.attrib['bb'] == "attrib bb"