Beispiel #1
0
    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)
Beispiel #2
0
    def serve_forever(self):
        while True:
            last = self.session.query(WorkerStatus).with_lockmode("update") \
                          .filter_by(worker_id=self.id).one()

            task_queue = self.session.query(TaskQueue) \
                    .filter(TaskQueue.id > last.task_id) \
                    .order_by(TaskQueue.id)

            for task in task_queue:
                initial_ctx = MethodContext(self.app)
                initial_ctx.in_string = [task.data]
                initial_ctx.transport.consumer_id = self.id
                initial_ctx.transport.task_id = task.id

                for ctx in self.generate_contexts(initial_ctx, 'utf8'):
                    self.get_in_object(ctx)
                    if ctx.in_error:
                        self.get_out_string(ctx)
                        logging.error(''.join(ctx.out_string))
                        continue

                    self.get_out_object(ctx)
                    if ctx.out_error:
                        self.get_out_string(ctx)
                        logging.error(''.join(ctx.out_string))
                        continue

                    self.get_out_string(ctx)
                    logging.debug(''.join(ctx.out_string))

                    last.task_id = task.id
                    self.session.commit()

            time.sleep(10)
Beispiel #3
0
    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"
Beispiel #4
0
    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)
Beispiel #5
0
        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"}}})]
Beispiel #6
0
        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'
Beispiel #7
0
    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()
Beispiel #8
0
    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'')
Beispiel #9
0
    def test_multiple_return_sd_0(self):
        class SomeService(ServiceBase):
            @srpc(_returns=Iterable(Integer))
            def some_call():
                return 1, 2

        app = Application([SomeService], 'tns', JsonObject(), JsonObject(),
                                                                       Wsdl11())

        server = ServerBase(app)
        initial_ctx = MethodContext(server)
        initial_ctx.in_string = ['{"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) == ['{"some_callResponse": {"some_callResult": {"integer": [1, 2]}}}' ]

        server = ServerBase(app)
        initial_ctx = MethodContext(server)
        initial_ctx.in_string = ['{"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) == ['{"some_callResponse": {"some_callResult": {"integer": [1, 2]}}}']
Beispiel #10
0
    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"
Beispiel #11
0
    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
Beispiel #12
0
    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_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)
Beispiel #14
0
    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')
Beispiel #15
0
    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)
Beispiel #16
0
    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')
Beispiel #17
0
    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')
Beispiel #18
0
    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)
Beispiel #19
0
        def test_multiple_return_sd_0(self):
            class SomeService(ServiceBase):
                @srpc(_returns=Iterable(Integer))
                def some_call():
                    return 1, 2

            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": {"integer": [1, 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)

            assert list(ctx.out_string) == [serializer.dumps({"some_callResponse": {"some_callResult": {"integer": [1, 2]}}})]
Beispiel #20
0
    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
Beispiel #21
0
    def handle_rpc(self, element, serviceId):

        log.debug('call handle_rpc')

        def _cb_deferred(ret, ctx):
            #             print('deferred: %s' % str(ret))
            log.debug('deferred result')
            om = ctx.descriptor.out_message
            if ((not issubclass(om, ComplexModelBase)) or
                    len(om._type_info) <= 1):
                ctx.out_object = (ret.encode('utf-8'))
            else:
                ctx.out_object = (r.decode('utf-8') for r in ret)
            self.get_out_string(ctx)
            return ctx.out_string[0]

        def _eb_deferred(error, ctx):
            ctx.out_error = error.value
            if isinstance(ctx.out_string, list):
                log.error(''.join(ctx.out_string))
            else:
                log.error(ctx.out_string)
            return ctx.out_string

        initial_ctx = MethodContext(self, MethodContext.SERVER)
        initial_ctx.in_string = element
        for ctx in self.generate_contexts(initial_ctx, 'utf8'):
            # This is standard boilerplate for invoking services.
            if ctx.in_error:
                print(ctx)
            try:
                self.get_in_object(ctx)
            except AttributeError:
                log.error(ctx.out_string)
                return defer.succeed(UPNP_ERROR % (serviceId,
                                                   ctx.in_error.faultcode,
                                                   ctx.in_error.faultstring))
            if ctx.in_error:
                self.get_out_string(ctx)
                log.error(''.join(ctx.out_string))
                continue
            self.get_out_object(ctx)
            if ctx.out_error:
                self.get_out_string(ctx)
                log.error(''.join(ctx.out_string))
                continue
            ret = ctx.out_object[0]
