Exemplo n.º 1
0
    def __init__(self, *args, **kwargs):
        """ResourceQueryTest base class constructor
        """
        super(ResourceServerTest, self).__init__(*args, **kwargs)

        self.config = {}
        with open("./config.json", "r") as f:
            self.config = json.load(f)

        self.testVector = {}
        with open("./tests/rs/testVector_ResourceServer.json", "r") as f:
            self.testVector = json.load(f)

        self.rs = ResourceServer(
            rs_url=self.config["urls"]["rs_url"],
            headers=self.config["headers"],
        )
        self.rs_query = ResourceQuery()

        self.rs_entity = self.rs_query.add_entity(
            self.testVector["entities"][0])
Exemplo n.º 2
0
    def __init__(self, *args, **kwargs):
        super(DuringTest, self).__init__(*args, **kwargs)
        self.config = {}
        with open("./config.json", "r") as f:
            self.config = json.load(f)
        self.token_obj = Token(client_id=self.config["client_id"],
                               client_secret=self.config["client_secret"])

        rs_url = "https://rs.iudx.org.in/ngsi-ld/v1"
        headers = {"content-type": "application/json"}
        self.rs: ResourceServer = ResourceServer(rs_url=rs_url,
                                                 headers=headers,
                                                 token_obj=self.token_obj)
Exemplo n.º 3
0
class ResourceServerTest(unittest.TestCase):
    """Test different scenarios for the ResourceServer class.
    """
    def __init__(self, *args, **kwargs):
        """ResourceQueryTest base class constructor
        """
        super(ResourceServerTest, self).__init__(*args, **kwargs)

        self.config = {}
        with open("./config.json", "r") as f:
            self.config = json.load(f)

        self.testVector = {}
        with open("./tests/rs/testVector_ResourceServer.json", "r") as f:
            self.testVector = json.load(f)

        self.rs = ResourceServer(
            rs_url=self.config["urls"]["rs_url"],
            headers=self.config["headers"],
        )
        self.rs_query = ResourceQuery()

        self.rs_entity = self.rs_query.add_entity(
            self.testVector["entities"][0])

    def test_get_latest(self):
        """Function to test the get latest resource API.
        """
        querries = []
        for i in range(3):
            query = self.rs_entity
            querries.append(query)

        results: List[ResourceResult] = self.rs.get_latest(querries)

        for result in results:
            print(f"RESULTS: {result.results}")
            print(f"TYPE: {result.type}")
            print(f"TITLE: {result.title}")
            print("*" * 30)

            self.assertEqual(result.type, 200)
            self.assertNotEqual(result.type, 400)
            self.assertNotEqual(result.type, 401)
            self.assertNotEqual(result.type, 404)
            self.assertNotEqual(result.type, 415)
            self.assertNotEqual(result.type, 500)

    def test_get_data(self):
        """Function to test the post complex query response API.
        """
        querries = []
        for i in range(3):
            query = self.rs_entity.during_search(
                start_time=self.testVector["time_params"][i]["time"],
                end_time=self.testVector["time_params"][i]["endtime"])
            querries.append(query)

        results: List[ResourceResult] = self.rs.get_data(querries)

        for result in results:
            print("*" * 30)
            print("*" * 30)
            print(results)
            print("*" * 30)

            print(f"RESULTS: {result.results}")
            print(f"TYPE: {result.type}")
            print(f"TITLE: {result.title}")
            print("*" * 30)

            self.assertEqual(result.type, 200)
            self.assertNotEqual(result.type, 400)
            self.assertNotEqual(result.type, 401)
            self.assertNotEqual(result.type, 404)
            self.assertNotEqual(result.type, 415)
            self.assertNotEqual(result.type, 500)
