def test_response_received(self):

        publish_urn = 'rho:instances.owner'

        payload = StoragePayload()
        payload.add_type(FOAF.Person, RHO.Owner)

        promise = self.rdf_publisher.send_out_request(payload)

        args, kwargs = self.roster_plugin.send_message.call_args
        payload = kwargs['payload']
        thread_id = kwargs['thread_id']

        response_payload = ResultCollectionPayload()
        response_payload.append(ResultPayload(about=publish_urn, types=[FOAF.Person, RHO.Owner]))

        self.rdf_publisher._send_message(RDFStanzaType.RESPONSE, response_payload, thread_id)
        response_args, response_kwargs = self.roster_plugin.send_message.call_args

        payload = response_kwargs['payload']
        response_message = Message()
        response_message.append(payload)
        response_message['thread'] = response_kwargs['thread_id']

        with mock.patch.object(promise, attribute='resolved') as mock_promise_resolve:
            self.rdf_publisher._receive_message(response_message)

            self.assertEqual(1, mock_promise_resolve.call_count)
            args, kwargs = mock_promise_resolve.call_args

            result = [rdf.about for rdf in args[0].results]

            self.assertEqual(result, [publish_urn])
    def command_start(self, iq, initial_session):
        """
        Starting point for creating a new node.
        :param iq:
        :param initial_session:
        :return:
        """
        if not initial_session['payload']:
            initial_session['notes'] = [('error', 'Cannot execute without a payload')]
        else:
            logger.info('Update Node iq: %s' % iq)
            logger.info('Initial_session: %s' % initial_session)

            payload = StoragePayload(initial_session['payload'])

            logger.debug('relationships: %s' % payload.references)
            logger.debug('properties: %s' % payload.properties)
            logger.debug('types: %s' % payload.types)
            logger.debug('about: %s' % payload.about)

            node = self._command_handler.get_node(payload.about)

            self._command_handler.update_node(node, payload.references, payload.properties)

            # Build up the form response containing the newly created uri
            result = ResultCollectionPayload()
            result.append(ResultPayload(about=str(node.uri), types=node.labels))

            initial_session['payload'] = result.populate_payload()

        return initial_session
    def test_execute_cypher(self):

        self.storage_client._store_found('[email protected]/storage')

        payload = StoragePayload()
        payload.add_property(NEO4J.cypher, 'Match (n) RETURN n LIMIT 25')

        promise = self.storage_client.execute_cypher(payload)

        def handle_result(result):
            self.session['result'] = result

        promise.then(handle_result)

        self.assertTrue(hasattr(promise, 'then'))

        self.send("""
                <iq type="set" to="[email protected]/storage" id="1">
                    <command xmlns="http://jabber.org/protocol/commands"
                        node="cypher"
                        action="execute">
                        <x xmlns="jabber:x:data" type="form">
                            <field var="http://www.neo4j.com/terms/#cypher" type="list-multi">
                                <value>Match (n) RETURN n LIMIT 25</value>
                                <validate xmlns="http://jabber.org/protocol/xdata-validate" datatype="xs:string" />
                            </field>
                        </x>
                    </command>
                </iq>
            """)

        self.assertNotIn('result', self.session)

        result_payload = ResultCollectionPayload()
        result_payload.append(ResultPayload(about='http://www.example.org/instance/01',
                                            types=[FOAF.Person]))

        self.recv("""
                <iq type='result' from='[email protected]/storage' to='tester@localhost/full' id='1'>
                    <command xmlns='http://jabber.org/protocol/commands'
                           sessionid='list:20020923T213616Z-700'
                           node='cypher'
                           status='completed'>
                            %s
                    </command>
                </iq>
            """ % result_payload.populate_payload())

        time.sleep(0.2)

        self.assertIn('result', self.session)

        result = self.session['result']

        self.assertEqual(1, len(result.results))

        self.assertEqual(result.results[0].about, 'http://www.example.org/instance/01')
        self.assertEquals(result.results[0].types[0], str(FOAF.Person))
    def test_sources_retrieved(self):

        publish_urn = 'rho:instances.owner'

        payload = StoragePayload()
        payload.add_type(FOAF.Person, RHO.Owner)

        promise = self.rdf_publisher.send_out_request(payload, allow_multiple=True)

        args, kwargs = self.roster_plugin.send_message.call_args
        payload = kwargs['payload']
        thread_id = kwargs['thread_id']

        args, kwargs = self.scheduler_plugin.schedule_task.call_args
        callback = kwargs['callback']

        response_payload = ResultCollectionPayload()
        response_payload.append(ResultPayload(about=publish_urn, types=[FOAF.Person, RHO.Owner]))

        search_command_node = 'xmpp:[email protected]/bot?command;node=search_command'

        rdf_payload = self.rdf_publisher.create_rdf(mtype=RDFStanzaType.SEARCH_RESPONSE,
                                                    payload=response_payload, source_name='Search Command',
                                                    source_command=search_command_node)

        response_message = Message()
        response_message.append(rdf_payload)
        response_message['thread'] = thread_id

        with mock.patch.object(promise, attribute='resolved') as mock_promise_resolve:
            self.rdf_publisher._receive_message(response_message)

            mock_promise_resolve.assert_not_called()

        with mock.patch.object(promise, attribute='resolved') as mock_promise_resolve:

            callback()

            self.assertEqual(1, mock_promise_resolve.call_count)
            args, kwargs = mock_promise_resolve.call_args

            result_payload = args[0]

            result = [rdf.about for rdf in result_payload.results]

            self.assertEqual(result, [publish_urn, ])

            self.assertTrue(hasattr(result_payload, 'sources'))

            sources = list(result_payload.sources)

            self.assertEqual(1, len(sources))

            self.assertEqual('Search Command', sources[0][0])
            self.assertEqual('xmpp:[email protected]/bot?command;node=search_command', sources[0][1])
    def test_retrieve_all(self):

        publish_urn = 'rho:instances.owner'

        payload = StoragePayload()
        payload.add_type(FOAF.Person, RHO.Owner)

        promise = self.rdf_publisher.send_out_request(payload, allow_multiple=True)

        args, kwargs = self.roster_plugin.send_message.call_args
        payload = kwargs['payload']
        thread_id = kwargs['thread_id']

        args, kwargs = self.scheduler_plugin.schedule_task.call_args
        callback = kwargs['callback']

        response_payload = ResultCollectionPayload()
        response_payload.append(ResultPayload(about=publish_urn, types=[FOAF.Person, RHO.Owner]))

        self.rdf_publisher._send_message(RDFStanzaType.RESPONSE, response_payload, thread_id)
        response_args, response_kwargs = self.roster_plugin.send_message.call_args

        payload = response_kwargs['payload']
        response_message = Message()
        response_message.append(payload)
        response_message['thread'] = response_kwargs['thread_id']

        with mock.patch.object(promise, attribute='resolved') as mock_promise_resolve:
            self.rdf_publisher._receive_message(response_message)

            mock_promise_resolve.assert_not_called()

        with mock.patch.object(promise, attribute='resolved') as mock_promise_resolve:
            self.rdf_publisher._receive_message(response_message)

            mock_promise_resolve.assert_not_called()

        with mock.patch.object(promise, attribute='resolved') as mock_promise_resolve:

            callback()

            self.assertEqual(1, mock_promise_resolve.call_count)
            args, kwargs = mock_promise_resolve.call_args

            result = [rdf.about for rdf in args[0].results]

            self.assertEqual(result, [publish_urn, publish_urn])

            # Should not have any sources defined.
            callback_results = args[0]

            self.assertFalse(hasattr(callback_results, 'sources'))
    def command_start(self, request, initial_session):
        """
        Starting point for creating a new node.
        :param request:
        :param initial_session:
        :return:
        """
        if not initial_session["payload"]:
            initial_session["notes"] = [("error", "Cannot execute without a payload")]
        else:
            payload = StoragePayload(initial_session["payload"])
            cypher_statement = payload.properties.get(str(NEO4J.cypher), None)

            if cypher_statement:
                records = self._command_handler.execute_cypher(cypher_statement[0])
            else:
                records = None

            # Build up the form response containing the newly created uri
            result_collection_payload = ResultCollectionPayload()

            translation_map = CypherFlags.TRANSLATION_KEY.fetch_from(payload.flags)
            translation_map = json.loads(translation_map)

            if records:
                for record in records.records:
                    about = None
                    labels = None
                    columns = {}

                    for key, value in translation_map.iteritems():
                        if key == str(RDF.about):
                            node = record[value]
                            about = node.uri
                            labels = node.labels
                        else:
                            columns[key] = record[value]

                    result_payload = ResultPayload(about=about, types=labels)

                    for key, value in columns.iteritems():
                        result_payload.add_column(key, value)

                    result_collection_payload.append(result_payload)

            initial_session["payload"] = result_collection_payload.populate_payload()

        return initial_session
    def test_process_handler(self):
        """
        This is a method that should receive a collection of results, package them in a rdf payload to be sent off
        :return:
        """
        search_handler._rdf_publish = mock.MagicMock(**{"create_rdf.return": True})

        payload = ResultCollectionPayload()

        result = self.search_handler._handle_results(payload)
        self.assertTrue(result)

        payload.append(ResultPayload(about="uri:valid", types=[WGS_84.SpatialThing]))

        result = self.search_handler._handle_results(payload)
        self.assertTrue(result)
    def test_multiple_responses(self):

        publish_urn = "rho:instances.owner"

        payload = StoragePayload()
        payload.add_type(FOAF.Person, RHO.Owner)

        promise = self.rdf_publisher.send_out_request(payload, allow_multiple=True)

        args, kwargs = self.roster_plugin.send_message.call_args
        payload = kwargs["payload"]
        thread_id = kwargs["thread_id"]

        args, kwargs = self.scheduler_plugin.schedule_task.call_args
        callback = kwargs["callback"]

        response_payload = ResultCollectionPayload()
        response_payload.append(ResultPayload(about=publish_urn, types=[FOAF.Person, RHO.Owner]))

        self.rdf_publisher._send_message(RDFStanzaType.RESPONSE, response_payload, thread_id)
        response_args, response_kwargs = self.roster_plugin.send_message.call_args

        payload = response_kwargs["payload"]
        response_message = Message()
        response_message.append(payload)
        response_message["thread"] = response_kwargs["thread_id"]

        with mock.patch.object(promise, attribute="resolved") as mock_promise_resolve:
            self.rdf_publisher._receive_message(response_message)

            mock_promise_resolve.assert_not_called()

        with mock.patch.object(promise, attribute="resolved") as mock_promise_resolve:
            self.rdf_publisher._receive_message(response_message)

            mock_promise_resolve.assert_not_called()

        with mock.patch.object(promise, attribute="resolved") as mock_promise_resolve:

            callback()

            self.assertEqual(1, mock_promise_resolve.call_count)
            args, kwargs = mock_promise_resolve.call_args

            result = [rdf.about for rdf in args[0].results]

            self.assertEqual(result, [publish_urn, publish_urn])
    def command_start(self, iq, initial_session):
        """
        Starting point for creating a new node.
        :param iq:
        :param initial_session:
        :return:
        """
        if not initial_session['payload']:
            initial_session['notes'] = [('error', 'Cannot execute without a payload')]
        else:
            payload = StoragePayload(initial_session['payload'])

            if logger.isEnabledFor(logging.DEBUG):
                logger.debug('Find Node iq: %s' % iq)
                logger.debug('Initial_session: %s' % initial_session)
                logger.debug('about: %s' % payload.about)
                logger.debug('relationships: %s' % payload.references)
                logger.debug('properties: %s' % payload.properties)
                logger.debug('types: %s' % payload.types)

            created = False
            nodes = self._command_handler.find_nodes(payload.types, **payload.properties)

            if not nodes and FindFlags.CREATE_IF_MISSING.fetch_from(payload.flags):
                node = self._command_handler.create_node(types=payload.types, properties=payload.properties,
                                                         relationships=payload.references)
                created = True
                nodes.append(node)

            # Build up the form response containing the newly created uri
            result_collection_payload = ResultCollectionPayload()
            for node in nodes:
                payload = ResultPayload(about=node.uri, types=node.labels)
                if created:
                    payload.add_flag(FindResults.CREATED, True)

                result_collection_payload.append(payload)

            initial_session['payload'] = result_collection_payload.populate_payload()

        return initial_session
    def test_update_node(self):

        self.storage_client._store_found('[email protected]/storage')

        payload = StoragePayload()
        payload.about = 'http://www.example.org/instance/01'
        payload.add_type(FOAF.Person)
        payload.add_property(FOAF.name, 'Robert')

        promise = self.storage_client.update_node(payload)

        def handle_result(result):
            self.session['result'] = result

        promise.then(handle_result)

        self.assertTrue(hasattr(promise, 'then'))

        self.send("""
                <iq type="set" to="[email protected]/storage" id="1">
                    <command xmlns="http://jabber.org/protocol/commands"
                        node="update_node"
                        action="execute">
                        <x xmlns="jabber:x:data" type="form">
                            <field var="http://www.w3.org/1999/02/22-rdf-syntax-ns#about" type="text-single">
                                <value>http://www.example.org/instance/01</value>
                            </field>
                            <field var="http://www.w3.org/1999/02/22-rdf-syntax-ns#type" type="list-multi">
                                <value>http://xmlns.com/foaf/0.1/Person</value>
                            </field>
                            <field var="http://xmlns.com/foaf/0.1/name" type="list-multi">
                                <value>Robert</value>
                                <validate xmlns="http://jabber.org/protocol/xdata-validate" datatype="xs:string" />
                            </field>
                        </x>
                    </command>
                </iq>
            """)

        self.assertNotIn('result', self.session)

        result_payload = ResultCollectionPayload()
        result_payload.append(ResultPayload(about='http://www.example.org/instance/01',
                                            types=[FOAF.Person]))

        self.recv("""
                <iq type='result' from='[email protected]/storage' to='tester@localhost/full' id='1'>
                    <command xmlns='http://jabber.org/protocol/commands'
                           sessionid='list:20020923T213616Z-700'
                           node='update_node'
                           status='completed'>
                            %s
                    </command>
                </iq>
            """ % result_payload.populate_payload())

        time.sleep(0.2)

        self.assertIn('result', self.session)

        result = self.session['result']

        self.assertEqual(1, len(result.results))

        self.assertEqual(result.results[0].about, 'http://www.example.org/instance/01')
        self.assertEquals(result.results[0].types[0], str(FOAF.Person))