#             print(ret)
            if isinstance(ret, Deferred):
                if ret.called:
                    return defer.succeed(_cb_deferred(ret.result, ctx))
                ret.addCallback(_cb_deferred, ctx)
                ret.addErrback(_eb_deferred, ctx)
                return ret
            else:
                self.get_out_string(ctx)
#                 print('no deferred: %s' % ctx.out_string)
                log.debug('result type no deferred')
                return defer.succeed(ctx.out_string)
Beispiel #22
0
    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',
        )
Beispiel #23
0
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
Beispiel #24
0
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
Beispiel #25
0
    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'
Beispiel #26
0
    def serve_forever(self):
        while True:
            # get the id of the last processed job
            last = self.session.query(WorkerStatus).with_lockmode("update") \
                          .filter_by(worker_id=self.id).one()

            # get new tasks
            task_id = 0
            if last.task is not None:
                task_id = last.task.id

            task_queue = self.session.query(TaskQueue) \
                    .filter(TaskQueue.id > task_id) \
                    .order_by(TaskQueue.id)

            for task in task_queue:
                initial_ctx = MethodContext(self)

                # this is the critical bit, where the request bytestream is put
                # in the context so that the protocol can deserialize it.
                initial_ctx.in_string = [task.data]

                # these two lines are purely for logging
                initial_ctx.transport.consumer_id = self.id
                initial_ctx.transport.task_id = task.id

                # The ``generate_contexts`` call parses the incoming stream and
                # splits the request into header and body parts.
                # There will be only one context here because no auxiliary
                # methods are defined.
                for ctx in self.generate_contexts(initial_ctx, 'utf8'):
                    # This is standard boilerplate for invoking services.
                    self.get_in_object(ctx)
                    if ctx.in_error:
                        self.get_out_string(ctx)
                        logging.error(''.join(ctx.out_string))
                        continue

                    self.get_out_object(ctx)
                    if ctx.out_error:
                        self.get_out_string(ctx)
                        logging.error(''.join(ctx.out_string))
                        continue

                    self.get_out_string(ctx)
                    logging.debug(''.join(ctx.out_string))

                    last.task_id = task.id
                    self.session.commit()

            time.sleep(10)
Beispiel #27
0
    def serve_forever(self):
        while True:
            # get the id of the last processed job
            last = self.session.query(WorkerStatus).with_lockmode("update") \
                          .filter_by(worker_id=self.id).one()

            # get new tasks
            task_id = 0
            if last.task is not None:
                task_id = last.task.id

            task_queue = self.session.query(TaskQueue) \
                    .filter(TaskQueue.id > task_id) \
                    .order_by(TaskQueue.id)

            for task in task_queue:
                initial_ctx = MethodContext(self)

                # this is the critical bit, where the request bytestream is put
                # in the context so that the protocol can deserialize it.
                initial_ctx.in_string = [task.data]

                # these two lines are purely for logging
                initial_ctx.transport.consumer_id = self.id
                initial_ctx.transport.task_id = task.id

                # The ``generate_contexts`` call parses the incoming stream and
                # splits the request into header and body parts.
                # There will be only one context here because no auxiliary
                # methods are defined.
                for ctx in self.generate_contexts(initial_ctx, 'utf8'):
                    # This is standard boilerplate for invoking services.
                    self.get_in_object(ctx)
                    if ctx.in_error:
                        self.get_out_string(ctx)
                        logging.error(''.join(ctx.out_string))
                        continue

                    self.get_out_object(ctx)
                    if ctx.out_error:
                        self.get_out_string(ctx)
                        logging.error(''.join(ctx.out_string))
                        continue

                    self.get_out_string(ctx)
                    logging.debug(''.join(ctx.out_string))

                    last.task_id = task.id
                    self.session.commit()

            time.sleep(10)
Beispiel #28
0
    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'
Beispiel #29
0
    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"
Beispiel #30
0
    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'
Beispiel #31
0
        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"
