diff --git a/LICENSE b/LICENSE index 0d1d964..6547849 100644 --- a/LICENSE +++ b/LICENSE @@ -1,6 +1,6 @@ MIT License -Copyright (c) 2019 W3C Hydra +Copyright (c) 2019 W3C Hydra, 2020-2021 Hydra Ecosystem Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal diff --git a/README.md b/README.md index d2ac429..9716203 100644 --- a/README.md +++ b/README.md @@ -14,7 +14,7 @@ https://hydra-python-core.readthedocs.io/en/develop/ To install the library: ```bash -pip install git+https://github.com/HTTP-APIs/hydra-python-core.git#egg=hydra_python_core +pip install hydra_python_core ``` **Note :-** If using hydrus, the library doesn't need to be installed separately as it is already a part of `requirements.txt` for hydrus. @@ -31,3 +31,6 @@ from hydra_python_core import doc_maker ``` *Porting out from hydrus the hydraspecs directory* + +### Tests +After installation: `python-m unittest` diff --git a/hydra_python_core/doc_maker.py b/hydra_python_core/doc_maker.py index 5e671da..48680dc 100644 --- a/hydra_python_core/doc_maker.py +++ b/hydra_python_core/doc_maker.py @@ -5,8 +5,16 @@ import json from pyld import jsonld import requests -from hydra_python_core.doc_writer import (HydraDoc, HydraClass, HydraClassProp, - HydraClassOp, HydraStatus, HydraLink, HydraCollection, DocUrl) +from hydra_python_core.doc_writer import ( + HydraDoc, + HydraClass, + HydraClassProp, + HydraClassOp, + HydraStatus, + HydraLink, + HydraCollection, + DocUrl, +) from typing import Any, Dict, Match, Optional, Tuple, Union, List from hydra_python_core.namespace import hydra, rdfs from urllib.parse import urlparse @@ -14,8 +22,9 @@ jsonld.set_document_loader(jsonld.requests_document_loader()) -def create_doc(doc: Dict[str, Any], HYDRUS_SERVER_URL: str = None, - API_NAME: str = None) -> HydraDoc: +def create_doc( + doc: Dict[str, Any], HYDRUS_SERVER_URL: str = None, API_NAME: str = None +) -> HydraDoc: """ Create the HydraDoc object from the API Documentation. @@ -27,17 +36,16 @@ def create_doc(doc: Dict[str, Any], HYDRUS_SERVER_URL: str = None, """ # These keys must be there in the APIDOC: @context, @id, @type - if not all(key in doc for key in ('@context', '@id', '@type')): + if not all(key in doc for key in ("@context", "@id", "@type")): raise SyntaxError("Please make sure doc contains @context, @id and @type") - - _context = doc['@context'] - base_url = '' - entrypoint = '' - doc_name = 'vocab' - doc_url = '' - _id = '' - _entrypoint = '' + _context = doc["@context"] + base_url = "" + entrypoint = "" + doc_name = "vocab" + doc_url = "" + _id = "" + _entrypoint = "" _title = "The default title" _description = "This is the default description" _classes = [] @@ -50,64 +58,70 @@ def create_doc(doc: Dict[str, Any], HYDRUS_SERVER_URL: str = None, expanded_doc = jsonld.expand(doc) for item in expanded_doc: - _id = item['@id'] + _id = item["@id"] # Extract base_url, entrypoint and API name - base_url = urlparse(_id).scheme + '//' + urlparse(_id).netloc + base_url = urlparse(_id).scheme + "//" + urlparse(_id).netloc entrypoint = _entrypoint - doc_name = urlparse(_id).path.split('/')[-1] - doc_url = DocUrl(HYDRUS_SERVER_URL, api_name=API_NAME, doc_name=doc_name).doc_url - for entrypoint in item[hydra['entrypoint']]: - _entrypoint = entrypoint['@id'] - if hydra['title'] in item: - for title in item[hydra['title']]: - _title = title['@value'] - if hydra['description'] in item: - for description in item[hydra['description']]: - _description = description['@value'] - for classes in item[hydra['supportedClass']]: + doc_name = urlparse(_id).path.split("/")[-1] + doc_url = DocUrl( + HYDRUS_SERVER_URL, api_name=API_NAME, doc_name=doc_name + ).doc_url + for entrypoint in item[hydra["entrypoint"]]: + _entrypoint = entrypoint["@id"] + if hydra["title"] in item: + for title in item[hydra["title"]]: + _title = title["@value"] + if hydra["description"] in item: + for description in item[hydra["description"]]: + _description = description["@value"] + for classes in item[hydra["supportedClass"]]: isCollection = False - if hydra['manages'] in classes: + if hydra["manages"] in classes: isCollection = True _collections.append(classes) - for supported_prop in classes[hydra['supportedProperty']]: - for prop in supported_prop[hydra['property']]: - if '@type' in prop: - for prop_type in prop['@type']: - if prop_type == hydra['Link']: + for supported_prop in classes[hydra["supportedProperty"]]: + for prop in supported_prop[hydra["property"]]: + if "@type" in prop: + for prop_type in prop["@type"]: + if prop_type == hydra["Link"]: # find the range of the link - for resource_range in prop[rdfs['range']]: - _endpoints.append(check_namespace(resource_range['@id'])) + for resource_range in prop[rdfs["range"]]: + _endpoints.append( + check_namespace(resource_range["@id"]) + ) if not isCollection: _classes.append(classes) - for status in item[hydra['possibleStatus']]: + for status in item[hydra["possibleStatus"]]: _possible_status.append(status) for classes in _classes: - if classes['@id'] == hydra['Resource'] or classes['@id'] == hydra['Collection']: + if classes["@id"] == hydra["Resource"] or classes["@id"] == hydra["Collection"]: continue endpoint = False - if classes['@id'].find("EntryPoint") != -1: - classes['@id'] = "{}{}".format(doc_url, "EntryPoint") + if classes["@id"].find("EntryPoint") != -1: + classes["@id"] = "{}{}".format(doc_url, "EntryPoint") else: - classes['@id'] = check_namespace(classes['@id']) + classes["@id"] = check_namespace(classes["@id"]) for endpoints in _endpoints: - if classes['@id'] == endpoints: + if classes["@id"] == endpoints: endpoint = True _endpoint_class.append(classes) if not endpoint: _non_endpoint_classes.append(classes) for collections in _collections: - collections['@id'] = check_namespace(collections['@id']) + collections["@id"] = check_namespace(collections["@id"]) for endpoints in _endpoints: - if collections['@id'] == endpoints: + if collections["@id"] == endpoints: _endpoint_collection.append(collections) # Main doc object if HYDRUS_SERVER_URL is not None and API_NAME is not None: apidoc = HydraDoc( - API_NAME, _title, _description, API_NAME, HYDRUS_SERVER_URL, doc_name) + API_NAME, _title, _description, API_NAME, HYDRUS_SERVER_URL, doc_name + ) else: apidoc = HydraDoc( - entrypoint, _title, _description, entrypoint, base_url, doc_name) + entrypoint, _title, _description, entrypoint, base_url, doc_name + ) # additional context entries for entry in _context: @@ -115,16 +129,22 @@ def create_doc(doc: Dict[str, Any], HYDRUS_SERVER_URL: str = None, # make endpoint classes for endpoint_classes in _endpoint_class: - if endpoint_classes['@id'] == hydra['Resource'] or endpoint_classes['@id'] == hydra['Collection'] or \ - endpoint_classes['@id'].find("EntryPoint") != -1: + if ( + endpoint_classes["@id"] == hydra["Resource"] + or endpoint_classes["@id"] == hydra["Collection"] + or endpoint_classes["@id"].find("EntryPoint") != -1 + ): continue class_ = create_class(endpoint_classes, endpoint=True) apidoc.add_supported_class(class_) # make non-endpoint classes for classes in _non_endpoint_classes: - if classes['@id'] == hydra['Resource'] or classes['@id'] == hydra['Collection'] or \ - classes['@id'].find("EntryPoint") != -1: + if ( + classes["@id"] == hydra["Resource"] + or classes["@id"] == hydra["Collection"] + or classes["@id"].find("EntryPoint") != -1 + ): continue class_ = create_class(classes, endpoint=False) apidoc.add_supported_class(class_) @@ -145,6 +165,7 @@ def create_doc(doc: Dict[str, Any], HYDRUS_SERVER_URL: str = None, apidoc.gen_EntryPoint() return apidoc + def create_collection(endpoint_collection: Dict[str, Any]) -> HydraCollection: """ Creates the instance of HydraCollection from expanded APIDOC @@ -156,38 +177,49 @@ def create_collection(endpoint_collection: Dict[str, Any]) -> HydraCollection: collection_name = "The default collection name" collection_description = "The default collection description" - if hydra['title'] in endpoint_collection: - collection_name = endpoint_collection[hydra['title']][0]['@value'] + if hydra["title"] in endpoint_collection: + collection_name = endpoint_collection[hydra["title"]][0]["@value"] - if hydra['description'] in endpoint_collection: - collection_description = endpoint_collection[hydra['description']][0]['@value'] + if hydra["description"] in endpoint_collection: + collection_description = endpoint_collection[hydra["description"]][0]["@value"] manages = {} - if hydra['object'] in endpoint_collection[hydra['manages']][0]: - manages['object'] = check_namespace(endpoint_collection[hydra['manages']][0][hydra['object']][0]['@id']) - if hydra['subject'] in endpoint_collection[hydra['manages']][0]: - manages['subject'] = check_namespace(endpoint_collection[hydra['manages']][0][hydra['subject']][0]['@id']) - if hydra['property'] in endpoint_collection[hydra['manages']][0]: - manages['property'] = check_namespace(endpoint_collection[hydra['manages']][0][hydra['property']][0]['@id']) + if hydra["object"] in endpoint_collection[hydra["manages"]][0]: + manages["object"] = check_namespace( + endpoint_collection[hydra["manages"]][0][hydra["object"]][0]["@id"] + ) + if hydra["subject"] in endpoint_collection[hydra["manages"]][0]: + manages["subject"] = check_namespace( + endpoint_collection[hydra["manages"]][0][hydra["subject"]][0]["@id"] + ) + if hydra["property"] in endpoint_collection[hydra["manages"]][0]: + manages["property"] = check_namespace( + endpoint_collection[hydra["manages"]][0][hydra["property"]][0]["@id"] + ) is_get = False is_post = False is_put = False is_del = False - for supported_operations in endpoint_collection[hydra['supportedOperation']]: - if supported_operations[hydra['method']][0]['@value'] == 'GET': + for supported_operations in endpoint_collection[hydra["supportedOperation"]]: + if supported_operations[hydra["method"]][0]["@value"] == "GET": is_get = True - if supported_operations[hydra['method']][0]['@value'] == 'PUT': + if supported_operations[hydra["method"]][0]["@value"] == "PUT": is_post = True - if supported_operations[hydra['method']][0]['@value'] == 'POST': + if supported_operations[hydra["method"]][0]["@value"] == "POST": is_put = True - if supported_operations[hydra['method']][0]['@value'] == 'PUT': + if supported_operations[hydra["method"]][0]["@value"] == "PUT": is_del = True - collection_ = HydraCollection(collection_name=collection_name, - collection_description=collection_description, - manages=manages, get=is_get, - post=is_post, put=is_put, delete=is_del) + collection_ = HydraCollection( + collection_name=collection_name, + collection_description=collection_description, + manages=manages, + get=is_get, + post=is_post, + put=is_put, + delete=is_del, + ) return collection_ @@ -204,14 +236,13 @@ def create_class(expanded_class: Dict[str, Any], endpoint: bool) -> HydraClass: class_title = "A Class" class_description = "The description of the class" - if hydra['title'] in expanded_class: - class_title = expanded_class[hydra['title']][0]['@value'] + if hydra["title"] in expanded_class: + class_title = expanded_class[hydra["title"]][0]["@value"] - if hydra['description'] in expanded_class: - class_description = expanded_class[hydra['description']][0]['@value'] + if hydra["description"] in expanded_class: + class_description = expanded_class[hydra["description"]][0]["@value"] - class_ = HydraClass(class_title, - class_description, endpoint=endpoint) + class_ = HydraClass(class_title, class_description, endpoint=endpoint) # add supported Property for supported_property in expanded_class[hydra["supportedProperty"]]: @@ -219,7 +250,7 @@ def create_class(expanded_class: Dict[str, Any], endpoint: bool) -> HydraClass: class_.add_supported_prop(prop_) # add supported operations - for supported_operations in expanded_class[hydra['supportedOperation']]: + for supported_operations in expanded_class[hydra["supportedOperation"]]: op_ = create_operation(supported_operations) class_.add_supported_op(op_) @@ -240,35 +271,37 @@ def create_operation(supported_operation: Dict[str, Any]) -> HydraClassOp: op_returns_header = [] op_possible_status = [] - if hydra['title'] in supported_operation: - op_title = supported_operation[hydra['title']][0]['@value'] + if hydra["title"] in supported_operation: + op_title = supported_operation[hydra["title"]][0]["@value"] - op_method = supported_operation[hydra['method']][0]['@value'] + op_method = supported_operation[hydra["method"]][0]["@value"] - if hydra['expects'] in supported_operation: - op_expects = check_namespace(supported_operation[hydra['expects']][0]['@id']) + if hydra["expects"] in supported_operation: + op_expects = check_namespace(supported_operation[hydra["expects"]][0]["@id"]) - if hydra['returns'] in supported_operation: - op_returns = check_namespace(supported_operation[hydra['returns']][0]['@id']) + if hydra["returns"] in supported_operation: + op_returns = check_namespace(supported_operation[hydra["returns"]][0]["@id"]) - if hydra['expectsHeader'] in supported_operation: - for header in supported_operation[hydra['expectsHeader']]: - op_expects_header.append(header['@value']) + if hydra["expectsHeader"] in supported_operation: + for header in supported_operation[hydra["expectsHeader"]]: + op_expects_header.append(header["@value"]) - if hydra['returnsHeader'] in supported_operation: - for header in supported_operation[hydra['returnsHeader']]: - op_returns_header.append(header['@value']) + if hydra["returnsHeader"] in supported_operation: + for header in supported_operation[hydra["returnsHeader"]]: + op_returns_header.append(header["@value"]) - if hydra['possibleStatus'] in supported_operation: - op_possible_status = create_status(supported_operation[hydra['possibleStatus']]) + if hydra["possibleStatus"] in supported_operation: + op_possible_status = create_status(supported_operation[hydra["possibleStatus"]]) - op_ = HydraClassOp(title=op_title, - method=op_method, - expects=op_expects, - returns=op_returns, - expects_header=op_expects_header, - returns_header=op_returns_header, - possible_status=op_possible_status) + op_ = HydraClassOp( + title=op_title, + method=op_method, + expects=op_expects, + returns=op_returns, + expects_header=op_expects_header, + returns_header=op_returns_header, + possible_status=op_possible_status, + ) return op_ @@ -285,15 +318,15 @@ def create_status(possible_status: List[Any]) -> List[HydraStatus]: status_id = None status_title = "The default title for status" status_desc = "The default description of status" - if hydra['description'] in status: - status_desc = status[hydra['description']][0]['@value'] - status_code = status[hydra['statusCode']][0]['@value'] + if hydra["description"] in status: + status_desc = status[hydra["description"]][0]["@value"] + status_code = status[hydra["statusCode"]][0]["@value"] - if '@id' in status: - status_id = status['@id'] + if "@id" in status: + status_id = status["@id"] - if hydra['title'] in status: - status_title = status[hydra['title']][0]['@value'] + if hydra["title"] in status: + status_title = status[hydra["title"]][0]["@value"] status_ = HydraStatus(status_code, status_id, status_title, status_desc) status_list.append(status_) @@ -301,7 +334,9 @@ def create_status(possible_status: List[Any]) -> List[HydraStatus]: return status_list -def create_property(supported_property: Dict[str, Any]) -> Union[HydraLink, HydraClassProp]: +def create_property( + supported_property: Dict[str, Any] +) -> Union[HydraLink, HydraClassProp]: """ Creates the HydraClassProp from the expanded supported property @@ -311,25 +346,27 @@ def create_property(supported_property: Dict[str, Any]) -> Union[HydraLink, Hydr prop_id = "" prop_title = "The title of Property" - if hydra['property'] in supported_property: - prop_id = check_namespace(supported_property[hydra['property']][0]['@id']) - if '@type' in supported_property[hydra['property']][0]: - if supported_property[hydra['property']][0]['@type'][0] == hydra['Link']: - prop_id = create_link(supported_property[hydra['property']][0]) + if hydra["property"] in supported_property: + prop_id = check_namespace(supported_property[hydra["property"]][0]["@id"]) + if "@type" in supported_property[hydra["property"]][0]: + if supported_property[hydra["property"]][0]["@type"][0] == hydra["Link"]: + prop_id = create_link(supported_property[hydra["property"]][0]) else: - raise KeyError("{} is missing".format(hydra['property'])) - - if hydra['title'] in supported_property: - prop_title = supported_property[hydra['title']][0]['@value'] - prop_read = supported_property[hydra['readable']][0]['@value'] - prop_require = supported_property[hydra['required']][0]['@value'] - prop_write = supported_property[hydra['writeable']][0]['@value'] - - prop_ = HydraClassProp(prop=prop_id, - title=prop_title, - required=prop_require, - read=prop_read, - write=prop_write) + raise KeyError("{} is missing".format(hydra["property"])) + + if hydra["title"] in supported_property: + prop_title = supported_property[hydra["title"]][0]["@value"] + prop_read = supported_property[hydra["readable"]][0]["@value"] + prop_require = supported_property[hydra["required"]][0]["@value"] + prop_write = supported_property[hydra["writeable"]][0]["@value"] + + prop_ = HydraClassProp( + prop=prop_id, + title=prop_title, + required=prop_require, + read=prop_read, + write=prop_write, + ) return prop_ @@ -340,22 +377,22 @@ def create_link(supported_property: Dict[str, Any]) -> HydraLink: :param supported_property: expanded Property :return: instance of HydraLink """ - prop_title = 'The default Link title' - prop_desc = 'The default Link description' + prop_title = "The default Link title" + prop_desc = "The default Link description" - prop_id = check_namespace(supported_property['@id']) - if hydra['description'] in supported_property: - prop_desc = supported_property[hydra['description']] - if hydra['title'] in supported_property: - prop_title = supported_property[hydra['title']][0]['@value'] + prop_id = check_namespace(supported_property["@id"]) + if hydra["description"] in supported_property: + prop_desc = supported_property[hydra["description"]] + if hydra["title"] in supported_property: + prop_title = supported_property[hydra["title"]][0]["@value"] - prop_domain = check_namespace(supported_property[rdfs['domain']][0]['@id']) - prop_range = check_namespace(supported_property[rdfs['range']][0]['@id']) + prop_domain = check_namespace(supported_property[rdfs["domain"]][0]["@id"]) + prop_range = check_namespace(supported_property[rdfs["range"]][0]["@id"]) link_ = HydraLink(prop_id, prop_title, prop_desc, prop_domain, prop_range) - if hydra['supportedOperation'] in supported_property: - for operations in supported_property[hydra['supportedOperation']]: + if hydra["supportedOperation"] in supported_property: + for operations in supported_property[hydra["supportedOperation"]]: operation = create_operation(operations) link_.add_supported_op(operation) @@ -369,8 +406,6 @@ def check_namespace(id_: str = None) -> str: :param id_ The id to check :return: correct url """ - if id_.find(DocUrl.doc_url) == -1 and id_ != "null" and id_.find('#') != -1: - id_ = "{}{}".format(DocUrl.doc_url, id_.split('#')[-1]) + if id_.find(DocUrl.doc_url) == -1 and id_ != "null" and id_.find("#") != -1: + id_ = "{}{}".format(DocUrl.doc_url, id_.split("#")[-1]) return id_ - - diff --git a/hydra_python_core/doc_writer.py b/hydra_python_core/doc_writer.py index 79fe071..55ace8b 100644 --- a/hydra_python_core/doc_writer.py +++ b/hydra_python_core/doc_writer.py @@ -1,13 +1,21 @@ """API Doc templates generator.""" from typing import Any, Dict, List, Optional, Union from urllib.parse import quote, urljoin +import re class HydraDoc: """Class for an API Doc.""" - def __init__(self, API: str, title: str, desc: str, - entrypoint: str, base_url: str, doc_name: str) -> None: + def __init__( + self, + API: str, + title: str, + desc: str, + entrypoint: str, + base_url: str, + doc_name: str, + ) -> None: """Initialize the APIDoc.""" self.API = API self.entrypoint_endpoint = entrypoint @@ -24,8 +32,7 @@ def __init__(self, API: str, title: str, desc: str, self.doc_name = doc_name self.doc_url = DocUrl(self.base_url, self.API, self.doc_name) - def add_supported_class( - self, class_: 'HydraClass') -> None: + def add_supported_class(self, class_: "HydraClass") -> None: """Add a new supportedClass. Raises: @@ -35,11 +42,13 @@ def add_supported_class( if not isinstance(class_, HydraClass): raise TypeError("Type is not ") self.parsed_classes[class_.path] = { - "context": Context(address="{}{}".format(self.base_url, self.API), class_=class_), + "context": Context( + address="{}{}".format(self.base_url, self.API), class_=class_ + ), "class": class_, } - def add_supported_collection(self, collection_: 'HydraCollection') -> None: + def add_supported_collection(self, collection_: "HydraCollection") -> None: """Add a supported Collection Raises: @@ -51,10 +60,13 @@ def add_supported_collection(self, collection_: 'HydraCollection') -> None: raise TypeError("Type is not ") self.collections[collection_.path] = { - "context": Context(address="{}{}".format(self.base_url, self.API), - collection=collection_), "collection": collection_} + "context": Context( + address="{}{}".format(self.base_url, self.API), collection=collection_ + ), + "collection": collection_, + } - def add_possible_status(self, status: Union['HydraStatus', 'HydraError']) -> None: + def add_possible_status(self, status: Union["HydraStatus", "HydraError"]) -> None: """Add a new possibleStatus. Raises: @@ -68,20 +80,24 @@ def add_possible_status(self, status: Union['HydraStatus', 'HydraError']) -> Non def add_baseCollection(self) -> None: """Add Collection class to the API Doc.""" collection = HydraClass( - _id="http://www.w3.org/ns/hydra/core#Collection", title="Collection", desc=None) + _id="http://www.w3.org/ns/hydra/core#Collection", + title="Collection", + desc=None, + ) member = HydraClassProp( - "http://www.w3.org/ns/hydra/core#member", "members", False, False, None) + "http://www.w3.org/ns/hydra/core#member", "members", False, False, None + ) collection.add_supported_prop(member) self.other_classes.append(collection) def add_baseResource(self) -> None: """Add Resource class to the API Doc.""" resource = HydraClass( - _id="http://www.w3.org/ns/hydra/core#Resource", title="Resource", desc=None) + _id="http://www.w3.org/ns/hydra/core#Resource", title="Resource", desc=None + ) self.other_classes.append(resource) - def add_to_context( - self, key: str, value: Union[Dict[str, str], str]) -> None: + def add_to_context(self, key: str, value: Union[Dict[str, str], str]) -> None: """Add entries to the vocabs context.""" self.context.add(key, value) @@ -92,15 +108,14 @@ def gen_EntryPoint(self) -> None: if self.parsed_classes[class_]["class"].endpoint: self.entrypoint.add_Class(self.parsed_classes[class_]["class"]) for collection in self.collections: - self.entrypoint.add_Collection( - self.collections[collection]["collection"]) + self.entrypoint.add_Collection(self.collections[collection]["collection"]) def generate(self) -> Dict[str, Any]: """Get the Hydra API Doc as a python dict.""" - parsed_classes = [self.parsed_classes[key]["class"] - for key in self.parsed_classes] - collections = [self.collections[key]["collection"] - for key in self.collections] + parsed_classes = [ + self.parsed_classes[key]["class"] for key in self.parsed_classes + ] + collections = [self.collections[key]["collection"] for key in self.collections] doc = { "@context": self.context.generate(), "@id": "{}/{}".format(urljoin(self.base_url, self.API), self.doc_name), @@ -109,18 +124,29 @@ def generate(self) -> Dict[str, Any]: "description": self.desc, "entrypoint": urljoin(self.base_url, self.entrypoint_endpoint), "supportedClass": [ - x.generate() for x in parsed_classes + self.other_classes + collections + [self.entrypoint]], - "possibleStatus": [status.generate() for status in self.possible_status] + x.generate() + for x in parsed_classes + + self.other_classes + + collections + + [self.entrypoint] + ], + "possibleStatus": [status.generate() for status in self.possible_status], } return doc -class HydraClass(): +class HydraClass: """Template for a new class.""" def __init__( - self, title: str, desc: str, path: str = None, - endpoint: bool = False, sub_classof: None = None, _id: str = None) -> None: + self, + title: str, + desc: str, + path: str = None, + endpoint: bool = False, + sub_classof: None = None, + _id: str = None, + ) -> None: """Initialize the Hydra_Class.""" self.id_ = _id if _id is not None else "{}{}".format(DocUrl.doc_url, title) self.title = title @@ -134,7 +160,8 @@ def __init__( self.parents = sub_classof def add_supported_prop( - self, prop: Union['HydraClassProp', 'EntryPointClass', 'EntryPointCollection']) -> None: + self, prop: Union["HydraClassProp", "EntryPointClass", "EntryPointCollection"] + ) -> None: """Add a new supportedProperty. Raises: @@ -143,12 +170,12 @@ def add_supported_prop( """ if not isinstance( - prop, (HydraClassProp, EntryPointClass, EntryPointCollection)): + prop, (HydraClassProp, EntryPointClass, EntryPointCollection) + ): raise TypeError("Type is not ") self.supportedProperty.append(prop) - def add_supported_op( - self, op: Union['EntryPointOp', 'HydraClassOp']) -> None: + def add_supported_op(self, op: Union["EntryPointOp", "HydraClassOp"]) -> None: """Add a new supportedOperation. Raises: @@ -174,17 +201,18 @@ def generate(self) -> Dict[str, Any]: return class_ -class HydraClassProp(): +class HydraClassProp: """Template for a new property.""" - def __init__(self, - prop: Union[str, 'HydraLink'], - title: str, - read: bool, - write: bool, - required: bool, - desc: str = "", - ) -> None: + def __init__( + self, + prop: Union[str, "HydraLink"], + title: str, + read: bool, + write: bool, + required: bool, + desc: str = "", + ) -> None: """Initialize the Hydra_Prop.""" self.prop = prop self.title = title @@ -200,7 +228,7 @@ def generate(self) -> Dict[str, Any]: "title": self.title, "required": self.required, "readable": self.read, - "writeable": self.write + "writeable": self.write, } if isinstance(self.prop, HydraLink): prop["property"] = self.prop.generate() @@ -211,18 +239,19 @@ def generate(self) -> Dict[str, Any]: return prop -class HydraClassOp(): +class HydraClassOp: """Template for a new supportedOperation.""" - def __init__(self, - title: str, - method: str, - expects: Optional[str], - returns: Optional[str], - expects_header: List[str] = [], - returns_header: List[str] = [], - possible_status: List[Union['HydraStatus', 'HydraError']] = [], - ) -> None: + def __init__( + self, + title: str, + method: str, + expects: Optional[str], + returns: Optional[str], + expects_header: List[str] = [], + returns_header: List[str] = [], + possible_status: List[Union["HydraStatus", "HydraError"]] = [], + ) -> None: """Initialize the Hydra_Prop.""" self.title = title self.method = method @@ -254,65 +283,114 @@ def generate(self) -> Dict[str, Any]: "returns": self.returns, "expectsHeader": self.expects_header, "returnsHeader": self.returns_header, - "possibleStatus": [status.generate() for status in self.possible_status] + "possibleStatus": [status.generate() for status in self.possible_status], } return op -class HydraCollection(): +class HydraCollection: """Class for Hydra Collection.""" def __init__( - self, - collection_name: str = None, - collection_path: str = None, - collection_description: str = None, - manages: Union[Dict[str, Any], List] = None, - get: bool = True, post: bool = True, put: bool = True, delete: bool = True) -> None: + self, + collection_name: str = None, + collection_path: str = None, + collection_description: str = None, + manages: Union[Dict[str, Any], List] = None, + get: bool = True, + post: bool = True, + put: bool = True, + delete: bool = True, + ) -> None: """Generate Collection for related resources.""" - self.collection_id = "{}{}".format(DocUrl.doc_url, quote(collection_name, safe='')) + self.collection_id = "{}{}".format( + DocUrl.doc_url, quote(collection_name, safe="") + ) self.name = collection_name self.collection_description = collection_description self.path = collection_path if collection_path else self.name self.supportedOperation = list() # type: List - self.supportedProperty = [HydraClassProp("http://www.w3.org/ns/hydra/core#member", - "members", - True, True, False, - "The members of {}".format(collection_name))] + self.supportedProperty = [ + HydraClassProp( + "http://www.w3.org/ns/hydra/core#member", + "members", + False, + False, + False, + "The members of {}".format(collection_name), + ) + ] + self.manages = manages if get: - get_op = HydraCollectionOp("_:{}_retrieve".format(self.name), - "http://schema.org/FindAction", - "GET", "Retrieves all the members of {}".format(self.name), - None, self.manages['object'], [], [], []) + get_op = HydraCollectionOp( + "_:{}_retrieve".format(self.name), + "http://schema.org/FindAction", + "GET", + "Retrieves all the members of {}".format(self.name), + None, + self.manages["object"], + [], + [], + [], + ) self.supportedOperation.append(get_op) if put: - put_op = HydraCollectionOp("_:{}_create".format(self.name), "http://schema.org/AddAction", - "PUT", "Create new member in {}".format(self.name), - self.manages['object'], self.manages['object'], [], [], - [HydraStatus(code=201, desc="A new member in {} created".format(self.name))] - ) + put_op = HydraCollectionOp( + "_:{}_create".format(self.name), + "http://schema.org/AddAction", + "PUT", + "Create new member in {}".format(self.name), + self.manages["object"], + self.manages["object"], + [], + [], + [ + HydraStatus( + code=201, desc="A new member in {} created".format(self.name) + ) + ], + ) self.supportedOperation.append(put_op) if post: - post_op = HydraCollectionOp("_:{}_update".format(self.name), - "http://schema.org/UpdateAction", - "POST", "Update member of {} ".format(self.name), - self.manages['object'], self.manages['object'], [], [], - [HydraStatus(code=200, desc="If the entity was updated" - "from {}.".format(self.name))] - ) + post_op = HydraCollectionOp( + "_:{}_update".format(self.name), + "http://schema.org/UpdateAction", + "POST", + "Update member of {} ".format(self.name), + self.manages["object"], + self.manages["object"], + [], + [], + [ + HydraStatus( + code=200, + desc="If the entity was updated" "from {}.".format(self.name), + ) + ], + ) self.supportedOperation.append(post_op) if delete: - delete_op = HydraCollectionOp("_:{}_delete".format(self.name), - "http://schema.org/DeleteAction", - "DELETE", "Delete member of {} ".format(self.name), - self.manages['object'], self.manages['object'], [], [], - [HydraStatus(code=200, desc="If entity was deleted" - "successfully from {}.".format(self.name))] - ) + delete_op = HydraCollectionOp( + "_:{}_delete".format(self.name), + "http://schema.org/DeleteAction", + "DELETE", + "Delete member of {} ".format(self.name), + self.manages["object"], + self.manages["object"], + [], + [], + [ + HydraStatus( + code=200, + desc="If entity was deleted" + "successfully from {}.".format(self.name), + ) + ], + ) self.supportedOperation.append(delete_op) def generate(self) -> Dict[str, Any]: @@ -326,7 +404,7 @@ def generate(self) -> Dict[str, Any]: "description": self.collection_description, "supportedOperation": [x.generate() for x in self.supportedOperation], "supportedProperty": [x.generate() for x in self.supportedProperty], - "manages": self.manages + "manages": self.manages, } return collection @@ -334,17 +412,18 @@ def generate(self) -> Dict[str, Any]: class HydraCollectionOp(HydraClassOp): """Operation class for Collection operations.""" - def __init__(self, - id_: str, - type_: str, - method: str, - desc: str, - expects: Optional[str], - returns: Optional[str], - expects_header: List[str] = [], - returns_header: List[str] = [], - possible_status: List[Union['HydraStatus', 'HydraError']] = [], - ) -> None: + def __init__( + self, + id_: str, + type_: str, + method: str, + desc: str, + expects: Optional[str], + returns: Optional[str], + expects_header: List[str] = [], + returns_header: List[str] = [], + possible_status: List[Union["HydraStatus", "HydraError"]] = [], + ) -> None: """Create method.""" self.id_ = id_ self.type_ = type_ @@ -367,28 +446,34 @@ def generate(self) -> Dict[str, Any]: "returns": self.returns, "expectsHeader": self.expects_header, "returnsHeader": self.returns_header, - "possibleStatus": [status.generate() for status in self.possible_status] + "possibleStatus": [status.generate() for status in self.possible_status], } return object_ -class HydraEntryPoint(): +class HydraEntryPoint: """Template for a new entrypoint.""" def __init__(self, base_url: str, entrypoint: str) -> None: """Initialize the Entrypoint.""" self.url = base_url self.api = entrypoint - self.entrypoint = HydraClass("EntryPoint", "The main entry point or homepage of the API.", - _id="{}#EntryPoint".format(urljoin(self.url, self.api))) - self.entrypoint.add_supported_op(EntryPointOp( - "_:entry_point".format(base_url), "GET", "The APIs main entry point.", None, None, - type_="{}/{}#EntryPoint".format(base_url, entrypoint))) - self.context = Context( - "{}{}".format( - base_url, - entrypoint), - entrypoint=self) + self.entrypoint = HydraClass( + "EntryPoint", + "The main entry point or homepage of the API.", + _id="{}?resource=EntryPoint".format(urljoin(self.url, self.api)), + ) + self.entrypoint.add_supported_op( + EntryPointOp( + "_:entry_point".format(base_url), + "GET", + "The APIs main entry point.", + None, + None, + type_="{}/{}?resource=EntryPoint".format(base_url, entrypoint), + ) + ) + self.context = Context("{}{}".format(base_url, entrypoint), entrypoint=self) self.collections: List[EntryPointCollection] = [] @@ -403,8 +488,9 @@ def add_Class(self, class_: HydraClass) -> None: raise TypeError("Type is not ") entrypoint_class = EntryPointClass(class_) self.entrypoint.add_supported_prop(entrypoint_class) - self.context.add(entrypoint_class.name, { - "@id": entrypoint_class.id_, "@type": "@id"}) + self.context.add( + entrypoint_class.name, {"@id": entrypoint_class.id_, "@type": "@id"} + ) def add_Collection(self, collection: HydraCollection) -> None: """Add supportedProperty to the EntryPoint. @@ -418,48 +504,48 @@ def add_Collection(self, collection: HydraCollection) -> None: entrypoint_collection = EntryPointCollection(collection) self.collections.append(entrypoint_collection.generate()) self.entrypoint.add_supported_prop(entrypoint_collection) - self.context.add(entrypoint_collection.name, { - "@id": entrypoint_collection.id_, "@type": "@id"}) + self.context.add( + entrypoint_collection.name, + {"@id": entrypoint_collection.id_, "@type": "@id"}, + ) def generate(self) -> Dict[str, Any]: """Get as a Python dict.""" return self.entrypoint.generate() def get(self) -> Dict[str, str]: - """Create the EntryPoint object to be returnd for the get function.""" + """Create the EntryPoint object to be returned for the get function.""" object_ = { - "@context": "{}{}/contexts/EntryPoint.jsonld".format(self.url,self.api), - "@id": "{}{}".format(self.url,self.api), + "@context": "{}{}/contexts/EntryPoint.jsonld".format(self.url, self.api), + "@id": "{}{}".format(self.url, self.api), "@type": "EntryPoint", - } for item in self.entrypoint.supportedProperty: uri = item.id_ if item.generate() in self.collections: collection_returned = item.generate() - collection_id = uri.replace( - "{}EntryPoint".format(DocUrl.doc_url), "{}{}".format(self.url,self.api)) + collection_id = uri collection_to_append = { "@id": collection_id, - 'title': collection_returned['hydra:title'], - '@type': "Collection", - "supportedOperation": collection_returned['property']['supportedOperation'], - "manages": collection_returned['property']['manages'] + "title": collection_returned["hydra:title"], + "@type": "Collection", + "supportedOperation": collection_returned["property"][ + "supportedOperation" + ], + "manages": collection_returned["property"]["manages"], } if "collections" in object_: - object_['collections'].append(collection_to_append) + object_["collections"].append(collection_to_append) else: - object_['collections'] = [] - object_['collections'].append(collection_to_append) + object_["collections"] = [] + object_["collections"].append(collection_to_append) else: - object_[item.name] = uri.replace( - "{}EntryPoint".format(DocUrl.doc_url), "{}{}".format(self.url,self.api)) - + object_[item.name] = uri return object_ -class EntryPointCollection(): +class EntryPointCollection: """Class for a Collection Entry to the EntryPoint object.""" def __init__(self, collection: HydraCollection) -> None: @@ -468,9 +554,15 @@ def __init__(self, collection: HydraCollection) -> None: self.supportedOperation = collection.supportedOperation self.manages = collection.manages if collection.path: - self.id_ = "{}EntryPoint/{}".format(DocUrl.doc_url, quote(collection.path, safe='')) + self.id_ = "{}EntryPoint/{}".format( + DocUrl.doc_url, quote(collection.path, safe="") + ) + self.base_url = DocUrl.doc_url else: - self.id_ = "{}EntryPoint/{}".format(DocUrl.doc_url, quote(self.name, safe='')) + self.id_ = "{}EntryPoint/{}".format( + DocUrl.doc_url, quote(collection.path, safe="") + ) + self.base_url = DocUrl.doc_url def generate(self) -> Dict[str, Any]: """Get as a python dict.""" @@ -479,30 +571,39 @@ def generate(self) -> Dict[str, Any]: "@id": self.id_, "@type": "hydra:Link", "label": self.name, - "description": "The {} collection".format(self.name, ), + "description": "The {} collection".format( + self.name, + ), "domain": "{}EntryPoint".format(DocUrl.doc_url), "range": "{}{}".format(DocUrl.doc_url, self.name), "manages": self.manages, "supportedOperation": [], }, "hydra:title": self.name.lower(), - "hydra:description": "The {} collection".format(self.name, ), + "hydra:description": "The {} collection".format( + self.name, + ), "required": None, "readable": True, - "writeable": False + "writeable": False, } # type: Dict[str, Any] for op in self.supportedOperation: - operation = EntryPointOp(op.id_.lower(), op.method, - op.desc, op.expects, op.returns, - op.expects_header, op.returns_header, - op.possible_status, - type_=op.type_) - object_["property"]["supportedOperation"].append( - operation.generate()) + operation = EntryPointOp( + op.id_.lower(), + op.method, + op.desc, + op.expects, + op.returns, + op.expects_header, + op.returns_header, + op.possible_status, + type_=op.type_, + ) + object_["property"]["supportedOperation"].append(operation.generate()) return object_ -class EntryPointClass(): +class EntryPointClass: """Class for a Operation Entry to the EntryPoint object.""" def __init__(self, class_: HydraClass) -> None: @@ -512,8 +613,10 @@ def __init__(self, class_: HydraClass) -> None: self.supportedOperation = class_.supportedOperation if class_.path: self.id_ = "{}EntryPoint/{}".format(DocUrl.doc_url, class_.path) + self.base_url = DocUrl.doc_url else: - self.id_ = "{}EntryPoint/{}".format(DocUrl.doc_url, self.name) + self.id_ = "{}/EntryPoint/{}".format(DocUrl.doc_url, self.name) + self.base_url = DocUrl.doc_url def generate(self) -> Dict[str, Any]: """Get as Python Dict.""" @@ -523,41 +626,48 @@ def generate(self) -> Dict[str, Any]: "@type": "hydra:Link", "label": self.name, "description": self.desc, - "domain": "{}EntryPoint".format(DocUrl.doc_url), + "domain": "{}EntryPoint".format(self.base_url), "range": "{}{}".format(DocUrl.doc_url, self.name), - "supportedOperation": [] + "supportedOperation": [], }, "hydra:title": self.name.lower(), "hydra:description": "The {} Class".format(self.name), "required": None, "readable": True, - "writeable": False + "writeable": False, } # type: Dict[str, Any] for op in self.supportedOperation: - operation = EntryPointOp(op.title.lower(), op.method, - None, op.expects, op.returns, op.expects_header, - op.returns_header, op.possible_status, - label=op.title) - object_["property"]["supportedOperation"].append( - operation.generate()) + operation = EntryPointOp( + op.title.lower(), + op.method, + None, + op.expects, + op.returns, + op.expects_header, + op.returns_header, + op.possible_status, + label=op.title, + ) + object_["property"]["supportedOperation"].append(operation.generate()) return object_ -class EntryPointOp(): +class EntryPointOp: """supportedOperation for EntryPoint.""" - def __init__(self, - id_: str, - method: str, - desc: str, - expects: Optional[str], - returns: Optional[str], - expects_header: List[str] = [], - returns_header: List[str] = [], - possible_status: List[Union['HydraStatus', 'HydraError']] = [], - type_: Optional[str] = None, - label: str = "", - ) -> None: + def __init__( + self, + id_: str, + method: str, + desc: str, + expects: Optional[str], + returns: Optional[str], + expects_header: List[str] = [], + returns_header: List[str] = [], + possible_status: List[Union["HydraStatus", "HydraError"]] = [], + type_: Optional[str] = None, + label: str = "", + ) -> None: """Create method.""" self.id_ = id_ self.method = method @@ -592,7 +702,7 @@ def generate(self) -> Dict[str, Any]: "returns": self.returns, "expectsHeader": self.expects_header, "returnsHeader": self.returns_header, - "possibleStatus": [status.generate() for status in self.possible_status] + "possibleStatus": [status.generate() for status in self.possible_status], } if self.type_ is not None: prop["@type"] = self.type_ @@ -601,13 +711,10 @@ def generate(self) -> Dict[str, Any]: return prop -class IriTemplateMapping(): +class IriTemplateMapping: """Class for hydra IriTemplateMapping""" - def __init__(self, - variable: str, - prop: str, - required: bool = False): + def __init__(self, variable: str, prop: str, required: bool = False): self.variable = variable self.prop = prop self.required = required @@ -618,18 +725,20 @@ def generate(self) -> Dict[str, Any]: "@type": "hydra:IriTemplateMapping", "hydra:variable": self.variable, "hydra:property": self.prop, - "hydra:required": self.required + "hydra:required": self.required, } return iri_template_mapping -class HydraIriTemplate(): +class HydraIriTemplate: """Class for hydra IriTemplates""" - def __init__(self, - template: str, - iri_mapping: List[IriTemplateMapping] = [], - basic_representation: bool = True): + def __init__( + self, + template: str, + iri_mapping: List[IriTemplateMapping] = [], + basic_representation: bool = True, + ): self.template = template if basic_representation: self.variable_rep = "hydra:BasicRepresentation" @@ -639,20 +748,22 @@ def __init__(self, def generate(self) -> Dict[str, Any]: """Get IriTemplate as a python dict""" - base_url = DocUrl.doc_url.rsplit('/',2)[0] + base_url = DocUrl.doc_url.rsplit("/", 2)[0] iri_template = { "@type": "hydra:IriTemplate", - "hydra:template": "{}{}".format(base_url,self.template), + "hydra:template": "{}{}".format(base_url, self.template), "hydra:variableRepresentation": self.variable_rep, - "hydra:mapping": [x.generate() for x in self.mapping] + "hydra:mapping": [x.generate() for x in self.mapping], } return iri_template -class HydraStatus(): +class HydraStatus: """Class for possibleStatus in Hydra Doc.""" - def __init__(self, code: int, id_: str = None, title: str = "", desc: str = "") -> None: + def __init__( + self, code: int, id_: str = None, title: str = "", desc: str = "" + ) -> None: """Create method.""" self.code = code self.id_ = id_ @@ -676,7 +787,9 @@ def generate(self, status_type: str = "Status") -> Dict[str, Any]: class HydraError(HydraStatus): """Class for Hydra Error to represent error details.""" - def __init__(self, code: int, id_: str = None, title: str = "", desc: str = "") -> None: + def __init__( + self, code: int, id_: str = None, title: str = "", desc: str = "" + ) -> None: """Create method""" super().__init__(code, id_, title, desc) @@ -686,11 +799,17 @@ def generate(self) -> Dict[str, Any]: return error -class HydraLink(): +class HydraLink: """Template for a link property.""" + def __init__( - self, id_: str, title: str = "", - desc: str = "", domain: str = "", range_: str = "") -> None: + self, + id_: str, + title: str = "", + desc: str = "", + domain: str = "", + range_: str = "", + ) -> None: """Initialize the Hydra_Link.""" self.id_ = id_ if "http" in id_ else "{}{}".format(DocUrl.doc_url, id_) self.range = range_ @@ -699,8 +818,7 @@ def __init__( self.domain = domain self.supportedOperation = list() # type: List - def add_supported_op( - self, op: Union['EntryPointOp', 'HydraClassOp']) -> None: + def add_supported_op(self, op: Union["EntryPointOp", "HydraClassOp"]) -> None: """Add a new supportedOperation. Raises: @@ -725,22 +843,26 @@ def generate(self) -> Dict[str, Any]: return link -class Context(): +class Context: """Class for JSON-LD context.""" - def __init__(self, - address: str, - class_: Optional[HydraClass] = None, - collection: Optional[HydraCollection] = None, - entrypoint: Optional[HydraEntryPoint] = None, - ) -> None: + def __init__( + self, + address: str, + class_: Optional[HydraClass] = None, + collection: Optional[HydraCollection] = None, + entrypoint: Optional[HydraEntryPoint] = None, + ) -> None: """Initialize context.""" # NOTE: adders is a dictionary containing additional # context elements to the base Hydra context if class_ is not None: - self.context = {"hydra": "http://www.w3.org/ns/hydra/core#", - "members": "http://www.w3.org/ns/hydra/core#member", "object": "http://schema.org/object", - class_.title: class_.id_} # type: Dict[str, Any] + self.context = { + "hydra": "http://www.w3.org/ns/hydra/core#", + "members": "http://www.w3.org/ns/hydra/core#member", + "object": "http://schema.org/object", + class_.title: class_.id_, + } # type: Dict[str, Any] for prop in class_.supportedProperty: if isinstance(prop.prop, HydraLink): self.context[prop.title] = prop.prop.id_ @@ -748,58 +870,37 @@ def __init__(self, self.context[prop.title] = prop.prop elif collection is not None: - self.context = {"hydra": "http://www.w3.org/ns/hydra/core#", - "members": "http://www.w3.org/ns/hydra/core#member", - collection.name: collection.collection_id} + self.context = { + "hydra": "http://www.w3.org/ns/hydra/core#", + "members": "http://www.w3.org/ns/hydra/core#member", + collection.name: collection.collection_id, + } elif entrypoint is not None: + entrypoint = "{}EntryPoint".format(DocUrl.doc_url) self.context = { - "EntryPoint": "{}EntryPoint".format(DocUrl.doc_url), + "EntryPoint": entrypoint, } else: self.context = { "hydra": "http://www.w3.org/ns/hydra/core#", - "property": { - "@type": "@id", - "@id": "hydra:property" - }, + "property": {"@type": "@id", "@id": "hydra:property"}, "supportedClass": "hydra:supportedClass", "supportedProperty": "hydra:supportedProperty", "supportedOperation": "hydra:supportedOperation", "label": "rdfs:label", "rdf": "http://www.w3.org/1999/02/22-rdf-syntax-ns#", - "domain": { - "@type": "@id", - "@id": "rdfs:domain" - }, + "domain": {"@type": "@id", "@id": "rdfs:domain"}, "ApiDocumentation": "hydra:ApiDocumentation", - "range": { - "@type": "@id", - "@id": "rdfs:range" - }, + "range": {"@type": "@id", "@id": "rdfs:range"}, "rdfs": "http://www.w3.org/2000/01/rdf-schema#", "title": "hydra:title", - "expects": { - "@type": "@id", - "@id": "hydra:expects" - }, - "returns": { - "@id": "hydra:returns", - "@type": "@id" - }, - "entrypoint": { - "@id": "hydra:entrypoint", - "@type": "@id" - }, - "object": { - "@id": "hydra:object", - "@type": "@id" - }, - "subject": { - "@id": "hydra:subject", - "@type": "@id" - }, + "expects": {"@type": "@id", "@id": "hydra:expects"}, + "returns": {"@id": "hydra:returns", "@type": "@id"}, + "entrypoint": {"@id": "hydra:entrypoint", "@type": "@id"}, + "object": {"@id": "hydra:object", "@type": "@id"}, + "subject": {"@id": "hydra:subject", "@type": "@id"}, "readable": "hydra:readable", "writeable": "hydra:writeable", "possibleStatus": "hydra:possibleStatus", @@ -810,11 +911,8 @@ def __init__(self, "expectsHeader": "hydra:expectsHeader", "returnsHeader": "hydra:returnsHeader", "manages": "hydra:manages", - "subClassOf": { - "@id": "rdfs:subClassOf", - "@type": "@id" - }, - "search": "hydra:search" + "subClassOf": {"@id": "rdfs:subClassOf", "@type": "@id"}, + "search": "hydra:search", } def createContext(self, object_: Dict[str, Any]) -> None: @@ -837,7 +935,7 @@ def add(self, key: str, value: Union[Dict[str, str], str]) -> None: class DocUrl: - doc_url = '' + doc_url = "" def __init__(self, base_url: str, api_name: str, doc_name: str) -> None: - DocUrl.doc_url = "{}/{}#".format(urljoin(base_url, api_name), doc_name) + DocUrl.doc_url = "{}/{}?resource=".format(urljoin(base_url, api_name), doc_name) diff --git a/hydra_python_core/namespace.py b/hydra_python_core/namespace.py index 9d82335..4e2ed39 100644 --- a/hydra_python_core/namespace.py +++ b/hydra_python_core/namespace.py @@ -11,9 +11,7 @@ "entrypoint": hydraNamespace + "entrypoint", "supportedClass": hydraNamespace + "supportedClass", "title": hydraNamespace + "title", - "ApiDocumentation": hydraNamespace + "ApiDocumentation", - "mapping": hydraNamespace + "mapping", "object": hydraNamespace + "object", "property": hydraNamespace + "property", @@ -21,33 +19,27 @@ "template": hydraNamespace + "template", "variable": hydraNamespace + "variable", "variableRepresentation": hydraNamespace + "variableRepresentation", - "BasicRepresentation": hydraNamespace + "BasicRepresentation", "IriTemplate": hydraNamespace + "IriTemplate", "IriTemplateMapping": hydraNamespace + "IriTemplateMapping", "Link": hydraNamespace + "Link", "TemplatedLink": hydraNamespace + "TemplatedLink", "VariableRepresentation": hydraNamespace + "VariableRepresentation", - "collection": hydraNamespace + "collection", "manages": hydraNamespace + "manages", "member": hydraNamespace + "member", "pageIndex": hydraNamespace + "pageIndex", "pageReference": hydraNamespace + "pageReference", "totalItems": hydraNamespace + "totalItems", - "Collection": hydraNamespace + "Collection", "PartialCollectionView": hydraNamespace + "PartialCollectionView", - "readable": hydraNamespace + "readable", "required": hydraNamespace + "required", "supportedOperation": hydraNamespace + "supportedOperation", "supportedProperty": hydraNamespace + "supportedProperty", "writeable": hydraNamespace + "writeable", - "Class": hydraNamespace + "Class", "SupportedProperty": hydraNamespace + "SupportedProperty", - "expects": hydraNamespace + "expects", "expectsHeader": hydraNamespace + "expectsHeader", "method": hydraNamespace + "method", @@ -55,28 +47,24 @@ "returns": hydraNamespace + "returns", "returnsHeader": hydraNamespace + "returnsHeader", "statusCode": hydraNamespace + "statusCode", - "Operation": hydraNamespace + "Operation", "Status": hydraNamespace + "Status", - "operation": hydraNamespace + "operation", - "Resource": hydraNamespace + "Resource", - "first": hydraNamespace + "first", "freetextQuery": hydraNamespace + "freetextQuery", "last": hydraNamespace + "last", "next": hydraNamespace + "next", "previous": hydraNamespace + "previous", "search": hydraNamespace + "search", - "view": hydraNamespace + "view" + "view": hydraNamespace + "view", } rdfNamespace = "http://www.w3.org/1999/02/22-rdf-syntax-ns#" rdf = { "namespace": rdfNamespace, "Property": rdfNamespace + "Property", - "type": rdfNamespace + "type" + "type": rdfNamespace + "type", } rdfsNamespace = "http://www.w3.org/2000/01/rdf-schema#" @@ -85,5 +73,5 @@ "comment": rdfsNamespace + "comment", "domain": rdfsNamespace + "domain", "label": rdfsNamespace + "label", - "range": rdfsNamespace + "range" -} \ No newline at end of file + "range": rdfsNamespace + "range", +} diff --git a/setup.cfg b/setup.cfg new file mode 100644 index 0000000..1d36346 --- /dev/null +++ b/setup.cfg @@ -0,0 +1,2 @@ +[flake8] +max-line-length = 88 \ No newline at end of file diff --git a/setup.py b/setup.py index 7fb089d..6d093ca 100644 --- a/setup.py +++ b/setup.py @@ -4,7 +4,8 @@ # pip >=20 from pip._internal.network.session import PipSession from pip._internal.req import parse_requirements - install_requires = parse_requirements('requirements.txt', session=PipSession()) + + install_requires = parse_requirements("requirements.txt", session=PipSession()) dependencies = [str(package.requirement) for package in install_requires] except ImportError: try: @@ -16,20 +17,19 @@ from pip.download import PipSession from pip.req import parse_requirements - install_requires = parse_requirements('requirements.txt',session=PipSession()) + install_requires = parse_requirements("requirements.txt", session=PipSession()) dependencies = [str(package.req) for package in install_requires] - setup( name='hydra_python_core', version='0.2', packages=find_packages(), - license='MIT', - description='Core functions for Hydrus', - long_description=open('README.md').read(), + license="MIT", + description="Core functions for Hydrus", + long_description=open("README.md").read(), long_description_content_type="text/markdown", install_requires=dependencies, - url='https://github.com/HTTP-APIs/hydra-python-core', - zip_safe=False + url="https://github.com/HTTP-APIs/hydra-python-core", + zip_safe=False, ) diff --git a/tests/test_doc_maker.py b/tests/test_doc_maker.py index a03f8c2..a9a3ba5 100644 --- a/tests/test_doc_maker.py +++ b/tests/test_doc_maker.py @@ -390,5 +390,31 @@ def test_output(self, mock_status): self.assertIsInstance(obj[0], doc_writer.HydraStatus) +class TestFragments(unittest.TestCase): + """ + Test Class for checking fragments in id's + """ + def test_fragments(self): + server_url = "http://hydrus.com/" + api_name = "test_api" + self.doc = doc_writer_sample_output.doc + apidoc = doc_maker.create_doc(self.doc, server_url, api_name) + for class_ in apidoc.parsed_classes: + resource = apidoc.parsed_classes[class_]['class'] + resource_id = resource.id_ + regex = r"(\W*\?resource=\W*)([a-zA-Z]+)" + match_groups = re.search(regex, resource_id) + + assert match_groups.groups()[0] is not None + assert match_groups.groups()[1] == class_ + + for collection in apidoc.collections: + resource_id = apidoc.collections[collection]['collection'].collection_id + regex = r"(\W*\?resource=\W*)([a-zA-Z]+)" + match_groups = re.search(regex, resource_id) + + assert match_groups.groups()[0] is not None + assert match_groups.groups()[1] == collection + if __name__ == '__main__': unittest.main() diff --git a/tests/test_pep8.py b/tests/test_pep8.py index 9df150b..d87619b 100644 --- a/tests/test_pep8.py +++ b/tests/test_pep8.py @@ -1,15 +1,16 @@ """Run PEP8 code format checker on all python files except samples directory.""" import os +from os.path import dirname, join import unittest + import pep8 -from os.path import dirname, abspath class Pep8Test(unittest.TestCase): def test_pep8(self): """Test method to check PEP8 compliance over the entire project.""" - self.file_structure = dirname(dirname(abspath(__file__))) + self.file_structure = join(dirname(dirname(__file__)), 'hydra_python_core') print("Testing for PEP8 compliance of python files in {}".format( self.file_structure)) style = pep8.StyleGuide()