Exemplo n.º 4
0
    def __init__(
        self: Entity,
        entity_id: str=None,
        cat_url: str="https://api.catalogue.iudx.org.in/iudx/cat/v1",
        rs_url: str="https://rs.iudx.org.in/ngsi-ld/v1",
        headers: Dict={"content-type": "application/json"},
        token: str=None,
        token_obj: Token=None
    ):
        """Entity base class constructor for getting the resources from
                catalogue server.

        Args:
            entity_id (String): Id of the entity to be queried.
        """

        # public variables
        self.catalogue: Catalogue = Catalogue(
            cat_url=cat_url,
            headers=headers,
            token=token
        )
        self.rs: ResourceServer = None
        self.rs_url = rs_url
        self.resources: List[Dict] = []
        self.entity_id = entity_id
        self.resources_df = None
        self.start_time = None
        self.end_time = None
        self.time_format = "%Y-%m-%dT%H:%M:%S+05:30"
        self.slot_hours = 24
        self.max_query_days = 61

        # private variables 
        self._iudx_entity_type: str = None
        self._voc_url: str = None
        self._cat_doc: Dict = None
        self._data_descriptor: Dict = None
        self._geo_properties: List[Dict] = None
        self._time_properties: List[Dict] = None
        self._quantitative_properties: List[Dict] = None
        self._properties: List[Dict] = None



        # Query the Catalogue module and fetch the item based on entity_id
        # and set the data descriptors
        documents_result = self.catalogue.get_item(self.entity_id)

        if "iudx:ResourceGroup" in documents_result.documents[0]["type"]:
            try:
                self._data_descriptor = documents_result.documents[0]["dataDescriptor"]
            except Exception as e:
                # TODO: Populate data descriptors for all resources
                self._data_descriptor = {}
                print()


            if ("accessPolicy" in documents_result.documents[0].keys() \
                    and documents_result.documents[0]["accessPolicy"] == "OPEN"):
                token_obj.set_item(rs_url.split("/")[2], "resource_server", "consumer")

            # TODO: Parse the data schema from the data descriptor
            for key in self._data_descriptor.keys():
                pass

            # Fetch all Resources for the entity from Catalogue.
            cat_query = CatalogueQuery()
            param1 = {"key": "resourceGroup", "value": [self.entity_id]}
            param2 = {"key": "type", "value": ["iudx:Resource"]}

            query = cat_query.property_search(
                        key=param1["key"],
                        value=param1["value"]
                    ).property_search(
                        key=param2["key"],
                        value=param2["value"]
                    )

            # update resources list with the resources retrieved
            # from Catalogue query.
            cat_result = self.catalogue.search_entity(query)

            self.resources = cat_result.documents
            # for res in cat_result.documents:
            #     self.resources.append(res["id"])


        elif "iudx:Resource" in documents_result.documents[0]["type"]:
            self.resources = [{"id": self.entity_id}]
            rg = self.catalogue.get_related_entity(self.entity_id, rel="resourceGroup")
            if ("accessPolicy" in documents_result.documents[0].keys() \
                    and documents_result.documents[0]["accessPolicy"] == "OPEN"):
                token_obj.set_item(rs_url.split("/")[2], "resource_server", "consumer")
            if ("accessPolicy" in rg.documents[0].keys() \
                    and rg.documents[0]["accessPolicy"] == "OPEN"):
                token_obj.set_item(rs_url.split("/")[2], "resource_server", "consumer")

        # Request access token
        if token is None and token_obj is not None:
            token = token_obj.request_token()

        self.rs: ResourceServer = ResourceServer(
            rs_url=rs_url,
            headers=headers,
            token=token
        )
        return
Exemplo n.º 5
0
from iudx.rs.ResourceServer import ResourceServer
from iudx.rs.ResourceQuery import ResourceQuery

# entity id for the pune env aqm sensor.
entity_id = "datakaveri.org/04a15c9960ffda227e9546f3f46e629e1fe4132b/rs.iudx.org.in/pune-env-aqm/f36b4669-628b-ad93-9970-f9d424afbf75"

# creating an object of ResourceServer class using rs_url.
rs = ResourceServer(rs_url="https://rs.iudx.org.in/ngsi-ld/v1",
                    headers={"content-type": "application/json"})

# creating a query for fetching latest data for the entity_id.
rs_query = ResourceQuery()
rs_entity = rs_query.add_entity(entity_id)

# fetch results for a list of entities.
results = rs.get_latest([rs_entity])

# printing results
print(f"RESULTS: {results[0].results}"
      )  # get the result data of the resource query.
print(f"STATUS: {results[0].type}")  # get the status code for the response.
Exemplo n.º 6
0
from iudx.rs.ResourceServer import ResourceServer
from iudx.rs.ResourceQuery import ResourceQuery

# entity id for the pune env aqm sensor.
entity_id = "datakaveri.org/04a15c9960ffda227e9546f3f46e629e1fe4132b/rs.iudx.org.in/pune-env-aqm/f36b4669-628b-ad93-9970-f9d424afbf75"

# creating an object of ResourceServer class using rs_url.
rs = ResourceServer(rs_url="https://rs.iudx.org.in/ngsi-ld/v1",
                    headers={"content-type": "application/json"})

# creating a query for fetching latest data for the entity_id.
rs_query = ResourceQuery()
rs_entity = rs_query.add_entity(entity_id)

# create a during query for a time interval.
during_query = rs_entity.during_search(start_time="2021-01-01T14:20:00Z",
                                       end_time="2021-01-09T14:20:00Z")

# fetch results for the list of during queries.
results = rs.get_data([during_query])

# printing results
print(f"RESULTS: {results[0].results}"
      )  # get the result data of the resource query.
print(f"STATUS: {results[0].type}")  # get the status code for the response.