Beispiel #32
0
 def __call__(self, REQUEST):
   server = self._getServer()
   if REQUEST.method == 'GET':
     wsdl = Wsdl11(server.app.interface)
     wsdl.build_interface_document(self.absolute_url())
     return wsdl.get_interface_document()
   REQUEST.stdin.seek(0)
   ctx = MethodContext(server)
   ctx.in_string = REQUEST.stdin
   ctx, = server.generate_contexts(ctx)
   ctx.udc = self
   server.get_in_object(ctx)
   server.get_out_object(ctx)
   server.get_out_string(ctx)
   return ''.join(ctx.out_string)
Beispiel #33
0
    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()
Beispiel #34
0
    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'
Beispiel #35
0
        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_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'
Beispiel #37
0
def _process_v1_msg(prot, msg):
    ctx = MethodContext(prot)

    header = None
    body = msg[1]
    if not isinstance(body, basestring):
        raise ValidationError(body, "Body must be a bytestream.")

    if len(msg) > 2:
        header = msg[2]
        if not isinstance(header, dict):
            raise ValidationError(header, "Header must be a dict.")

    ctx.in_string = [body]
    ctx.transport.in_header = header

    return ctx
Beispiel #38
0
    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'
Beispiel #39
0
def _process_v1_msg(prot, msg):
    ctx = MethodContext(prot)

    header = None
    body = msg[1]
    if not isinstance(body, basestring):
        raise ValidationError(body, "Body must be a bytestream.")

    if len(msg) > 2:
        header = msg[2]
        if not isinstance(header, dict):
            raise ValidationError(header, "Header must be a dict.")

    ctx.in_string = [body]
    ctx.transport.in_header = header

    return ctx
Beispiel #40
0
    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'
Beispiel #41
0
    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"
Beispiel #42
0
    def test_multiple_dict_array(self):
        class SomeService(ServiceBase):
            @srpc(Iterable(String), _returns=Iterable(String))
            def some_call(s):
                return s

        app = Application([SomeService], 'tns', JsonObject(), JsonObject(), Wsdl11())
        server = ServerBase(app)

        initial_ctx = MethodContext(server)
        initial_ctx.in_string = ['{"some_call":{"s":["a","b"]}}']

        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) == ['{"some_callResponse": {"some_callResult": {"string": ["a", "b"]}}}']
Beispiel #43
0
    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)
Beispiel #44
0
        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)
Beispiel #45
0
 def __call__(self, REQUEST):
     server = self._getServer()
     if REQUEST.method == "GET":
         wsdl = Wsdl11(server.app.interface)
         wsdl.build_interface_document(self.absolute_url())
         return wsdl.get_interface_document()
     REQUEST.stdin.seek(0)
     if hasattr(MethodContext, "SERVER"):
         ctx = MethodContext(server, MethodContext.SERVER)
     else:  # BBB spyne < 2.12
         ctx = MethodContext(server)
     ctx.in_string = REQUEST.stdin
     ctx, = server.generate_contexts(ctx)
     ctx.udc = self
     server.get_in_object(ctx)
     server.get_out_object(ctx)
     server.get_out_string(ctx)
     return "".join(ctx.out_string)
Beispiel #46
0
        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'
Beispiel #47
0
    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"
Beispiel #48
0
    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"
Beispiel #49
0
    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')
Beispiel #50
0
    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 __call__(self, REQUEST):  # pylint: disable=arguments-differ
     server = self._getServer()
     if REQUEST.method == 'GET':
         wsdl = Wsdl11(server.app.interface)
         wsdl.build_interface_document(self.absolute_url())
         return wsdl.get_interface_document()
     REQUEST.stdin.seek(0)
     if hasattr(MethodContext, 'SERVER'):
         ctx = MethodContext(server, MethodContext.SERVER)
     else:  # BBB spyne < 2.12
         ctx = MethodContext(server)  # pylint: disable=no-value-for-parameter
     ctx.in_string = REQUEST.stdin
     ctx, = server.generate_contexts(ctx)
     ctx.udc = self
     server.get_in_object(ctx)
     server.get_out_object(ctx)
     server.get_out_string(ctx)
     return ''.join(ctx.out_string)
