def test_wrapped_array(self): parent = etree.Element('parent') val = ['a', 'b'] cls = Array(Unicode, namespace='tns') XmlDocument().to_parent(None, cls, val, parent, 'tns') print(etree.tostring(parent, pretty_print=True)) xpath = parent.xpath('//x:stringArray/x:string/text()', namespaces={'x': 'tns'}) assert xpath == val
def test_duration_positive_milliseconds_only(self): answer = 'PT0.666000S' gg = SomeBlob() gg.howlong = timedelta(milliseconds=666) element = etree.Element('test') XmlDocument().to_parent(None, SomeBlob, gg, element, gg.get_namespace()) element = element[0] print(gg.howlong) print(etree.tostring(element, pretty_print=True)) assert element[0].text == answer data = element.find('{%s}howlong' % gg.get_namespace()).text self.assertEquals(data, answer) s1 = XmlDocument().from_element(None, SomeBlob, element) assert total_seconds(s1.howlong) == total_seconds(gg.howlong)
def test_onehour_oneminute_onesecond(self): answer = 'PT1H1M1S' gg = SomeBlob() gg.howlong = timedelta(hours=1, minutes=1, seconds=1) element = etree.Element('test') XmlDocument().to_parent(None, SomeBlob, gg, element, gg.get_namespace()) element = element[0] print(gg.howlong) print(etree.tostring(element, pretty_print=True)) assert element[0].text == answer data = element.find('{%s}howlong' % gg.get_namespace()).text self.assertEquals(data, answer) s1 = XmlDocument().from_element(None, SomeBlob, element) assert total_seconds(s1.howlong) == total_seconds(gg.howlong)
def test_decimal_format(self): f = 123456 str_format = '${0}' element = etree.Element('test') XmlDocument().to_parent(None, Decimal(str_format=str_format), f, element, ns_test) element = element[0] self.assertEquals(element.text, '$123456')
def test_type_names(self): class Test(ComplexModel): any_xml = AnyXml any_dict = AnyDict unicode_ = Unicode any_uri = AnyUri decimal = Decimal double = Double float = Float integer = Integer unsigned = UnsignedInteger int64 = Integer64 int32 = Integer32 int16 = Integer16 int8 = Integer8 uint64 = UnsignedInteger64 uint32 = UnsignedInteger32 uint16 = UnsignedInteger16 uint8 = UnsignedInteger8 t = Time d = Date dt = DateTime dur = Duration bool = Boolean f = File b = ByteArray class Service(ServiceBase): @srpc(Test) def call(t): pass AnyXml.__type_name__ = 'oui' try: app.interface.build_interface_document() except: pass else: raise Exception("must fail.") AnyXml.__type_name__ = 'anyType' app = Application([Service], 'hey', in_protocol=XmlDocument(), out_protocol=XmlDocument()) XmlSchema(app.interface).build_interface_document()
def test_attribute_of_multi(self): class C(ComplexModel): a = Unicode(max_occurs='unbounded') b = XmlAttribute(Unicode, attribute_of="a") class SomeService(ServiceBase): @srpc(C, _returns=C) def some_call(c): assert c.a == ['a0', 'a1'] assert c.b == ['b0', 'b1'] 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="b0">a0</a>' '<a b="b1">a1</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 = etree.fromstring(''.join(ctx.out_string)).xpath( '//s0:a', namespaces=app.interface.nsmap) print etree.tostring(ret[0], pretty_print=True) print etree.tostring(ret[1], pretty_print=True) assert ret[0].text == "a0" assert ret[0].attrib['b'] == "b0" assert ret[1].text == "a1" assert ret[1].attrib['b'] == "b1"
def test_default(self): class SomeComplexModel(ComplexModel): _type_info = [ ('a', Unicode), ('b', Unicode(default='default')), ] obj = XmlDocument().from_element( None, SomeComplexModel, etree.fromstring(""" <hey> <a>string</a> </hey> """) ) # xml schema says it should be None assert obj.b == 'default' obj = XmlDocument().from_element( None, SomeComplexModel, etree.fromstring(""" <hey> <a>string</a> <b xsi:nil="true" xmlns:xsi="%s"/> </hey> """ % NS_XSI) ) # xml schema says it should be 'default' assert obj.b == 'default' obj = XmlDocument(replace_null_with_default=False).from_element( None, SomeComplexModel, etree.fromstring(""" <hey> <a>string</a> <b xsi:nil="true" xmlns:xsi="%s"/> </hey> """ % NS_XSI) ) # xml schema says it should be 'default' assert obj.b is None
def test_nested_class(self): # FIXME: this test is incomplete p = Person() element = etree.Element('test') XmlDocument().to_parent(None, Person, p, element, ns_test) element = element[0] self.assertEquals(None, p.name) self.assertEquals(None, p.birthdate) self.assertEquals(None, p.age) self.assertEquals(None, p.addresses)
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 start_a2bs(config): subconfig = config.services.getwrite( 'web', HttpListener( host='0.0.0.0', port=9271, disabled=False, _subapps=[ StaticFileServer(url='assets', path=abspath('assets'), list_contents=False) ], )) services = [ TestServices, CardReaderServices, CardWriterServices, SipBuddyReaderServices, SipBuddyWriterServices, ExtReaderServices, ExtWriterServices, ] subconfig.subapps['json'] = \ Application(services, tns='a2bs.web', name='A2BillingJson', in_protocol=HttpRpc(validator='soft'), out_protocol=JsonDocument(), config=config, ) subconfig.subapps['xml'] = \ Application(services, tns='a2bs.web', name='A2BillingXml', in_protocol=HttpRpc(validator='soft'), out_protocol=XmlDocument(), config=config, ) subconfig.subapps[''] = \ Application(services, tns='a2bs.web', name='A2BillingHtml', in_protocol=HttpRpc(validator='soft'), out_protocol=HtmlMicroFormat(), config=config, ) site = subconfig.gen_site() logger.info("listening for a2billing http endpoint %s:%d", subconfig.host, subconfig.port) return reactor.listenTCP(subconfig.port, site, interface=subconfig.host), None
def test_utcdatetime(self): datestring = '2007-05-15T13:40:44Z' e = etree.Element('test') e.text = datestring dt = XmlDocument().from_element(None, DateTime, e) self.assertEquals(dt.year, 2007) self.assertEquals(dt.month, 5) self.assertEquals(dt.day, 15) datestring = '2007-05-15T13:40:44.003Z' e = etree.Element('test') e.text = datestring dt = XmlDocument().from_element(None, DateTime, e) self.assertEquals(dt.year, 2007) self.assertEquals(dt.month, 5) self.assertEquals(dt.day, 15)
def test_to_parent_w_detail(self): from lxml.etree import Element element = Element('testing') detail = Element('something') fault = Fault(detail=detail) cls = Fault XmlDocument().to_parent(None, cls, fault, element, 'urn:ignored') (child,) = element.getchildren() self.assertTrue(child.find('detail').find('something') is detail)
def test_simple_array(self): class cls(ComplexModel): __namespace__ = 'tns' s = Unicode(max_occurs='unbounded') val = cls(s=['a', 'b']) parent = etree.Element('parent') XmlDocument().to_parent(None, cls, val, parent, 'tns') print(etree.tostring(parent, pretty_print=True)) xpath = parent.xpath('//x:cls/x:s/text()', namespaces={'x': 'tns'}) assert xpath == val.s
def get_xml_as_object(elt, cls): '''Returns a native :class:`spyne.model.complex.ComplexModel` child from an ElementTree representation of the same class. :param value: The class the xml document represents. :param value: The xml document to be deserialized. ''' xml_object = XmlDocument() return xml_object.from_element(cls, elt)
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_serialize_simple_array(self): t = SomeClass(days=[ DaysOfWeekEnum.Monday, DaysOfWeekEnum.Tuesday, DaysOfWeekEnum.Wednesday, DaysOfWeekEnum.Thursday, DaysOfWeekEnum.Friday, DaysOfWeekEnum.Saturday, DaysOfWeekEnum.Sunday, ]) SomeClass.resolve_namespace(SomeClass, 'tns') elt = etree.Element('test') XmlDocument().to_parent(None, SomeClass, t, elt, 'test_namespace') elt = elt[0] print((etree.tostring(elt, pretty_print=True))) ret = XmlDocument().from_element(None, SomeClass, elt) self.assertEqual(t.days, ret.days)
def initialize(services=(SomeService, )): logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) observer = log.PythonLoggingObserver('twisted') log.startLoggingWithObserver(observer.emit, setStdout=False) application = Application(services, 'spyne.examples.hello.twisted', in_protocol=HttpRpc(), out_protocol=XmlDocument()) return application
def main(): logging.basicConfig(level=logging.DEBUG) logging.getLogger('spyne.protocol.xml').setLevel(logging.DEBUG) services = (SomeService, SomeAuxService) application = Application(services, 'spyne.examples.auxproc', in_protocol=HttpRpc(), out_protocol=XmlDocument()) server = make_server(host, port, WsgiApplication(application)) logging.info("listening to http://%s:%d" % (host, port)) return server.serve_forever()
def test_method_exception(self): from spyne.protocol.xml import XmlDocument h = [0] def on_method_exception_object(ctx): assert ctx.out_error is not None from spyne.protocol.xml import SchemaValidationError assert isinstance(ctx.out_error, SchemaValidationError) logging.error(repr(ctx.out_error)) h[0] += 1 class SomeService(Service): @rpc(Unicode(5)) def some_call(ctx, some_str): print(some_str) app = Application([SomeService], "some_tns", in_protocol=XmlDocument(validator='lxml'), out_protocol=Soap11()) app.event_manager.add_listener( "method_exception_object", on_method_exception_object) # this shouldn't be called because: # 1. document isn't validated # 2. hence; document can't be parsed # 3. hence; document can't be mapped to a function # 4. hence; document can't be mapped to a service class # 5. hence; no handlers from the service class is invoked. # 6. hence; the h[0] == 1 check (instead of 2) SomeService.event_manager.add_listener( "method_exception_object", on_method_exception_object) wsgi_app = WsgiApplication(app) xml_request = b""" <tns:some_call xmlns:tns="some_tns"> <tns:some_str>123456</tns:some_str> </tns:some_call> """ _ = b''.join(wsgi_app({ 'PATH_INFO': '/', 'SERVER_NAME': 'localhost', 'SERVER_PORT': '7000', 'REQUEST_METHOD': 'POST', 'wsgi.url_scheme': 'http', 'wsgi.input': BytesIO(xml_request), }, start_response)) assert h[0] == 1
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, [ b'<some_call xmlns="tns">' # no mandatory elements at all... b'</some_call>' ]) self.assertRaises(SchemaValidationError, server.get_out_object, ctx) ctx = self._get_ctx( server, [ b'<some_call xmlns="tns">' b'<c>' # no mandatory elements here... b'</c>' b'</some_call>' ]) self.assertRaises(SchemaValidationError, server.get_out_object, ctx)
def test_serialize_complex_array(self): days = [ DaysOfWeekEnum.Monday, DaysOfWeekEnum.Tuesday, DaysOfWeekEnum.Wednesday, DaysOfWeekEnum.Thursday, DaysOfWeekEnum.Friday, DaysOfWeekEnum.Saturday, DaysOfWeekEnum.Sunday, ] days_xml = [ ('{tns}DaysOfWeekEnum', 'Monday'), ('{tns}DaysOfWeekEnum', 'Tuesday'), ('{tns}DaysOfWeekEnum', 'Wednesday'), ('{tns}DaysOfWeekEnum', 'Thursday'), ('{tns}DaysOfWeekEnum', 'Friday'), ('{tns}DaysOfWeekEnum', 'Saturday'), ('{tns}DaysOfWeekEnum', 'Sunday'), ] DaysOfWeekEnumArray = Array(DaysOfWeekEnum) DaysOfWeekEnumArray.__namespace__ = 'tns' elt = etree.Element('test') XmlDocument().to_parent(None, DaysOfWeekEnumArray, days, elt, 'test_namespace') elt = elt[0] ret = XmlDocument().from_element(None, Array(DaysOfWeekEnum), elt) assert days == ret print((etree.tostring(elt, pretty_print=True))) pprint(self.app.interface.nsmap) assert days_xml == [(e.tag, e.text) for e in elt.xpath( '//tns:DaysOfWeekEnum', namespaces=self.app.interface.nsmap)]
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] assert target.attrib['{%s}c' % app.interface.nsmap["s1"]] == "bar"
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, [b'<some_call xmlns="tns">' b'<s>hello</s>' b'</some_call>']) server.get_out_object(ctx) server.get_out_string(ctx) ret = etree.fromstring(b''.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, [ b'<some_call xmlns="tns">' # no mandatory elements here... b'</some_call>' ]) self.assertRaises(SchemaValidationError, server.get_out_object, ctx)
def test_call(self): queue = set() class MessageService(ServiceBase): @srpc(String, String) def send_message(s, k): queue.add((s,k)) application = Application([MessageService], 'some_tns', in_protocol=XmlDocument(), out_protocol=XmlDocument()) server = NullServer(application) queue.clear() server.service.send_message("zabaaa", k="hobaa") assert set([("zabaaa","hobaa")]) == queue queue.clear() server.service.send_message(k="hobaa") assert set([(None,"hobaa")]) == queue queue.clear() server.service.send_message("zobaaa", s="hobaa") assert set([("hobaa", None)]) == queue
def test_to_parent_element_wo_detail(self): from lxml.etree import Element import spyne.const.xml_ns ns_soap_env = spyne.const.xml_ns.soap_env element = Element('testing') fault = Fault() cls = Fault XmlDocument().to_parent_element(cls, fault, 'urn:ignored', element) (child,) = element.getchildren() self.assertEqual(child.tag, '{%s}Fault' % ns_soap_env) self.assertEqual(child.find('faultcode').text, 'senv:Server') self.assertEqual(child.find('faultstring').text, 'Fault') self.assertEqual(child.find('faultactor').text, '') self.failIf(child.findall('detail'))
def test_from_xml_w_detail(self): from lxml.etree import Element from lxml.etree import SubElement from spyne.const.xml import SOAP11_ENV element = Element(SOAP11_ENV('Fault')) fcode = SubElement(element, 'faultcode') fcode.text = 'soap11env:other' fstr = SubElement(element, 'faultstring') fstr.text = 'Testing' actor = SubElement(element, 'faultactor') actor.text = 'phreddy' detail = SubElement(element, 'detail') fault = XmlDocument().from_element(None, Fault, element) self.assertTrue(fault.detail is detail)
def simple_get_restriction_tag(document, cls): extends = _check_extension_attrs(cls) if extends is None: return simple_type = etree.Element(XSD('simpleType')) simple_type.set('name', cls.get_type_name()) document.add_simple_type(cls, simple_type) restriction = etree.SubElement(simple_type, XSD('restriction')) restriction.set('base', extends.get_type_name_ns(document.interface)) for v in cls.Attributes.values: enumeration = etree.SubElement(restriction, XSD('enumeration')) enumeration.set('value', XmlDocument().to_unicode(cls, v)) return restriction
def test_from_xml_w_detail(self): from lxml.etree import Element from lxml.etree import SubElement import spyne.const.xml_ns ns_soap_env = spyne.const.xml_ns.soap11_env element = Element('{%s}Fault' % ns_soap_env) fcode = SubElement(element, 'faultcode') fcode.text = 'soap11env:other' fstr = SubElement(element, 'faultstring') fstr.text = 'Testing' actor = SubElement(element, 'faultactor') actor.text = 'phreddy' detail = SubElement(element, 'detail') fault = XmlDocument().from_element(None, Fault, element) self.failUnless(fault.detail is detail)
def test_to_parent_wo_detail(self): from lxml.etree import Element import spyne.const.xml ns_soap_env = spyne.const.xml.NS_SOAP11_ENV soap_env = spyne.const.xml.PREFMAP[spyne.const.xml.NS_SOAP11_ENV] element = Element('testing') fault = Fault() cls = Fault XmlDocument().to_parent(None, cls, fault, element, 'urn:ignored') (child,) = element.getchildren() self.assertEqual(child.tag, '{%s}Fault' % ns_soap_env) self.assertEqual(child.find('faultcode').text, '%s:Server' % soap_env) self.assertEqual(child.find('faultstring').text, 'Fault') self.assertEqual(child.find('faultactor').text, '') self.assertFalse(child.findall('detail'))
def test_from_xml_wo_detail(self): from lxml.etree import Element from lxml.etree import SubElement import spyne.const.xml_ns ns_soap_env = spyne.const.xml_ns.soap_env element = Element('{%s}Fault' % ns_soap_env) fcode = SubElement(element, 'faultcode') fcode.text = 'senv:other' fstr = SubElement(element, 'faultstring') fstr.text = 'Testing' actor = SubElement(element, 'faultactor') actor.text = 'phreddy' fault = XmlDocument().from_element(Fault, element) self.assertEqual(fault.faultcode, 'senv:other') self.assertEqual(fault.faultstring, 'Testing') self.assertEqual(fault.faultactor, 'phreddy') self.assertEqual(fault.detail, None)