Beispiel #52
0
    def test_parse_hex_values(self):
        """
        Test that non-utf-8 hex values can be parsed without error
        """
        # Example TR-069 CPE->ACS RPC call. 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">0_THOM_TR69_ID</cwmp:ID>
                </soapenv:Header>
                <soapenv:Body>
                    <cwmp:Inform>
                        <DeviceId>
                            <Manufacturer>THOMSON</Manufacturer>
                            <OUI>00147F</OUI>
                            <ProductClass>SpeedTouch 780</ProductClass>
                            <SerialNumber>CP0611JTLNW</SerialNumber>
                        </DeviceId>
                        <Event soap:arrayType="cwmp:EventStruct[04]">
                            <EventStruct>
                                <EventCode>0 BOOTSTRAP</EventCode>
                                <CommandKey></CommandKey>
                            </EventStruct>
                            <EventStruct>
                                <EventCode>1 BOOT</EventCode>
                                <CommandKey></CommandKey>
                            </EventStruct>
                            <EventStruct>
                                <EventCode>2 PERIODIC</EventCode>
                                <CommandKey></CommandKey>
                            </EventStruct>
                            <EventStruct>
                                <EventCode>4 VALUE CHANGE</EventCode>
                                <CommandKey></CommandKey>
                            </EventStruct>
                        </Event>
                        <MaxEnvelopes>2</MaxEnvelopes>
                        <CurrentTime>1970-01-01T00:01:09Z</CurrentTime>
                        <RetryCount>05</RetryCount>
                        <ParameterList soap:arrayType="cwmp:ParameterValueStruct[12]">
                            <ParameterValueStruct>
                                <Name>InternetGatewayDevice.DeviceSummary</Name>
                                <Value xsi:type="xsd:string">
                                    \xff\xff\xff\xff\xff</Value>
                            </ParameterValueStruct>
                        </ParameterList>
                    </cwmp:Inform>
                </soapenv:Body>
            </soapenv: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)
Beispiel #53
0
    def __call__(self, *args, **kwargs):
        initial_ctx = MethodContext(self, MethodContext.SERVER)
        initial_ctx.method_request_string = self._key
        initial_ctx.in_header = self._in_header
        initial_ctx.transport.type = NullServer.transport
        initial_ctx.locale = self._locale

        contexts = self.app.in_protocol.generate_method_contexts(initial_ctx)

        retval = None
        logger.warning("%s start request %s" % (_big_header, _big_footer))

        if self._async:
            from twisted.internet.defer import Deferred

        for cnt, ctx in enumerate(contexts):
            # this reconstruction is quite costly. I wonder whether it's a
            # problem though.

            _type_info = ctx.descriptor.in_message._type_info
            ctx.in_object = [None] * len(_type_info)
            for i in range(len(args)):
                ctx.in_object[i] = args[i]

            for i, k in enumerate(_type_info.keys()):
                val = kwargs.get(k, None)
                if val is not None:
                    ctx.in_object[i] = val

            if ctx.descriptor.body_style == BODY_STYLE_BARE:
                ctx.in_object = ctx.descriptor.in_message \
                                      .get_serialization_instance(ctx.in_object)

            if cnt == 0:
                p_ctx = ctx
            else:
                ctx.descriptor.aux.initialize_context(ctx, p_ctx, error=None)

            # do logging.getLogger('spyne.server.null').setLevel(logging.CRITICAL)
            # to hide the following
            logger.warning("%s start context %s" %
                           (_small_header, _small_footer))
            logger.warning("%r.%r" %
                           (ctx.service_class, ctx.descriptor.function))
            try:
                self.app.process_request(ctx)
            finally:
                logger.warning("%s  end context  %s" %
                               (_small_header, _small_footer))

            if cnt == 0:
                if self._async and isinstance(ctx.out_object[0], Deferred):
                    retval = ctx.out_object[0]
                    retval.addCallback(_cb_async, ctx, cnt, self)

                else:
                    retval = _cb_sync(ctx, cnt, self)

        if not self._async:
            p_ctx.close()

        logger.warning("%s  end request  %s" % (_big_header, _big_footer))

        return retval
Beispiel #54
0
    def test_generate_set_parameter_values_string(self):
        """
        Test that correct string is generated for SetParameterValues ACS->CPE
        request
        """
        # Example ACS->CPE RPC call. Copied from:
        # http://djuro82.blogspot.com/2011/05/tr-069-cpe-provisioning.html
        # Following edits made:
        # - Change header ID value from 'null0' to 'null', to match magma
        #   default ID
        expected_acs_string = b'''
        <soapenv:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/encoding/" xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:cwmp="urn:dslforum-org:cwmp-1-0" xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
            <soapenv:Header>
                <cwmp:ID soapenv:mustUnderstand="1">null</cwmp:ID>
            </soapenv:Header>
            <soapenv:Body>
                <cwmp:SetParameterValues>
                    <ParameterList soap:arrayType="cwmp:ParameterValueStruct[4]">
                        <ParameterValueStruct>
                            <Name>InternetGatewayDevice.ManagementServer.PeriodicInformEnable</Name>
                            <Value xsi:type="xsd:boolean">1</Value>
                        </ParameterValueStruct>
                        <ParameterValueStruct>
                            <Name>InternetGatewayDevice.ManagementServer.ConnectionRequestUsername</Name>
                            <Value xsi:type="xsd:string">00147F-SpeedTouch780-CP0611JTLNW</Value>
                        </ParameterValueStruct>
                        <ParameterValueStruct>
                            <Name>InternetGatewayDevice.ManagementServer.ConnectionRequestPassword</Name>
                            <Value xsi:type="xsd:string">98ff55fb377bf724c625f60dec448646</Value>
                        </ParameterValueStruct>
                        <ParameterValueStruct>
                            <Name>InternetGatewayDevice.ManagementServer.PeriodicInformInterval</Name>
                            <Value xsi:type="xsd:unsignedInt">60</Value>
                        </ParameterValueStruct>
                    </ParameterList>
                    <ParameterKey>null</ParameterKey>
                </cwmp:SetParameterValues>
            </soapenv:Body>
        </soapenv:Envelope>
        '''

        request = models.SetParameterValues()

        request.ParameterList = \
            models.ParameterValueList(arrayType='cwmp:ParameterValueStruct[4]')
        request.ParameterList.ParameterValueStruct = []

        param = models.ParameterValueStruct()
        param.Name = 'InternetGatewayDevice.ManagementServer.PeriodicInformEnable'
        param.Value = models.anySimpleType(type='xsd:boolean')
        param.Value.Data = '1'
        request.ParameterList.ParameterValueStruct.append(param)

        param = models.ParameterValueStruct()
        param.Name = 'InternetGatewayDevice.ManagementServer.ConnectionRequestUsername'
        param.Value = models.anySimpleType(type='xsd:string')
        param.Value.Data = '00147F-SpeedTouch780-CP0611JTLNW'
        request.ParameterList.ParameterValueStruct.append(param)

        param = models.ParameterValueStruct()
        param.Name = 'InternetGatewayDevice.ManagementServer.ConnectionRequestPassword'
        param.Value = models.anySimpleType(type='xsd:string')
        param.Value.Data = '98ff55fb377bf724c625f60dec448646'
        request.ParameterList.ParameterValueStruct.append(param)

        param = models.ParameterValueStruct()
        param.Name = 'InternetGatewayDevice.ManagementServer.PeriodicInformInterval'
        param.Value = models.anySimpleType(type='xsd:unsignedInt')
        param.Value.Data = '60'
        request.ParameterList.ParameterValueStruct.append(param)

        request.ParameterKey = 'null'

        def side_effect(*args, **_kwargs):
            ctx = args[0]
            ctx.out_header = models.ID(mustUnderstand='1')
            ctx.out_header.Data = 'null'
            ctx.descriptor.out_message.Attributes.sub_name = request.__class__.__name__
            return request

        self.p.stop()
        self.p = patch.object(AutoConfigServer, '_handle_tr069_message',
                              Mock(side_effect=side_effect))
        self.p.start()

        server = ServerBase(self.app)

        ctx = MethodContext(server, MethodContext.SERVER)
        ctx.in_string = [b'']
        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

        server.get_out_string(ctx)

        xml_tree = XmlTree()
        match = xml_tree.xml_compare(
            xml_tree.convert_string_to_tree(b''.join(ctx.out_string)),
            xml_tree.convert_string_to_tree(expected_acs_string))
        self.assertTrue(match)
Beispiel #55
0
 def _get_ctx(self, server, in_string):
     initial_ctx = MethodContext(server)
     initial_ctx.in_string = in_string
     ctx, = server.generate_contexts(initial_ctx)
     server.get_in_object(ctx)
     return ctx
Beispiel #56
0
    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"