diff --git a/CHANGELOG.md b/CHANGELOG.md index ffb6c8f5d..da2009ef8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,7 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0 ### Additions +- Add support of properties indirect reference ($ref) resolution; Add support of inner properties direct and indirect reference resolution to its owner model/enum (#329). Thanks @p1-ra! - New `--meta` command line option for specifying what type of metadata should be generated: - `poetry` is the default value, same behavior you're used to in previous versions - `setup` will generate a pyproject.toml with no Poetry information, and instead create a `setup.py` with the diff --git a/end_to_end_tests/golden-record-custom/custom_e2e/models/a_model.py b/end_to_end_tests/golden-record-custom/custom_e2e/models/a_model.py index 9237d2428..97ae9d56d 100644 --- a/end_to_end_tests/golden-record-custom/custom_e2e/models/a_model.py +++ b/end_to_end_tests/golden-record-custom/custom_e2e/models/a_model.py @@ -27,6 +27,9 @@ class AModel: a_nullable_date: Optional[datetime.date] required_nullable: Optional[str] nullable_model: Optional[AModelNullableModel] + an_enum_indirect_ref: Union[Unset, AnEnum] = UNSET + direct_ref_to_itself: Union["AModel", Unset] = UNSET + indirect_ref_to_itself: Union["AModel", Unset] = UNSET nested_list_of_enums: Union[Unset, List[List[DifferentEnum]]] = UNSET a_not_required_date: Union[Unset, datetime.date] = UNSET attr_1_leading_digit: Union[Unset, str] = UNSET @@ -48,6 +51,18 @@ def to_dict(self) -> Dict[str, Any]: required_not_nullable = self.required_not_nullable model = self.model.to_dict() + an_enum_indirect_ref: Union[Unset, AnEnum] = UNSET + if not isinstance(self.an_enum_indirect_ref, Unset): + an_enum_indirect_ref = self.an_enum_indirect_ref + + direct_ref_to_itself: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.direct_ref_to_itself, Unset): + direct_ref_to_itself = self.direct_ref_to_itself.to_dict() + + indirect_ref_to_itself: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.indirect_ref_to_itself, Unset): + indirect_ref_to_itself = self.indirect_ref_to_itself.to_dict() + nested_list_of_enums: Union[Unset, List[Any]] = UNSET if not isinstance(self.nested_list_of_enums, Unset): nested_list_of_enums = [] @@ -94,6 +109,12 @@ def to_dict(self) -> Dict[str, Any]: "nullable_model": nullable_model, } ) + if an_enum_indirect_ref is not UNSET: + field_dict["an_enum_indirect_ref"] = an_enum_indirect_ref + if direct_ref_to_itself is not UNSET: + field_dict["direct_ref_to_itself"] = direct_ref_to_itself + if indirect_ref_to_itself is not UNSET: + field_dict["indirect_ref_to_itself"] = indirect_ref_to_itself if nested_list_of_enums is not UNSET: field_dict["nested_list_of_enums"] = nested_list_of_enums if a_not_required_date is not UNSET: @@ -137,6 +158,21 @@ def _parse_a_camel_date_time(data: Any) -> Union[datetime.datetime, datetime.dat model = AModelModel.from_dict(d.pop("model")) + an_enum_indirect_ref: Union[Unset, AnEnum] = UNSET + _an_enum_indirect_ref = d.pop("an_enum_indirect_ref", UNSET) + if not isinstance(_an_enum_indirect_ref, Unset): + an_enum_indirect_ref = AnEnum(_an_enum_indirect_ref) + + direct_ref_to_itself: Union[AModel, Unset] = UNSET + _direct_ref_to_itself = d.pop("direct_ref_to_itself", UNSET) + if not isinstance(_direct_ref_to_itself, Unset): + direct_ref_to_itself = AModel.from_dict(_direct_ref_to_itself) + + indirect_ref_to_itself: Union[AModel, Unset] = UNSET + _indirect_ref_to_itself = d.pop("indirect_ref_to_itself", UNSET) + if not isinstance(_indirect_ref_to_itself, Unset): + indirect_ref_to_itself = AModel.from_dict(_indirect_ref_to_itself) + nested_list_of_enums = [] _nested_list_of_enums = d.pop("nested_list_of_enums", UNSET) for nested_list_of_enums_item_data in _nested_list_of_enums or []: @@ -188,6 +224,9 @@ def _parse_a_camel_date_time(data: Any) -> Union[datetime.datetime, datetime.dat a_date=a_date, required_not_nullable=required_not_nullable, model=model, + an_enum_indirect_ref=an_enum_indirect_ref, + direct_ref_to_itself=direct_ref_to_itself, + indirect_ref_to_itself=indirect_ref_to_itself, nested_list_of_enums=nested_list_of_enums, a_nullable_date=a_nullable_date, a_not_required_date=a_not_required_date, diff --git a/end_to_end_tests/golden-record/my_test_api_client/models/a_model.py b/end_to_end_tests/golden-record/my_test_api_client/models/a_model.py index 9237d2428..97ae9d56d 100644 --- a/end_to_end_tests/golden-record/my_test_api_client/models/a_model.py +++ b/end_to_end_tests/golden-record/my_test_api_client/models/a_model.py @@ -27,6 +27,9 @@ class AModel: a_nullable_date: Optional[datetime.date] required_nullable: Optional[str] nullable_model: Optional[AModelNullableModel] + an_enum_indirect_ref: Union[Unset, AnEnum] = UNSET + direct_ref_to_itself: Union["AModel", Unset] = UNSET + indirect_ref_to_itself: Union["AModel", Unset] = UNSET nested_list_of_enums: Union[Unset, List[List[DifferentEnum]]] = UNSET a_not_required_date: Union[Unset, datetime.date] = UNSET attr_1_leading_digit: Union[Unset, str] = UNSET @@ -48,6 +51,18 @@ def to_dict(self) -> Dict[str, Any]: required_not_nullable = self.required_not_nullable model = self.model.to_dict() + an_enum_indirect_ref: Union[Unset, AnEnum] = UNSET + if not isinstance(self.an_enum_indirect_ref, Unset): + an_enum_indirect_ref = self.an_enum_indirect_ref + + direct_ref_to_itself: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.direct_ref_to_itself, Unset): + direct_ref_to_itself = self.direct_ref_to_itself.to_dict() + + indirect_ref_to_itself: Union[Unset, Dict[str, Any]] = UNSET + if not isinstance(self.indirect_ref_to_itself, Unset): + indirect_ref_to_itself = self.indirect_ref_to_itself.to_dict() + nested_list_of_enums: Union[Unset, List[Any]] = UNSET if not isinstance(self.nested_list_of_enums, Unset): nested_list_of_enums = [] @@ -94,6 +109,12 @@ def to_dict(self) -> Dict[str, Any]: "nullable_model": nullable_model, } ) + if an_enum_indirect_ref is not UNSET: + field_dict["an_enum_indirect_ref"] = an_enum_indirect_ref + if direct_ref_to_itself is not UNSET: + field_dict["direct_ref_to_itself"] = direct_ref_to_itself + if indirect_ref_to_itself is not UNSET: + field_dict["indirect_ref_to_itself"] = indirect_ref_to_itself if nested_list_of_enums is not UNSET: field_dict["nested_list_of_enums"] = nested_list_of_enums if a_not_required_date is not UNSET: @@ -137,6 +158,21 @@ def _parse_a_camel_date_time(data: Any) -> Union[datetime.datetime, datetime.dat model = AModelModel.from_dict(d.pop("model")) + an_enum_indirect_ref: Union[Unset, AnEnum] = UNSET + _an_enum_indirect_ref = d.pop("an_enum_indirect_ref", UNSET) + if not isinstance(_an_enum_indirect_ref, Unset): + an_enum_indirect_ref = AnEnum(_an_enum_indirect_ref) + + direct_ref_to_itself: Union[AModel, Unset] = UNSET + _direct_ref_to_itself = d.pop("direct_ref_to_itself", UNSET) + if not isinstance(_direct_ref_to_itself, Unset): + direct_ref_to_itself = AModel.from_dict(_direct_ref_to_itself) + + indirect_ref_to_itself: Union[AModel, Unset] = UNSET + _indirect_ref_to_itself = d.pop("indirect_ref_to_itself", UNSET) + if not isinstance(_indirect_ref_to_itself, Unset): + indirect_ref_to_itself = AModel.from_dict(_indirect_ref_to_itself) + nested_list_of_enums = [] _nested_list_of_enums = d.pop("nested_list_of_enums", UNSET) for nested_list_of_enums_item_data in _nested_list_of_enums or []: @@ -188,6 +224,9 @@ def _parse_a_camel_date_time(data: Any) -> Union[datetime.datetime, datetime.dat a_date=a_date, required_not_nullable=required_not_nullable, model=model, + an_enum_indirect_ref=an_enum_indirect_ref, + direct_ref_to_itself=direct_ref_to_itself, + indirect_ref_to_itself=indirect_ref_to_itself, nested_list_of_enums=nested_list_of_enums, a_nullable_date=a_nullable_date, a_not_required_date=a_not_required_date, diff --git a/end_to_end_tests/openapi.json b/end_to_end_tests/openapi.json index fcd83e460..db4ae351a 100644 --- a/end_to_end_tests/openapi.json +++ b/end_to_end_tests/openapi.json @@ -675,6 +675,15 @@ "required": ["an_enum_value", "aCamelDateTime", "a_date", "a_nullable_date", "required_nullable", "required_not_nullable", "model", "nullable_model"], "type": "object", "properties": { + "an_enum_indirect_ref": { + "$ref": "#/components/schemas/AnEnumDeeperIndirectReference" + }, + "direct_ref_to_itself": { + "$ref": "#/components/schemas/AModel" + }, + "indirect_ref_to_itself": { + "$ref": "#/components/schemas/AModelDeeperIndirectReference" + }, "an_enum_value": { "$ref": "#/components/schemas/AnEnum" }, @@ -716,7 +725,7 @@ "a_not_required_date": { "title": "A Nullable Date", "type": "string", - "format": "date", + "format": "date" }, "1_leading_digit": { "title": "Leading Digit", @@ -782,11 +791,23 @@ "description": "A Model for testing all the ways custom objects can be used ", "additionalProperties": false }, + "AModelIndirectReference": { + "$ref": "#/components/schemas/AModel" + }, + "AModelDeeperIndirectReference": { + "$ref": "#/components/schemas/AModelIndirectReference" + }, + "AnEnumIndirectReference": { + "$ref": "#/components/schemas/AnEnum" + }, "AnEnum": { "title": "AnEnum", "enum": ["FIRST_VALUE", "SECOND_VALUE"], "description": "For testing Enums in all the ways they can be used " }, + "AnEnumDeeperIndirectReference": { + "$ref": "#/components/schemas/AnEnumIndirectReference" + }, "AnIntEnum": { "title": "AnIntEnum", "enum": [-1, 1, 2], diff --git a/openapi_python_client/__init__.py b/openapi_python_client/__init__.py index b5ad8afeb..61ae6914b 100644 --- a/openapi_python_client/__init__.py +++ b/openapi_python_client/__init__.py @@ -3,19 +3,20 @@ import shutil import subprocess import sys +import urllib from enum import Enum from pathlib import Path -from typing import Any, Dict, Optional, Sequence, Union +from typing import Any, Dict, Optional, Sequence, Union, cast import httpcore import httpx -import yaml from jinja2 import BaseLoader, ChoiceLoader, Environment, FileSystemLoader, PackageLoader from openapi_python_client import utils from .parser import GeneratorData, import_string_from_reference from .parser.errors import GeneratorError +from .resolver.schema_resolver import SchemaResolver from .utils import snake_case if sys.version_info.minor < 8: # version did not exist before 3.8, need to use a backport @@ -318,20 +319,21 @@ def update_existing_client( def _get_document(*, url: Optional[str], path: Optional[Path]) -> Union[Dict[str, Any], GeneratorError]: - yaml_bytes: bytes if url is not None and path is not None: return GeneratorError(header="Provide URL or Path, not both.") - if url is not None: - try: - response = httpx.get(url) - yaml_bytes = response.content - except (httpx.HTTPError, httpcore.NetworkError): - return GeneratorError(header="Could not get OpenAPI document from provided URL") - elif path is not None: - yaml_bytes = path.read_bytes() - else: + + if url is None and path is None: return GeneratorError(header="No URL or Path provided") + + source = cast(Union[str, Path], (url if url is not None else path)) try: - return yaml.safe_load(yaml_bytes) - except yaml.YAMLError: + resolver = SchemaResolver(source) + result = resolver.resolve() + if len(result.errors) > 0: + return GeneratorError(header="; ".join(result.errors)) + except (httpx.HTTPError, httpcore.NetworkError, urllib.error.URLError): + return GeneratorError(header="Could not get OpenAPI document from provided URL") + except Exception: return GeneratorError(header="Invalid YAML from provided source") + + return result.schema diff --git a/openapi_python_client/parser/properties/__init__.py b/openapi_python_client/parser/properties/__init__.py index 992d726df..18304058d 100644 --- a/openapi_python_client/parser/properties/__init__.py +++ b/openapi_python_client/parser/properties/__init__.py @@ -1,5 +1,6 @@ +import copy from itertools import chain -from typing import Any, ClassVar, Dict, Generic, Iterable, Iterator, List, Optional, Set, Tuple, TypeVar, Union +from typing import Any, ClassVar, Dict, Generic, Iterable, Iterator, List, Optional, Set, Tuple, TypeVar, Union, cast import attr @@ -14,6 +15,92 @@ from .schemas import Schemas +class LazyReferencePropertyProxy: + + __GLOBAL_SCHEMAS_REF: Schemas = Schemas() + __PROXIES: List[Tuple["LazyReferencePropertyProxy", oai.Reference]] = [] + + @classmethod + def update_schemas(cls, schemas: Schemas) -> None: + cls.__GLOBAL_SCHEMAS_REF = schemas + + @classmethod + def create(cls, name: str, required: bool, data: oai.Reference, parent_name: str) -> "LazyReferencePropertyProxy": + proxy = LazyReferencePropertyProxy(name, required, data, parent_name) + cls.__PROXIES.append((proxy, data)) + return proxy + + @classmethod + def created_proxies(cls) -> List[Tuple["LazyReferencePropertyProxy", oai.Reference]]: + return cls.__PROXIES + + @classmethod + def flush_internal_references(cls) -> None: + cls.__PROXIES = [] + cls.__GLOBAL_SCHEMAS_REF = Schemas() + + def __init__(self, name: str, required: bool, data: oai.Reference, parent_name: str): + self._name = name + self._required = required + self._data = data + self._parent_name = parent_name + self._reference: Reference = Reference.from_ref(data.ref) + self._reference_to_itself: bool = self._reference.class_name == parent_name + self._resolved: Union[Property, None] = None + + def get_instance_type_string(self) -> str: + return self.get_type_string(no_optional=True) + + def get_type_string(self, no_optional: bool = False) -> str: + resolved = self.resolve() + if resolved: + return resolved.get_type_string(no_optional) + return "LazyReferencePropertyProxy" + + def get_imports(self, *, prefix: str) -> Set[str]: + resolved = self.resolve() + if resolved: + return resolved.get_imports(prefix=prefix) + return set() + + def to_string(self) -> str: + resolved = cast(Property, self.resolve(False)) + p_repr = resolved.to_string() + return p_repr.replace(f"{self._parent_name}", f"'{self._parent_name}'") + + def __copy__(self) -> Property: + resolved = cast(Property, self.resolve(False)) + return copy.copy(resolved) + + def __deepcopy__(self, memo: Any) -> Property: + resolved = cast(Property, self.resolve(False)) + return copy.deepcopy(resolved, memo) + + def __getattr__(self, name: str) -> Any: + if name == "nullable": + return False + elif name == "required": + return self._required + else: + resolved = self.resolve(False) + return resolved.__getattribute__(name) + + def resolve(self, allow_lazyness: bool = True) -> Union[Property, None]: + if not self._resolved: + schemas = LazyReferencePropertyProxy.__GLOBAL_SCHEMAS_REF + class_name = self._reference.class_name + existing = schemas.enums.get(class_name) or schemas.models.get(class_name) + if existing: + self._resolved = attr.evolve(existing, required=self._required, name=self._name) + + if self._resolved: + return self._resolved + elif allow_lazyness: + return None + else: + raise RuntimeError(f"Reference {self._data} shall have been resolved.") + + @attr.s(auto_attribs=True, frozen=True) class NoneProperty(Property): """ A property that is always None (used for empty schemas) """ @@ -235,7 +322,13 @@ def _string_based_property( def build_model_property( - *, data: oai.Schema, name: str, schemas: Schemas, required: bool, parent_name: Optional[str] + *, + data: oai.Schema, + name: str, + schemas: Schemas, + required: bool, + parent_name: Optional[str], + lazy_references: Dict[str, oai.Reference], ) -> Tuple[Union[ModelProperty, PropertyError], Schemas]: """ A single ModelProperty from its OAI data @@ -259,7 +352,12 @@ def build_model_property( for key, value in (data.properties or {}).items(): prop_required = key in required_set prop, schemas = property_from_data( - name=key, required=prop_required, data=value, schemas=schemas, parent_name=class_name + name=key, + required=prop_required, + data=value, + schemas=schemas, + parent_name=class_name, + lazy_references=lazy_references, ) if isinstance(prop, PropertyError): return prop, schemas @@ -285,6 +383,7 @@ def build_model_property( data=data.additionalProperties, schemas=schemas, parent_name=class_name, + lazy_references=lazy_references, ) if isinstance(additional_properties, PropertyError): return additional_properties, schemas @@ -385,12 +484,23 @@ def build_enum_property( def build_union_property( - *, data: oai.Schema, name: str, required: bool, schemas: Schemas, parent_name: str + *, + data: oai.Schema, + name: str, + required: bool, + schemas: Schemas, + parent_name: str, + lazy_references: Dict[str, oai.Reference], ) -> Tuple[Union[UnionProperty, PropertyError], Schemas]: sub_properties: List[Property] = [] for sub_prop_data in chain(data.anyOf, data.oneOf): sub_prop, schemas = property_from_data( - name=name, required=required, data=sub_prop_data, schemas=schemas, parent_name=parent_name + name=name, + required=required, + data=sub_prop_data, + schemas=schemas, + parent_name=parent_name, + lazy_references=lazy_references, ) if isinstance(sub_prop, PropertyError): return PropertyError(detail=f"Invalid property in union {name}", data=sub_prop_data), schemas @@ -410,12 +520,23 @@ def build_union_property( def build_list_property( - *, data: oai.Schema, name: str, required: bool, schemas: Schemas, parent_name: str + *, + data: oai.Schema, + name: str, + required: bool, + schemas: Schemas, + parent_name: str, + lazy_references: Dict[str, oai.Reference], ) -> Tuple[Union[ListProperty[Any], PropertyError], Schemas]: if data.items is None: return PropertyError(data=data, detail="type array must have items defined"), schemas inner_prop, schemas = property_from_data( - name=f"{name}_item", required=True, data=data.items, schemas=schemas, parent_name=parent_name + name=f"{name}_item", + required=True, + data=data.items, + schemas=schemas, + parent_name=parent_name, + lazy_references=lazy_references, ) if isinstance(inner_prop, PropertyError): return PropertyError(data=inner_prop.data, detail=f"invalid data in items of array {name}"), schemas @@ -437,10 +558,14 @@ def _property_from_data( data: Union[oai.Reference, oai.Schema], schemas: Schemas, parent_name: str, + lazy_references: Dict[str, oai.Reference], ) -> Tuple[Union[Property, PropertyError], Schemas]: """ Generate a Property from the OpenAPI dictionary representation of it """ name = utils.remove_string_escapes(name) if isinstance(data, oai.Reference): + if not _is_local_reference(data): + return PropertyError(data=data, detail="Remote reference schemas are not supported."), schemas + reference = Reference.from_ref(data.ref) existing = schemas.enums.get(reference.class_name) or schemas.models.get(reference.class_name) if existing: @@ -448,13 +573,47 @@ def _property_from_data( attr.evolve(existing, required=required, name=name), schemas, ) - return PropertyError(data=data, detail="Could not find reference in parsed models or enums"), schemas + else: + + def lookup_is_reference_to_itself( + ref_name: str, + owner_class_name: str, + lazy_references: Dict[str, oai.Reference], + ) -> bool: + if ref_name in lazy_references: + next_ref_name = _reference_pointer_name(lazy_references[ref_name]) + return lookup_is_reference_to_itself( + next_ref_name, + owner_class_name, + lazy_references, + ) + + return ref_name.casefold() == owner_class_name.casefold() + + reference_name = _reference_pointer_name(data) + if lookup_is_reference_to_itself(reference_name, parent_name, lazy_references): + return cast(Property, LazyReferencePropertyProxy.create(name, required, data, parent_name)), schemas + else: + return PropertyError(data=data, detail="Could not find reference in parsed models or enums."), schemas + if data.enum: return build_enum_property( - data=data, name=name, required=required, schemas=schemas, enum=data.enum, parent_name=parent_name + data=data, + name=name, + required=required, + schemas=schemas, + enum=data.enum, + parent_name=parent_name, ) if data.anyOf or data.oneOf: - return build_union_property(data=data, name=name, required=required, schemas=schemas, parent_name=parent_name) + return build_union_property( + data=data, + name=name, + required=required, + schemas=schemas, + parent_name=parent_name, + lazy_references=lazy_references, + ) if not data.type: return NoneProperty(name=name, required=required, nullable=False, default=None), schemas @@ -491,9 +650,23 @@ def _property_from_data( schemas, ) elif data.type == "array": - return build_list_property(data=data, name=name, required=required, schemas=schemas, parent_name=parent_name) + return build_list_property( + data=data, + name=name, + required=required, + schemas=schemas, + parent_name=parent_name, + lazy_references=lazy_references, + ) elif data.type == "object": - return build_model_property(data=data, name=name, schemas=schemas, required=required, parent_name=parent_name) + return build_model_property( + data=data, + name=name, + schemas=schemas, + required=required, + parent_name=parent_name, + lazy_references=lazy_references, + ) return PropertyError(data=data, detail=f"unknown type {data.type}"), schemas @@ -504,52 +677,182 @@ def property_from_data( data: Union[oai.Reference, oai.Schema], schemas: Schemas, parent_name: str, + lazy_references: Optional[Dict[str, oai.Reference]] = None, ) -> Tuple[Union[Property, PropertyError], Schemas]: + if lazy_references is None: + lazy_references = dict() + try: - return _property_from_data(name=name, required=required, data=data, schemas=schemas, parent_name=parent_name) + return _property_from_data( + name=name, + required=required, + data=data, + schemas=schemas, + parent_name=parent_name, + lazy_references=lazy_references, + ) except ValidationError: return PropertyError(detail="Failed to validate default value", data=data), schemas -def update_schemas_with_data(name: str, data: oai.Schema, schemas: Schemas) -> Union[Schemas, PropertyError]: +def update_schemas_with_data( + name: str, data: oai.Schema, schemas: Schemas, lazy_references: Dict[str, oai.Reference] +) -> Union[Schemas, PropertyError]: prop: Union[PropertyError, ModelProperty, EnumProperty] if data.enum is not None: prop, schemas = build_enum_property( - data=data, name=name, required=True, schemas=schemas, enum=data.enum, parent_name=None + data=data, + name=name, + required=True, + schemas=schemas, + enum=data.enum, + parent_name=None, ) else: - prop, schemas = build_model_property(data=data, name=name, schemas=schemas, required=True, parent_name=None) + prop, schemas = build_model_property( + data=data, name=name, schemas=schemas, required=True, parent_name=None, lazy_references=lazy_references + ) + if isinstance(prop, PropertyError): return prop else: return schemas +def resolve_reference_and_update_schemas( + name: str, data: oai.Reference, schemas: Schemas, references_by_name: Dict[str, oai.Reference] +) -> Union[Schemas, PropertyError]: + if _is_local_reference(data): + return _resolve_local_reference_schema(name, data, schemas, references_by_name) + else: + return _resolve_remote_reference_schema(name, data, schemas, references_by_name) + + +def _resolve_local_reference_schema( + name: str, data: oai.Reference, schemas: Schemas, references_by_name: Dict[str, oai.Reference] +) -> Union[Schemas, PropertyError]: + resolved_model_or_enum = _resolve_model_or_enum_reference(name, data, schemas, references_by_name) + + if resolved_model_or_enum: + model_name = utils.pascal_case(name) + + if isinstance(resolved_model_or_enum, EnumProperty): + schemas.enums[model_name] = resolved_model_or_enum + + elif isinstance(resolved_model_or_enum, ModelProperty): + schemas.models[model_name] = resolved_model_or_enum + + return schemas + else: + return PropertyError(data=data, detail="Failed to resolve local reference schemas.") + + +def _resolve_model_or_enum_reference( + name: str, data: oai.Reference, schemas: Schemas, references_by_name: Dict[str, oai.Reference] +) -> Union[EnumProperty, ModelProperty, None]: + target_model = _reference_model_name(data) + target_name = _reference_pointer_name(data) + + if target_model == name or target_name == name: + return None # Avoid infinite loop + + if target_name in references_by_name: + return _resolve_model_or_enum_reference( + target_name, references_by_name[target_name], schemas, references_by_name + ) + + if target_model in schemas.enums: + return schemas.enums[target_model] + elif target_model in schemas.models: + return schemas.models[target_model] + + return None + + +def _resolve_remote_reference_schema( + name: str, data: oai.Reference, schemas: Schemas, references_by_name: Dict[str, oai.Reference] +) -> Union[Schemas, PropertyError]: + return PropertyError(data=data, detail="Remote reference schemas are not supported.") + + +def _is_local_reference(reference: oai.Reference) -> bool: + return reference.ref.startswith("#", 0) + + +def _reference_model_name(reference: oai.Reference) -> str: + return Reference.from_ref(reference.ref).class_name + + +def _reference_pointer_name(reference: oai.Reference) -> str: + parts = reference.ref.split("/") + return parts[-1] + + def build_schemas(*, components: Dict[str, Union[oai.Reference, oai.Schema]]) -> Schemas: """ Get a list of Schemas from an OpenAPI dict """ schemas = Schemas() to_process: Iterable[Tuple[str, Union[oai.Reference, oai.Schema]]] = components.items() processing = True errors: List[PropertyError] = [] + lazy_self_references: Dict[str, oai.Reference] = dict() + visited: List[str] = [] + references_by_name: Dict[str, oai.Reference] = dict() + references_to_process: List[Tuple[str, oai.Reference]] = list() + LazyReferencePropertyProxy.flush_internal_references() # Cleanup side effects # References could have forward References so keep going as long as we are making progress while processing: processing = False errors = [] next_round = [] + # Only accumulate errors from the last round, since we might fix some along the way for name, data in to_process: + visited.append(name) + if isinstance(data, oai.Reference): - schemas.errors.append(PropertyError(data=data, detail="Reference schemas are not supported.")) + references_by_name[name] = data + references_to_process.append((name, data)) continue - schemas_or_err = update_schemas_with_data(name, data, schemas) + + schemas_or_err = update_schemas_with_data(name, data, schemas, lazy_self_references) + if isinstance(schemas_or_err, PropertyError): next_round.append((name, data)) errors.append(schemas_or_err) else: schemas = schemas_or_err processing = True # We made some progress this round, do another after it's done + to_process = next_round + + for name, reference in references_to_process: + schemas_or_err = resolve_reference_and_update_schemas(name, reference, schemas, references_by_name) + + if isinstance(schemas_or_err, PropertyError): + if _reference_pointer_name(reference) in visited and name not in lazy_self_references: + # It's a reference to an already visited Enum|Model; not yet resolved + # It's an indirect reference toward this Enum|Model; + # It will be lazy proxified and resolved later on + lazy_self_references[name] = reference + processing = True + else: + errors.append(schemas_or_err) + schemas.errors.extend(errors) + for name in lazy_self_references.keys(): + schemas_or_err = resolve_reference_and_update_schemas( + name, lazy_self_references[name], schemas, references_by_name + ) + if isinstance(schemas_or_err, PropertyError): + schemas.errors.extend(errors) + + LazyReferencePropertyProxy.update_schemas(schemas) + for reference_proxy, data in LazyReferencePropertyProxy.created_proxies(): + if not reference_proxy.resolve(): + schemas.errors.append( + PropertyError(data=data, detail="Could not find reference in parsed models or enums.") + ) + return schemas diff --git a/openapi_python_client/parser/responses.py b/openapi_python_client/parser/responses.py index 3d01a0eab..00810b12f 100644 --- a/openapi_python_client/parser/responses.py +++ b/openapi_python_client/parser/responses.py @@ -20,6 +20,7 @@ class Response: _SOURCE_BY_CONTENT_TYPE = { "application/json": "response.json()", + "application/problem+json": "response.json()", "application/vnd.api+json": "response.json()", "application/octet-stream": "response.content", "text/html": "response.text", diff --git a/openapi_python_client/resolver/__init__.py b/openapi_python_client/resolver/__init__.py new file mode 100644 index 000000000..e69de29bb diff --git a/openapi_python_client/resolver/collision_resolver.py b/openapi_python_client/resolver/collision_resolver.py new file mode 100644 index 000000000..85e252c66 --- /dev/null +++ b/openapi_python_client/resolver/collision_resolver.py @@ -0,0 +1,145 @@ +import hashlib +from typing import Any, Dict, List, Tuple + +from .reference import Reference +from .resolver_types import SchemaData + + +class CollisionResolver: + def __init__(self, root: SchemaData, refs: Dict[str, SchemaData], errors: List[str], parent: str): + self._root: SchemaData = root + self._refs: Dict[str, SchemaData] = refs + self._errors: List[str] = errors + self._parent = parent + self._refs_index: Dict[str, str] = dict() + self._schema_index: Dict[str, Reference] = dict() + self._keys_to_replace: Dict[str, Tuple[int, SchemaData, List[str]]] = dict() + + def _browse_schema(self, attr: Any, root_attr: Any) -> None: + if isinstance(attr, dict): + attr_copy = {**attr} # Create a shallow copy + for key, val in attr_copy.items(): + if key == "$ref": + ref = Reference(val, self._parent) + value = ref.pointer.value + + assert value + + schema = self._get_from_ref(ref, root_attr) + hashed_schema = self._reference_schema_hash(schema) + + if value in self._refs_index.keys(): + if self._refs_index[value] != hashed_schema: + if ref.is_local(): + self._increment_ref(ref, root_attr, hashed_schema, attr, key) + else: + assert ref.abs_path in self._refs.keys() + self._increment_ref(ref, self._refs[ref.abs_path], hashed_schema, attr, key) + else: + self._refs_index[value] = hashed_schema + + if hashed_schema in self._schema_index.keys(): + existing_ref = self._schema_index[hashed_schema] + if ( + existing_ref.pointer.value != ref.pointer.value + and ref.pointer.tokens()[-1] == existing_ref.pointer.tokens()[-1] + ): + self._errors.append(f"Found a duplicate schema in {existing_ref.value} and {ref.value}") + else: + self._schema_index[hashed_schema] = ref + + else: + self._browse_schema(val, root_attr) + + elif isinstance(attr, list): + for val in attr: + self._browse_schema(val, root_attr) + + def _get_from_ref(self, ref: Reference, attr: SchemaData) -> SchemaData: + if ref.is_remote(): + assert ref.abs_path in self._refs.keys() + attr = self._refs[ref.abs_path] + cursor = attr + query_parts = ref.pointer.tokens() + + for key in query_parts: + if key == "": + continue + + if isinstance(cursor, dict) and key in cursor: + cursor = cursor[key] + else: + self._errors.append(f"Did not find data corresponding to the reference {ref.value}") + + if list(cursor) == ["$ref"]: + ref2 = Reference(cursor["$ref"], self._parent) + if ref2.is_remote(): + attr = self._refs[ref2.abs_path] + return self._get_from_ref(ref2, attr) + + return cursor + + def _increment_ref( + self, ref: Reference, schema: SchemaData, hashed_schema: str, attr: Dict[str, Any], key: str + ) -> None: + i = 2 + value = ref.pointer.value + incremented_value = value + "_" + str(i) + + while incremented_value in self._refs_index.keys(): + if self._refs_index[incremented_value] == hashed_schema: + if ref.value not in self._keys_to_replace.keys(): + break # have to increment target key aswell + else: + attr[key] = ref.value + "_" + str(i) + return + else: + i = i + 1 + incremented_value = value + "_" + str(i) + + attr[key] = ref.value + "_" + str(i) + self._refs_index[incremented_value] = hashed_schema + self._keys_to_replace[ref.value] = (i, schema, ref.pointer.tokens()) + + def _modify_root_ref_name(self, query_parts: List[str], i: int, attr: SchemaData) -> None: + cursor = attr + last_key = query_parts[-1] + + for key in query_parts: + if key == "": + continue + + if key == last_key and key + "_" + str(i) not in cursor: + assert key in cursor, "Didnt find %s in %s" % (key, attr) + cursor[key + "_" + str(i)] = cursor.pop(key) + return + + if isinstance(cursor, dict) and key in cursor: + cursor = cursor[key] + else: + return + + def resolve(self) -> None: + self._browse_schema(self._root, self._root) + for file, schema in self._refs.items(): + self._browse_schema(schema, schema) + for a, b in self._keys_to_replace.items(): + self._modify_root_ref_name(b[2], b[0], b[1]) + + def _reference_schema_hash(self, schema: Dict[str, Any]) -> str: + md5 = hashlib.md5() + hash_elms = [] + for key in schema.keys(): + if key == "description": + hash_elms.append(schema[key]) + if key == "type": + hash_elms.append(schema[key]) + if key == "allOf": + for item in schema[key]: + hash_elms.append(str(item)) + + hash_elms.append(key) + + hash_elms.sort() + md5.update(";".join(hash_elms).encode("utf-8")) + return md5.hexdigest() diff --git a/openapi_python_client/resolver/data_loader.py b/openapi_python_client/resolver/data_loader.py new file mode 100644 index 000000000..df6677020 --- /dev/null +++ b/openapi_python_client/resolver/data_loader.py @@ -0,0 +1,24 @@ +import json + +import yaml + +from .resolver_types import SchemaData + + +class DataLoader: + @classmethod + def load(cls, path: str, data: bytes) -> SchemaData: + data_type = path.split(".")[-1].casefold() + + if data_type == "json": + return cls.load_json(data) + else: + return cls.load_yaml(data) + + @classmethod + def load_json(cls, data: bytes) -> SchemaData: + return json.loads(data) + + @classmethod + def load_yaml(cls, data: bytes) -> SchemaData: + return yaml.safe_load(data) diff --git a/openapi_python_client/resolver/pointer.py b/openapi_python_client/resolver/pointer.py new file mode 100644 index 000000000..36874e294 --- /dev/null +++ b/openapi_python_client/resolver/pointer.py @@ -0,0 +1,48 @@ +import urllib.parse +from typing import List, Union + + +class Pointer: + """ https://tools.ietf.org/html/rfc6901 """ + + def __init__(self, pointer: str) -> None: + if pointer is None or pointer != "" and not pointer.startswith("/"): + raise ValueError(f'Invalid pointer value {pointer}, it must match: *( "/" reference-token )') + + self._pointer = pointer + + @property + def value(self) -> str: + return self._pointer + + @property + def parent(self) -> Union["Pointer", None]: + tokens = self.tokens(False) + + if len(tokens) > 1: + tokens.pop() + return Pointer("/".join(tokens)) + else: + assert tokens[-1] == "" + return None + + def tokens(self, unescape: bool = True) -> List[str]: + tokens = [] + + if unescape: + for token in self._pointer.split("/"): + tokens.append(self._unescape(token)) + else: + tokens = self._pointer.split("/") + + return tokens + + @property + def unescapated_value(self) -> str: + return self._unescape(self._pointer) + + def _unescape(self, data: str) -> str: + data = urllib.parse.unquote(data) + data = data.replace("~1", "/") + data = data.replace("~0", "~") + return data diff --git a/openapi_python_client/resolver/reference.py b/openapi_python_client/resolver/reference.py new file mode 100644 index 000000000..dbd5bd007 --- /dev/null +++ b/openapi_python_client/resolver/reference.py @@ -0,0 +1,68 @@ +import urllib.parse +from pathlib import Path +from typing import Union + +from .pointer import Pointer + + +class Reference: + """ https://tools.ietf.org/html/draft-pbryan-zyp-json-ref-03 """ + + def __init__(self, reference: str, parent: str = None): + self._ref = reference + self._parsed_ref = urllib.parse.urlparse(reference) + self._parent = parent + + @property + def path(self) -> str: + return urllib.parse.urldefrag(self._parsed_ref.geturl()).url + + @property + def abs_path(self) -> str: + if self._parent: + parent_dir = Path(self._parent) + abs_path = parent_dir.joinpath(self.path) + abs_path = abs_path.resolve() + return str(abs_path) + else: + return self.path + + @property + def parent(self) -> Union[str, None]: + return self._parent + + @property + def pointer(self) -> Pointer: + frag = self._parsed_ref.fragment + if self.is_url() and frag != "" and not frag.startswith("/"): + frag = f"/{frag}" + + return Pointer(frag) + + def is_relative(self) -> bool: + """ return True if reference path is a relative path """ + return not self.is_absolute() + + def is_absolute(self) -> bool: + """ return True is reference path is an absolute path """ + return self._parsed_ref.netloc != "" + + @property + def value(self) -> str: + return self._ref + + def is_url(self) -> bool: + """ return True if the reference path is pointing to an external url location """ + return self.is_remote() and self._parsed_ref.netloc != "" + + def is_remote(self) -> bool: + """ return True if the reference pointer is pointing to a remote document """ + return not self.is_local() + + def is_local(self) -> bool: + """ return True if the reference pointer is pointing to the current document """ + return self._parsed_ref.path == "" + + def is_full_document(self) -> bool: + """ return True if the reference pointer is pointing to the whole document content """ + return self.pointer.parent is None diff --git a/openapi_python_client/resolver/resolved_schema.py b/openapi_python_client/resolver/resolved_schema.py new file mode 100644 index 000000000..2612e0362 --- /dev/null +++ b/openapi_python_client/resolver/resolved_schema.py @@ -0,0 +1,175 @@ +from typing import Any, Dict, Generator, List, Tuple, Union, cast + +from .reference import Reference +from .resolver_types import SchemaData + + +class ResolvedSchema: + def __init__(self, root: SchemaData, refs: Dict[str, SchemaData], errors: List[str], parent: str): + self._root: SchemaData = root + self._refs: Dict[str, SchemaData] = refs + self._errors: List[str] = errors + self._resolved_remotes_components: SchemaData = cast(SchemaData, {}) + self._parent = parent + + self._resolved_schema: SchemaData = cast(SchemaData, {}) + if len(self._errors) == 0: + self._process() + + @property + def schema(self) -> SchemaData: + return self._root + + @property + def errors(self) -> List[str]: + return self._errors.copy() + + def _dict_deep_update(self, d: Dict[str, Any], u: Dict[str, Any]) -> Dict[str, Any]: + for k, v in u.items(): + if isinstance(d, Dict) and list(d) == ["$ref"]: + d.pop("$ref") + if isinstance(v, Dict): + d[k] = self._dict_deep_update(d.get(k, {}), v) + else: + d[k] = v + return d + + def _process(self) -> None: + self._process_remote_paths() + self._process_remote_components(self._root, parent_path=self._parent) + self._dict_deep_update(self._root, self._resolved_remotes_components) + + def _process_remote_paths(self) -> None: + refs_to_replace = [] + refs_to_remove = [] + for owner, ref_key, ref_val in self._lookup_schema_references_in(self._root, "paths"): + ref = Reference(ref_val, self._parent) + + if ref.is_local(): + continue + + remote_path = ref.abs_path + path = ref.pointer.unescapated_value + tokens = ref.pointer.tokens() + + if remote_path not in self._refs: + self._errors.append("Failed to resolve remote reference > {0}".format(remote_path)) + else: + remote_schema = self._refs[remote_path] + remote_value = self._lookup_dict(remote_schema, tokens) + if not remote_value: + self._errors.append("Failed to read remote value {}, in remote ref {}".format(path, remote_path)) + refs_to_remove.append((owner, ref_key)) + else: + refs_to_replace.append((owner, remote_schema, remote_value)) + + for owner, remote_schema, remote_value in refs_to_replace: + self._process_remote_components(remote_schema, remote_value, 1, self._parent) + self._replace_reference_with(owner, remote_value) + + for owner, ref_key in refs_to_remove: + owner.pop(ref_key) + + def _process_remote_components( + self, owner: SchemaData, subpart: Union[SchemaData, None] = None, depth: int = 0, parent_path: str = None + ) -> None: + target = subpart if subpart else owner + + for parent, ref_key, ref_val in self._lookup_schema_references(target): + ref = Reference(ref_val, parent_path) + + if ref.is_local(): + # print('Found local reference >> {0}'.format(ref.value)) + if depth > 0: + self._transform_to_local_components(owner, ref) + else: + remote_path = ref.abs_path + if remote_path not in self._refs: + self._errors.append("Failed to resolve remote reference > {0}".format(remote_path)) + else: + remote_owner = self._refs[remote_path] + self._transform_to_local_components(remote_owner, ref) + self._transform_to_local_ref(parent, ref) + + def _transform_to_local_components(self, owner: SchemaData, ref: Reference) -> None: + self._ensure_components_dir_exists(ref) + + # print('Processing remote component > {0}'.format(ref.value)) + remote_component = self._lookup_dict(owner, ref.pointer.tokens()) + pointer_parent = ref.pointer.parent + + if pointer_parent is not None: + root_components_dir = self._lookup_dict(self._resolved_remotes_components, pointer_parent.tokens()) + component_name = ref.pointer.value.split("/")[-1] + + if remote_component is None: + print("Weird relookup of >> {0}".format(ref.value)) + assert ref.is_local() and self._lookup_dict(self._resolved_remotes_components, ref.pointer.tokens()) + return + + if "$ref" in remote_component: + subref = Reference(remote_component["$ref"], ref.parent) + if not subref.is_local(): + print("Lookup remote ref >>> {0}".format(subref.value)) + self._process_remote_components(remote_component, parent_path=ref.parent) + + if root_components_dir is not None: + if component_name not in root_components_dir: + root_components_dir[component_name] = remote_component + self._process_remote_components(owner, remote_component, 2, ref.parent) + + def _ensure_components_dir_exists(self, ref: Reference) -> None: + cursor = self._resolved_remotes_components + pointer_dir = ref.pointer.parent + assert pointer_dir is not None + + for key in pointer_dir.value.split("/"): # noqa + if key == "": + continue + + if key not in cursor: + cursor[key] = {} + + cursor = cursor[key] + + def _transform_to_local_ref(self, owner: Dict[str, Any], ref: Reference) -> None: + owner["$ref"] = "#{0}".format(ref.pointer.value) + + def _lookup_dict(self, attr: SchemaData, query_parts: List[str]) -> Union[SchemaData, None]: + cursor = attr + + for key in query_parts: + if key == "": + continue + + if isinstance(cursor, dict) and key in cursor: + cursor = cursor[key] + else: + return None + return cursor + + def _replace_reference_with(self, root: Dict[str, Any], new_value: Dict[str, Any]) -> None: + for key in new_value: + root[key] = new_value[key] + + root.pop("$ref") + + def _lookup_schema_references_in( + self, attr: SchemaData, path: str + ) -> Generator[Tuple[SchemaData, str, Any], None, None]: + if not isinstance(attr, dict) or path not in attr: + return + + yield from self._lookup_schema_references(attr[path]) + + def _lookup_schema_references(self, attr: Any) -> Generator[Tuple[SchemaData, str, str], None, None]: + if isinstance(attr, dict): + for key, val in attr.items(): + if key == "$ref": + yield cast(SchemaData, attr), cast(str, key), cast(str, val) + else: + yield from self._lookup_schema_references(val) + + elif isinstance(attr, list): + for val in attr: + yield from self._lookup_schema_references(val) diff --git a/openapi_python_client/resolver/resolver_types.py b/openapi_python_client/resolver/resolver_types.py new file mode 100644 index 000000000..84f6cea5b --- /dev/null +++ b/openapi_python_client/resolver/resolver_types.py @@ -0,0 +1,3 @@ +from typing import Any, Dict, NewType + +SchemaData = NewType("SchemaData", Dict[str, Any]) diff --git a/openapi_python_client/resolver/schema_resolver.py b/openapi_python_client/resolver/schema_resolver.py new file mode 100644 index 000000000..3521842fb --- /dev/null +++ b/openapi_python_client/resolver/schema_resolver.py @@ -0,0 +1,147 @@ +import logging +import urllib +from pathlib import Path +from typing import Any, Dict, Generator, List, Union, cast + +import httpx + +from .collision_resolver import CollisionResolver +from .data_loader import DataLoader +from .reference import Reference +from .resolved_schema import ResolvedSchema +from .resolver_types import SchemaData + + +class SchemaResolver: + def __init__(self, url_or_path: Union[str, Path]): + if not url_or_path: + raise ValueError("Invalid document root reference, it shall be an remote url or local file path") + + self._root_path: Union[Path, None] = None + self._root_url: Union[str, None] = None + self._root_url_scheme: Union[str, None] = None + self._parent_path: str + + if self._isapath(url_or_path): + url_or_path = cast(Path, url_or_path) + self._root_path = url_or_path.absolute() + self._parent_path = str(self._root_path.parent) + else: + url_or_path = cast(str, url_or_path) + self._root_url = url_or_path + self._parent_path = url_or_path + try: + self._root_url_scheme = urllib.parse.urlparse(url_or_path).scheme + if self._root_url_scheme not in ["http", "https"]: + raise ValueError(f"Unsupported URL scheme '{self._root_url_scheme}', expecting http or https") + except (TypeError, AttributeError): + raise urllib.error.URLError(f"Coult not parse URL > {url_or_path}") + + def _isapath(self, url_or_path: Union[str, Path]) -> bool: + return isinstance(url_or_path, Path) + + def resolve(self, recursive: bool = True) -> ResolvedSchema: + assert self._root_path or self._root_url + + root_schema: SchemaData + external_schemas: Dict[str, SchemaData] = {} + errors: List[str] = [] + parent: str + + if self._root_path: + root_schema = self._fetch_remote_file_path(self._root_path) + elif self._root_url: + root_schema = self._fetch_url_reference(self._root_url) + + self._resolve_schema_references(self._parent_path, root_schema, external_schemas, errors, recursive) + CollisionResolver(root_schema, external_schemas, errors, self._parent_path).resolve() + return ResolvedSchema(root_schema, external_schemas, errors, self._parent_path) + + def _resolve_schema_references( + self, + parent: str, + root: SchemaData, + external_schemas: Dict[str, SchemaData], + errors: List[str], + recursive: bool, + ) -> None: + + for ref in self._lookup_schema_references(root): + if ref.is_local(): + continue + + try: + path = self._absolute_path(ref.path, parent) + parent = self._parent(path) + + if path in external_schemas: + continue + + external_schemas[path] = self._fetch_remote_reference(path) + + if recursive: + self._resolve_schema_references(parent, external_schemas[path], external_schemas, errors, recursive) + + except Exception: + errors.append(f"Failed to gather external reference data of {ref.value} from {path}") + logging.exception(f"Failed to gather external reference data of {ref.value} from {path}") + + def _parent(self, abs_path: str) -> str: + if abs_path.startswith("http", 0): + return urllib.parse.urljoin(f"{abs_path}/", "..") + else: + path = Path(abs_path) + return str(path.parent) + + def _absolute_path(self, relative_path: str, parent: str) -> str: + if relative_path.startswith("http", 0): + return relative_path + + if relative_path.startswith("//"): + if parent.startswith("http"): + scheme = urllib.parse.urlparse(parent).scheme + return f"{scheme}:{relative_path}" + else: + scheme = self._root_url_scheme or "http" + return f"{scheme}:{relative_path}" + + if parent.startswith("http"): + return urllib.parse.urljoin(parent, relative_path) + else: + parent_dir = Path(parent) + abs_path = parent_dir.joinpath(relative_path) + abs_path = abs_path.resolve() + return str(abs_path) + + def _fetch_remote_reference(self, abs_path: str) -> SchemaData: + res: SchemaData + + if abs_path.startswith("http"): + res = self._fetch_url_reference(abs_path) + else: + res = self._fetch_remote_file_path(Path(abs_path)) + + return res + + def _fetch_remote_file_path(self, path: Path) -> SchemaData: + logging.info(f"Fetching remote ref file path > {path}") + return DataLoader.load(str(path), path.read_bytes()) + + def _fetch_url_reference(self, url: str) -> SchemaData: + if url.startswith("//", 0): + url = "{0}:{1}".format((self._root_url_scheme or "http"), url) + + logging.info(f"Fetching remote ref url > {url}") + return DataLoader.load(url, httpx.get(url).content) + + def _lookup_schema_references(self, attr: Any) -> Generator[Reference, None, None]: + if isinstance(attr, dict): + for key, val in attr.items(): + if key == "$ref": + yield Reference(val) + else: + yield from self._lookup_schema_references(val) + + elif isinstance(attr, list): + for val in attr: + yield from self._lookup_schema_references(val) diff --git a/tests/test___init__.py b/tests/test___init__.py index 3d2547d89..44988ec2e 100644 --- a/tests/test___init__.py +++ b/tests/test___init__.py @@ -1,4 +1,5 @@ import pathlib +from urllib.parse import ParseResult import httpcore import jinja2 @@ -169,7 +170,7 @@ def test__get_document_url_and_path(self, mocker): loads.assert_not_called() def test__get_document_bad_url(self, mocker): - get = mocker.patch("httpx.get", side_effect=httpcore.NetworkError) + get = mocker.patch("httpx.get") Path = mocker.patch("openapi_python_client.Path") loads = mocker.patch("yaml.safe_load") @@ -179,7 +180,7 @@ def test__get_document_bad_url(self, mocker): result = _get_document(url=url, path=None) assert result == GeneratorError(header="Could not get OpenAPI document from provided URL") - get.assert_called_once_with(url) + get.assert_not_called() Path.assert_not_called() loads.assert_not_called() @@ -190,7 +191,7 @@ def test__get_document_url_no_path(self, mocker): from openapi_python_client import _get_document - url = mocker.MagicMock() + url = "http://localhost/" _get_document(url=url, path=None) get.assert_called_once_with(url) @@ -200,6 +201,7 @@ def test__get_document_url_no_path(self, mocker): def test__get_document_path_no_url(self, mocker): get = mocker.patch("httpx.get") loads = mocker.patch("yaml.safe_load") + mocker.patch("openapi_python_client.resolver.schema_resolver.SchemaResolver._isapath", return_value=True) from openapi_python_client import _get_document @@ -207,12 +209,13 @@ def test__get_document_path_no_url(self, mocker): _get_document(url=None, path=path) get.assert_not_called() - path.read_bytes.assert_called_once() - loads.assert_called_once_with(path.read_bytes()) + path.absolute().read_bytes.assert_called_once() + loads.assert_called_once_with(path.absolute().read_bytes()) def test__get_document_bad_yaml(self, mocker): get = mocker.patch("httpx.get") loads = mocker.patch("yaml.safe_load", side_effect=yaml.YAMLError) + mocker.patch("openapi_python_client.resolver.schema_resolver.SchemaResolver._isapath", return_value=True) from openapi_python_client import _get_document @@ -220,8 +223,8 @@ def test__get_document_bad_yaml(self, mocker): result = _get_document(url=None, path=path) get.assert_not_called() - path.read_bytes.assert_called_once() - loads.assert_called_once_with(path.read_bytes()) + path.absolute().read_bytes.assert_called_once() + loads.assert_called_once_with(path.absolute().read_bytes()) assert result == GeneratorError(header="Invalid YAML from provided source") diff --git a/tests/test_parser/test_properties/test_init.py b/tests/test_parser/test_properties/test_init.py index ee07d3973..2edc7fa17 100644 --- a/tests/test_parser/test_properties/test_init.py +++ b/tests/test_parser/test_properties/test_init.py @@ -548,7 +548,7 @@ def test_property_from_data_ref_enum(self): from openapi_python_client.parser.properties import EnumProperty, Reference, Schemas, property_from_data name = "some_enum" - data = oai.Reference.construct(ref="MyEnum") + data = oai.Reference.construct(ref="#MyEnum") existing_enum = EnumProperty( name="an_enum", required=True, @@ -579,7 +579,7 @@ def test_property_from_data_ref_model(self): name = "new_name" required = False class_name = "MyModel" - data = oai.Reference.construct(ref=class_name) + data = oai.Reference.construct(ref=f"#{class_name}") existing_model = ModelProperty( name="old_name", required=True, @@ -611,7 +611,12 @@ def test_property_from_data_ref_model(self): assert schemas == new_schemas def test_property_from_data_ref_not_found(self, mocker): - from openapi_python_client.parser.properties import PropertyError, Schemas, property_from_data + from openapi_python_client.parser.properties import ( + LazyReferencePropertyProxy, + PropertyError, + Schemas, + property_from_data, + ) name = mocker.MagicMock() required = mocker.MagicMock() @@ -621,11 +626,16 @@ def test_property_from_data_ref_not_found(self, mocker): schemas = Schemas() prop, new_schemas = property_from_data( - name=name, required=required, data=data, schemas=schemas, parent_name="parent" + name=name, + required=required, + data=data, + schemas=schemas, + parent_name="parent", + lazy_references=dict(), ) from_ref.assert_called_once_with(data.ref) - assert prop == PropertyError(data=data, detail="Could not find reference in parsed models or enums") + assert prop == PropertyError(data=data, detail="Could not find reference in parsed models or enums.") assert schemas == new_schemas def test_property_from_data_string(self, mocker): @@ -698,7 +708,12 @@ def test_property_from_data_array(self, mocker): assert response == build_list_property.return_value build_list_property.assert_called_once_with( - data=data, name=name, required=required, schemas=schemas, parent_name="parent" + data=data, + name=name, + required=required, + schemas=schemas, + parent_name="parent", + lazy_references=dict(), ) def test_property_from_data_object(self, mocker): @@ -717,7 +732,12 @@ def test_property_from_data_object(self, mocker): assert response == build_model_property.return_value build_model_property.assert_called_once_with( - data=data, name=name, required=required, schemas=schemas, parent_name="parent" + data=data, + name=name, + required=required, + schemas=schemas, + parent_name="parent", + lazy_references=dict(), ) def test_property_from_data_union(self, mocker): @@ -739,7 +759,12 @@ def test_property_from_data_union(self, mocker): assert response == build_union_property.return_value build_union_property.assert_called_once_with( - data=data, name=name, required=required, schemas=schemas, parent_name="parent" + data=data, + name=name, + required=required, + schemas=schemas, + parent_name="parent", + lazy_references=dict(), ) def test_property_from_data_unsupported_type(self, mocker): @@ -794,7 +819,12 @@ def test_build_list_property_no_items(self, mocker): schemas = properties.Schemas() p, new_schemas = properties.build_list_property( - name=name, required=required, data=data, schemas=schemas, parent_name="parent" + name=name, + required=required, + data=data, + schemas=schemas, + parent_name="parent", + lazy_references=dict(), ) assert p == PropertyError(data=data, detail="type array must have items defined") @@ -817,14 +847,24 @@ def test_build_list_property_invalid_items(self, mocker): ) p, new_schemas = properties.build_list_property( - name=name, required=required, data=data, schemas=schemas, parent_name="parent" + name=name, + required=required, + data=data, + schemas=schemas, + parent_name="parent", + lazy_references=dict(), ) assert p == PropertyError(data="blah", detail=f"invalid data in items of array {name}") assert new_schemas == second_schemas assert schemas != new_schemas, "Schema was mutated" property_from_data.assert_called_once_with( - name=f"{name}_item", required=True, data=data.items, schemas=schemas, parent_name="parent" + name=f"{name}_item", + required=True, + data=data.items, + schemas=schemas, + parent_name="parent", + lazy_references=dict(), ) def test_build_list_property(self, mocker): @@ -845,7 +885,12 @@ def test_build_list_property(self, mocker): mocker.patch("openapi_python_client.utils.to_valid_python_identifier", return_value=name) p, new_schemas = properties.build_list_property( - name=name, required=required, data=data, schemas=schemas, parent_name="parent" + name=name, + required=required, + data=data, + schemas=schemas, + parent_name="parent", + lazy_references=dict(), ) assert isinstance(p, properties.ListProperty) @@ -853,7 +898,12 @@ def test_build_list_property(self, mocker): assert new_schemas == second_schemas assert schemas != new_schemas, "Schema was mutated" property_from_data.assert_called_once_with( - name=f"{name}_item", required=True, data=data.items, schemas=schemas, parent_name="parent" + name=f"{name}_item", + required=True, + data=data.items, + schemas=schemas, + parent_name="parent", + lazy_references=dict(), ) @@ -1009,10 +1059,18 @@ def test_build_schemas(mocker): build_model_property.assert_has_calls( [ - mocker.call(data=in_data["1"], name="1", schemas=Schemas(), required=True, parent_name=None), - mocker.call(data=in_data["2"], name="2", schemas=schemas_1, required=True, parent_name=None), - mocker.call(data=in_data["3"], name="3", schemas=schemas_2, required=True, parent_name=None), - mocker.call(data=in_data["3"], name="3", schemas=schemas_2, required=True, parent_name=None), + mocker.call( + data=in_data["1"], name="1", schemas=Schemas(), required=True, parent_name=None, lazy_references=dict() + ), + mocker.call( + data=in_data["2"], name="2", schemas=schemas_1, required=True, parent_name=None, lazy_references=dict() + ), + mocker.call( + data=in_data["3"], name="3", schemas=schemas_2, required=True, parent_name=None, lazy_references=dict() + ), + mocker.call( + data=in_data["3"], name="3", schemas=schemas_2, required=True, parent_name=None, lazy_references=dict() + ), ] ) # schemas_3 was the last to come back from build_model_property, but it should be ignored because it's an error @@ -1020,13 +1078,43 @@ def test_build_schemas(mocker): assert result.errors == [error] -def test_build_parse_error_on_reference(): +def test_build_parse_error_on_unknown_local_reference(): from openapi_python_client.parser.openapi import build_schemas - ref_schema = oai.Reference.construct() + ref_schema = oai.Reference.construct(ref="#/foobar") in_data = {"1": ref_schema} result = build_schemas(components=in_data) - assert result.errors[0] == PropertyError(data=ref_schema, detail="Reference schemas are not supported.") + assert result.errors[0] == PropertyError(data=ref_schema, detail="Failed to resolve local reference schemas.") + + +def test_build_parse_success_on_known_local_reference(mocker): + from openapi_python_client.parser.openapi import build_schemas + + build_model_property = mocker.patch(f"{MODULE_NAME}.build_model_property") + schemas = mocker.MagicMock() + build_enum_property = mocker.patch(f"{MODULE_NAME}.build_enum_property", return_value=(mocker.MagicMock(), schemas)) + in_data = {"1": oai.Reference.construct(ref="#/foobar"), "foobar": mocker.MagicMock(enum=["val1", "val2", "val3"])} + + result = build_schemas(components=in_data) + + assert len(result.errors) == 0 + assert result.enums["1"] == result.enums["foobar"] + + +def test_build_parse_error_on_remote_reference(): + from openapi_python_client.parser.openapi import build_schemas + + ref_schemas = [ + oai.Reference.construct(ref="http://foobar/../foobar.yaml#/foobar"), + oai.Reference.construct(ref="https://foobar/foobar.yaml#/foobar"), + oai.Reference.construct(ref="../foobar.yaml#/foobar"), + oai.Reference.construct(ref="foobar.yaml#/foobar"), + oai.Reference.construct(ref="//foobar#/foobar"), + ] + for ref_schema in ref_schemas: + in_data = {"1": ref_schema} + result = build_schemas(components=in_data) + assert result.errors[0] == PropertyError(data=ref_schema, detail="Remote reference schemas are not supported.") def test_build_enums(mocker): @@ -1078,6 +1166,7 @@ def test_build_model_property(additional_properties_schema, expected_additional_ schemas=schemas, required=True, parent_name="parent", + lazy_references=dict(), ) assert new_schemas != schemas @@ -1124,6 +1213,7 @@ def test_build_model_property_conflict(): schemas=schemas, required=True, parent_name=None, + lazy_references=dict(), ) assert new_schemas == schemas @@ -1141,11 +1231,7 @@ def test_build_model_property_bad_prop(): schemas = Schemas(models={"OtherModel": None}) err, new_schemas = build_model_property( - data=data, - name="prop", - schemas=schemas, - required=True, - parent_name=None, + data=data, name="prop", schemas=schemas, required=True, parent_name=None, lazy_references=dict() ) assert new_schemas == schemas @@ -1170,6 +1256,7 @@ def test_build_model_property_bad_additional_props(): schemas=schemas, required=True, parent_name=None, + lazy_references=dict(), ) assert new_schemas == schemas @@ -1216,3 +1303,376 @@ def test_build_enum_property_bad_default(): assert schemas == schemas assert err == PropertyError(detail="B is an invalid default for enum Existing", data=data) + + +def test__is_local_reference(): + from openapi_python_client.parser.properties import _is_local_reference + + data_set = [ + ("//foobar#foobar", False), + ("foobar#/foobar", False), + ("foobar.json", False), + ("foobar.yaml", False), + ("../foo/bar.json#/foobar", False), + ("#/foobar", True), + ("#/foo/bar", True), + ] + + for data, expected_result in data_set: + ref = oai.Reference.construct(ref=data) + assert _is_local_reference(ref) == expected_result + + +def test__reference_pointer_name(): + from openapi_python_client.parser.properties import _reference_pointer_name + + data_set = [ + ("#/foobar", "foobar"), + ("#/foo/bar", "bar"), + ] + + for data, expected_result in data_set: + ref = oai.Reference.construct(ref=data) + assert _reference_pointer_name(ref) == expected_result + + +def test__reference_model_name(): + from openapi_python_client.parser.properties import _reference_model_name + + data_set = [ + ("#/foobar", "Foobar"), + ("#/foo/bar", "Bar"), + ] + + for data, expected_result in data_set: + ref = oai.Reference.construct(ref=data) + assert _reference_model_name(ref) == expected_result + + +def test__resolve_model_or_enum_reference(mocker): + from openapi_python_client.parser.properties import _resolve_model_or_enum_reference + from openapi_python_client.parser.properties.schemas import Schemas + + references_by_name = { + "FooBarReferenceLoop": oai.Reference.construct(ref="#/foobar"), + "FooBarDeeperReferenceLoop": oai.Reference.construct(ref="#/FooBarReferenceLoop"), + "BarFooReferenceLoop": oai.Reference.construct(ref="#/barfoo"), + "BarFooDeeperReferenceLoop": oai.Reference.construct(ref="#/BarFooReferenceLoop"), + "InfiniteReferenceLoop": oai.Reference.construct(ref="#/InfiniteReferenceLoop"), + "UnknownReference": oai.Reference.construct(ref="#/unknown"), + } + schemas = Schemas(enums={"Foobar": 1}, models={"Barfoo": 2}) + + res_1 = _resolve_model_or_enum_reference( + "FooBarReferenceLoop", references_by_name["FooBarReferenceLoop"], schemas, references_by_name + ) + res_2 = _resolve_model_or_enum_reference( + "FooBarDeeperReferenceLoop", references_by_name["FooBarDeeperReferenceLoop"], schemas, references_by_name + ) + res_3 = _resolve_model_or_enum_reference( + "BarFooReferenceLoop", references_by_name["BarFooReferenceLoop"], schemas, references_by_name + ) + res_4 = _resolve_model_or_enum_reference( + "BarFooDeeperReferenceLoop", references_by_name["BarFooDeeperReferenceLoop"], schemas, references_by_name + ) + res_5 = _resolve_model_or_enum_reference( + "InfiniteReferenceLoop", references_by_name["InfiniteReferenceLoop"], schemas, references_by_name + ) + res_6 = _resolve_model_or_enum_reference( + "UnknownReference", references_by_name["UnknownReference"], schemas, references_by_name + ) + + assert res_1 == schemas.enums["Foobar"] + assert res_2 == schemas.enums["Foobar"] + assert res_3 == schemas.models["Barfoo"] + assert res_4 == schemas.models["Barfoo"] + assert res_5 == None + assert res_6 == None + + +def test__resolve_local_reference_schema(mocker): + from openapi_python_client.parser.properties import _resolve_local_reference_schema + from openapi_python_client.parser.properties.enum_property import EnumProperty + from openapi_python_client.parser.properties.model_property import ModelProperty + from openapi_python_client.parser.properties.schemas import Schemas + + references_by_name = { + "FooBarReferenceLoop": oai.Reference.construct(ref="#/foobar"), + "FooBarDeeperReferenceLoop": oai.Reference.construct(ref="#/FooBarReferenceLoop"), + "fooBarLowerCaseReferenceLoop": oai.Reference.construct(ref="#/foobar"), + "fooBarLowerCaseDeeperReferenceLoop": oai.Reference.construct(ref="#/fooBarLowerCaseReferenceLoop"), + "BarFooReferenceLoop": oai.Reference.construct(ref="#/barfoo"), + "BarFooDeeperReferenceLoop": oai.Reference.construct(ref="#/BarFooReferenceLoop"), + "InfiniteReferenceLoop": oai.Reference.construct(ref="#/InfiniteReferenceLoop"), + "UnknownReference": oai.Reference.construct(ref="#/unknown"), + } + schemas = Schemas( + enums={ + "Foobar": EnumProperty( + name="Foobar", + required=False, + nullable=True, + default="foobar", + values=["foobar"], + value_type="str", + reference="", + ) + }, + models={ + "Barfoo": ModelProperty( + name="Barfoo", + required=False, + nullable=True, + default="barfoo", + reference="", + required_properties=[], + optional_properties=[], + description="", + relative_imports=[], + additional_properties=[], + ) + }, + ) + + res_1 = _resolve_local_reference_schema( + "FooBarReferenceLoop", references_by_name["FooBarReferenceLoop"], schemas, references_by_name + ) + res_2 = _resolve_local_reference_schema( + "FooBarDeeperReferenceLoop", references_by_name["FooBarDeeperReferenceLoop"], schemas, references_by_name + ) + res_3 = _resolve_local_reference_schema( + "BarFooReferenceLoop", references_by_name["BarFooReferenceLoop"], schemas, references_by_name + ) + res_4 = _resolve_local_reference_schema( + "BarFooDeeperReferenceLoop", references_by_name["BarFooDeeperReferenceLoop"], schemas, references_by_name + ) + res_5 = _resolve_local_reference_schema( + "fooBarLowerCaseReferenceLoop", references_by_name["fooBarLowerCaseReferenceLoop"], schemas, references_by_name + ) + res_6 = _resolve_local_reference_schema( + "fooBarLowerCaseDeeperReferenceLoop", + references_by_name["fooBarLowerCaseDeeperReferenceLoop"], + schemas, + references_by_name, + ) + res_7 = _resolve_local_reference_schema( + "InfiniteReferenceLoop", references_by_name["InfiniteReferenceLoop"], schemas, references_by_name + ) + res_8 = _resolve_local_reference_schema( + "UnknownReference", references_by_name["UnknownReference"], schemas, references_by_name + ) + + assert res_1 == res_2 == res_3 == res_4 == res_5 == res_6 == schemas + assert schemas.enums["FooBarReferenceLoop"] == schemas.enums["Foobar"] + assert schemas.enums["FooBarDeeperReferenceLoop"] == schemas.enums["Foobar"] + assert schemas.models["BarFooReferenceLoop"] == schemas.models["Barfoo"] + assert schemas.models["BarFooDeeperReferenceLoop"] == schemas.models["Barfoo"] + assert schemas.enums["FooBarLowerCaseReferenceLoop"] == schemas.enums["Foobar"] + assert schemas.enums["FooBarLowerCaseDeeperReferenceLoop"] == schemas.enums["Foobar"] + assert isinstance(res_7, PropertyError) + assert isinstance(res_8, PropertyError) + + +def _base_api_data(): + return """ +--- +openapi: 3.0.2 +info: + title: test + description: test + version: 1.0.0 +paths: + /tests/: + get: + operationId: getTests + description: test + responses: + '200': + description: test + content: + application/json: + schema: + $ref: '#/components/schemas/fooBar' +""" + + +def test_lazy_proxy_reference_unresolved(): + import copy + + import openapi_python_client.schema as oai + from openapi_python_client.parser.properties import LazyReferencePropertyProxy, Schemas + + LazyReferencePropertyProxy.update_schemas(Schemas()) + lazy_reference_proxy = LazyReferencePropertyProxy.create( + "childProperty", False, oai.Reference(ref="#/foobar"), "AModel" + ) + + assert lazy_reference_proxy.get_instance_type_string() == "LazyReferencePropertyProxy" + assert lazy_reference_proxy.get_type_string(no_optional=False) == "LazyReferencePropertyProxy" + assert lazy_reference_proxy.get_type_string(no_optional=True) == "LazyReferencePropertyProxy" + assert lazy_reference_proxy.get_imports(prefix="..") == set() + assert lazy_reference_proxy.resolve() == None + assert lazy_reference_proxy.required == False + assert lazy_reference_proxy.nullable == False + with pytest.raises(RuntimeError): + lazy_reference_proxy.resolve(False) + with pytest.raises(RuntimeError): + copy.copy(lazy_reference_proxy) + with pytest.raises(RuntimeError): + copy.deepcopy(lazy_reference_proxy) + with pytest.raises(RuntimeError): + lazy_reference_proxy.name + with pytest.raises(RuntimeError): + lazy_reference_proxy.default + with pytest.raises(RuntimeError): + lazy_reference_proxy.python_name + with pytest.raises(RuntimeError): + lazy_reference_proxy.template + + +def test_lazy_proxy_reference_resolved(): + import copy + + import yaml + + import openapi_python_client.schema as oai + from openapi_python_client.parser.properties import LazyReferencePropertyProxy, Schemas, build_schemas + + data = yaml.safe_load( + f""" +{_base_api_data()} +components: + schemas: + fooBar: + type: object + properties: + childSettings: + type: number +""" + ) + openapi = oai.OpenAPI.parse_obj(data) + schemas = build_schemas(components=openapi.components.schemas) + foobar = schemas.models.get("FooBar") + + LazyReferencePropertyProxy.update_schemas(schemas) + lazy_reference_proxy = LazyReferencePropertyProxy.create( + "childProperty", True, oai.Reference(ref="#/components/schemas/fooBar"), "AModel" + ) + + assert foobar + assert lazy_reference_proxy.get_instance_type_string() == foobar.get_instance_type_string() + assert lazy_reference_proxy.get_type_string(no_optional=False) == foobar.get_type_string(no_optional=False) + assert lazy_reference_proxy.get_type_string(no_optional=True) == foobar.get_type_string(no_optional=True) + assert lazy_reference_proxy.get_imports(prefix="..") == foobar.get_imports(prefix="..") + assert lazy_reference_proxy.name == "childProperty" and foobar.name == "fooBar" + assert lazy_reference_proxy.nullable == foobar.nullable + assert lazy_reference_proxy.default == foobar.default + assert lazy_reference_proxy.python_name == "child_property" and foobar.python_name == "foo_bar" + assert lazy_reference_proxy.template == foobar.template + try: + copy.copy(lazy_reference_proxy) + copy.deepcopy(lazy_reference_proxy) + except Exception as e: + pytest.fail(e) + + +def test_build_schemas_resolve_inner_property_remote_reference(): + import yaml + + import openapi_python_client.schema as oai + from openapi_python_client.parser.properties import Schemas, build_schemas + + data = yaml.safe_load( + f""" +{_base_api_data()} +components: + schemas: + fooBar: + type: object + properties: + childSettings: + type: array + items: + $ref: 'AnOtherDocument#/components/schemas/bar' +""" + ) + openapi = oai.OpenAPI.parse_obj(data) + + schemas = build_schemas(components=openapi.components.schemas) + + assert len(schemas.errors) == 1 + assert schemas.errors[0] == PropertyError( + data=oai.Reference(ref="AnOtherDocument#/components/schemas/bar"), + detail="invalid data in items of array childSettings", + ) + + +def test_build_schemas_lazy_resolve_inner_property_self_direct_reference(): + import yaml + + import openapi_python_client.schema as oai + from openapi_python_client.parser.properties import Schemas, build_schemas + + data = yaml.safe_load( + f""" +{_base_api_data()} +components: + schemas: + fooBar: + type: object + properties: + childSettings: + type: array + items: + $ref: '#/components/schemas/fooBar' +""" + ) + openapi = oai.OpenAPI.parse_obj(data) + + schemas = build_schemas(components=openapi.components.schemas) + + foo_bar = schemas.models.get("FooBar") + assert len(schemas.errors) == 0 + assert foo_bar + child_settings = foo_bar.optional_properties[0] + assert child_settings.inner_property.reference == foo_bar.reference + + +def test_build_schemas_lazy_resolve_known_inner_property_self_indirect_reference(): + import yaml + + import openapi_python_client.schema as oai + from openapi_python_client.parser.properties import Schemas, build_schemas + + data = yaml.safe_load( + f""" +{_base_api_data()} +components: + schemas: + fooBar: + type: object + properties: + childSettings: + type: array + description: test + items: + $ref: '#/components/schemas/FoobarSelfIndirectReference' + FoobarSelfIndirectReference: + $ref: '#/components/schemas/foobarSelfDeeperIndirectReference' + foobarSelfDeeperIndirectReference: + $ref: '#/components/schemas/fooBar' +""" + ) + openapi = oai.OpenAPI.parse_obj(data) + + schemas = build_schemas(components=openapi.components.schemas) + + assert len(schemas.errors) == 0 + foobar = schemas.models.get("FooBar") + foobar_indirect_ref = schemas.models.get("FoobarSelfIndirectReference") + foobar_deep_indirect_ref = schemas.models.get("FoobarSelfDeeperIndirectReference") + assert foobar is not None and foobar_indirect_ref is not None and foobar_deep_indirect_ref is not None + assert foobar == foobar_indirect_ref == foobar_deep_indirect_ref + + child_settings = foobar.optional_properties[0] + assert child_settings.inner_property.reference == foobar.reference diff --git a/tests/test_resolver/test_resolver_collision_resolver.py b/tests/test_resolver/test_resolver_collision_resolver.py new file mode 100644 index 000000000..0d9191a1c --- /dev/null +++ b/tests/test_resolver/test_resolver_collision_resolver.py @@ -0,0 +1,163 @@ +import pathlib +import urllib +import urllib.parse + +import pytest + + +def test__collision_resolver_get_schema_from_ref(): + + from openapi_python_client.resolver.collision_resolver import CollisionResolver + + root_schema = {"foo": {"$ref": "first_instance.yaml#/foo"}} + + external_schemas = {"/home/user/first_instance.yaml": {"food": {"description": "food_first_description"}}} + + errors = [] + + CollisionResolver(root_schema, external_schemas, errors, "/home/user").resolve() + + assert len(errors) == 1 + assert errors == ["Did not find data corresponding to the reference first_instance.yaml#/foo"] + + +def test__collision_resolver_duplicate_schema(): + + from openapi_python_client.resolver.collision_resolver import CollisionResolver + + root_schema = { + "foo": {"$ref": "first_instance.yaml#/foo"}, + "bar": {"$ref": "second_instance.yaml#/bar/foo"}, + } + + external_schemas = { + "/home/user/first_instance.yaml": {"foo": {"description": "foo_first_description"}}, + "/home/user/second_instance.yaml": {"bar": {"foo": {"description": "foo_first_description"}}}, + } + + errors = [] + + CollisionResolver(root_schema, external_schemas, errors, "/home/user").resolve() + + assert len(errors) == 1 + assert errors == ["Found a duplicate schema in first_instance.yaml#/foo and second_instance.yaml#/bar/foo"] + + +def test__collision_resolver(): + + from openapi_python_client.resolver.collision_resolver import CollisionResolver + + root_schema = { + "foobar": {"$ref": "first_instance.yaml#/foo"}, + "barfoo": {"$ref": "second_instance.yaml#/foo"}, + "barbarfoo": {"$ref": "third_instance.yaml#/foo"}, + "foobarfoo": {"$ref": "second_instance.yaml#/foo"}, + "barfoobar": {"$ref": "first_instance.yaml#/bar/foo"}, + "localref": {"$ref": "#/local_ref"}, + "local_ref": {"description": "a local ref"}, + "array": ["array_item_one", "array_item_two"], + "last": {"$ref": "first_instance.yaml#/fourth_instance"}, + "baz": {"$ref": "fifth_instance.yaml#/foo"}, + } + + external_schemas = { + "/home/user/first_instance.yaml": { + "foo": {"description": "foo_first_description"}, + "bar": {"foo": {"description": "nested foo"}}, + "fourth_instance": {"$ref": "fourth_instance.yaml#/foo"}, + }, + "/home/user/second_instance.yaml": { + "foo": {"description": "foo_second_description"}, + "another_local_ref": {"$ref": "#/foo"}, + }, + "/home/user/third_instance.yaml": {"foo": {"description": "foo_third_description"}}, + "/home/user/fourth_instance.yaml": {"foo": {"description": "foo_fourth_description"}}, + "/home/user/fifth_instance.yaml": {"foo": {"description": "foo_second_description"}}, + } + + root_schema_result = { + "foobar": {"$ref": "first_instance.yaml#/foo"}, + "barfoo": {"$ref": "second_instance.yaml#/foo_2"}, + "barbarfoo": {"$ref": "third_instance.yaml#/foo_3"}, + "foobarfoo": {"$ref": "second_instance.yaml#/foo_2"}, + "barfoobar": {"$ref": "first_instance.yaml#/bar/foo"}, + "localref": {"$ref": "#/local_ref"}, + "local_ref": {"description": "a local ref"}, + "array": ["array_item_one", "array_item_two"], + "last": {"$ref": "first_instance.yaml#/fourth_instance"}, + "baz": {"$ref": "fifth_instance.yaml#/foo_2"}, + } + + external_schemas_result = { + "/home/user/first_instance.yaml": { + "foo": {"description": "foo_first_description"}, + "bar": {"foo": {"description": "nested foo"}}, + "fourth_instance": {"$ref": "fourth_instance.yaml#/foo_4"}, + }, + "/home/user/second_instance.yaml": { + "foo_2": {"description": "foo_second_description"}, + "another_local_ref": {"$ref": "#/foo_2"}, + }, + "/home/user/third_instance.yaml": {"foo_3": {"description": "foo_third_description"}}, + "/home/user/fourth_instance.yaml": {"foo_4": {"description": "foo_fourth_description"}}, + "/home/user/fifth_instance.yaml": {"foo_2": {"description": "foo_second_description"}}, + } + + errors = [] + + CollisionResolver(root_schema, external_schemas, errors, "/home/user").resolve() + + assert len(errors) == 0 + assert root_schema == root_schema_result + assert external_schemas == external_schemas_result + + +def test__collision_resolver_deep_root_keys(): + + from openapi_python_client.resolver.collision_resolver import CollisionResolver + + root_schema = { + "foobar": {"$ref": "first_instance.yaml#/bar/foo"}, + "barfoo": {"$ref": "second_instance.yaml#/bar/foo"}, + "barfoobar": {"$ref": "second_instance.yaml#/barfoobar"}, + } + + external_schemas = { + "/home/user/first_instance.yaml": { + "bar": {"foo": {"description": "foo_first_description"}}, + }, + "/home/user/second_instance.yaml": { + "bar": {"foo": {"description": "foo_second_description"}}, + "barfoobar": { + "type": "object", + "allOf": [{"description": "first_description"}, {"description": "second_description"}], + }, + }, + } + + root_schema_result = { + "foobar": {"$ref": "first_instance.yaml#/bar/foo"}, + "barfoo": {"$ref": "second_instance.yaml#/bar/foo_2"}, + "barfoobar": {"$ref": "second_instance.yaml#/barfoobar"}, + } + + external_schemas_result = { + "/home/user/first_instance.yaml": { + "bar": {"foo": {"description": "foo_first_description"}}, + }, + "/home/user/second_instance.yaml": { + "bar": {"foo_2": {"description": "foo_second_description"}}, + "barfoobar": { + "type": "object", + "allOf": [{"description": "first_description"}, {"description": "second_description"}], + }, + }, + } + + errors = [] + + CollisionResolver(root_schema, external_schemas, errors, "/home/user").resolve() + + assert len(errors) == 0 + assert root_schema == root_schema_result + assert external_schemas == external_schemas_result diff --git a/tests/test_resolver/test_resolver_data_loader.py b/tests/test_resolver/test_resolver_data_loader.py new file mode 100644 index 000000000..271067ccd --- /dev/null +++ b/tests/test_resolver/test_resolver_data_loader.py @@ -0,0 +1,52 @@ +import pytest + + +def test_load(mocker): + from openapi_python_client.resolver.data_loader import DataLoader + + dl_load_json = mocker.patch("openapi_python_client.resolver.data_loader.DataLoader.load_json") + dl_load_yaml = mocker.patch("openapi_python_client.resolver.data_loader.DataLoader.load_yaml") + + content = mocker.MagicMock() + DataLoader.load("foobar.json", content) + dl_load_json.assert_called_once_with(content) + + content = mocker.MagicMock() + DataLoader.load("foobar.jSoN", content) + dl_load_json.assert_called_with(content) + + content = mocker.MagicMock() + DataLoader.load("foobar.yaml", content) + dl_load_yaml.assert_called_once_with(content) + + content = mocker.MagicMock() + DataLoader.load("foobar.yAmL", content) + dl_load_yaml.assert_called_with(content) + + content = mocker.MagicMock() + DataLoader.load("foobar.ymL", content) + dl_load_yaml.assert_called_with(content) + + content = mocker.MagicMock() + DataLoader.load("foobar", content) + dl_load_yaml.assert_called_with(content) + + +def test_load_yaml(mocker): + from openapi_python_client.resolver.data_loader import DataLoader + + yaml_safeload = mocker.patch("yaml.safe_load") + + content = mocker.MagicMock() + DataLoader.load_yaml(content) + yaml_safeload.assert_called_once_with(content) + + +def test_load_json(mocker): + from openapi_python_client.resolver.data_loader import DataLoader + + json_loads = mocker.patch("json.loads") + + content = mocker.MagicMock() + DataLoader.load_json(content) + json_loads.assert_called_once_with(content) diff --git a/tests/test_resolver/test_resolver_pointer.py b/tests/test_resolver/test_resolver_pointer.py new file mode 100644 index 000000000..92e1ded35 --- /dev/null +++ b/tests/test_resolver/test_resolver_pointer.py @@ -0,0 +1,97 @@ +import pytest + + +def get_data_set(): + # https://tools.ietf.org/html/rfc6901 + return { + "valid_pointers": [ + "/myElement", + "/definitions/myElement", + "", + "/foo", + "/foo/0", + "/", + "/a~1b", + "/c%d", + "/e^f", + "/g|h", + "/i\\j" '/k"l', + "/ ", + "/m~0n", + "/m~01", + ], + "invalid_pointers": ["../foo", "foobar", None], + "tokens_by_pointer": { + "/myElement": ["", "myElement"], + "/definitions/myElement": ["", "definitions", "myElement"], + "": [""], + "/foo": ["", "foo"], + "/foo/0": ["", "foo", "0"], + "/": ["", ""], + "/a~1b": ["", "a/b"], + "/c%d": ["", "c%d"], + "/e^f": ["", "e^f"], + "/g|h": ["", "g|h"], + "/i\\j": ["", "i\\j"], + '/k"l': ["", 'k"l'], + "/ ": ["", " "], + "/m~0n": ["", "m~n"], + "/m~01": ["", "m~1"], + }, + } + + +def test___init__(): + from openapi_python_client.resolver.pointer import Pointer + + data_set = get_data_set() + + for pointer_str in data_set["valid_pointers"]: + p = Pointer(pointer_str) + assert p.value != None + assert p.value == pointer_str + + for pointer_str in data_set["invalid_pointers"]: + with pytest.raises(ValueError): + p = Pointer(pointer_str) + + +def test_token(): + from openapi_python_client.resolver.pointer import Pointer + + data_set = get_data_set() + + for pointer_str in data_set["tokens_by_pointer"].keys(): + p = Pointer(pointer_str) + expected_tokens = data_set["tokens_by_pointer"][pointer_str] + + for idx, token in enumerate(p.tokens()): + assert expected_tokens[idx] == token + + +def test_parent(): + from openapi_python_client.resolver.pointer import Pointer + + data_set = get_data_set() + + for pointer_str in data_set["tokens_by_pointer"].keys(): + p = Pointer(pointer_str) + expected_tokens = data_set["tokens_by_pointer"][pointer_str] + + while p.parent is not None: + p = p.parent + expected_tokens.pop() + assert p.tokens()[-1] == expected_tokens[-1] + assert len(p.tokens()) == len(expected_tokens) + + assert len(expected_tokens) == 1 + assert expected_tokens[-1] == "" + + +def test__unescape_and__escape(): + from openapi_python_client.resolver.pointer import Pointer + + escaped_unescaped_values = [("/m~0n", "/m~n"), ("/m~01", "/m~1"), ("/a~1b", "/a/b"), ("/foobar", "/foobar")] + + for escaped, unescaped in escaped_unescaped_values: + assert Pointer(escaped).unescapated_value == unescaped diff --git a/tests/test_resolver/test_resolver_reference.py b/tests/test_resolver/test_resolver_reference.py new file mode 100644 index 000000000..bc13266b2 --- /dev/null +++ b/tests/test_resolver/test_resolver_reference.py @@ -0,0 +1,223 @@ +import pytest + + +def get_data_set(): + # https://swagger.io/docs/specification/using-ref/ + return { + "local_references": ["#/definitions/myElement"], + "remote_references": [ + "document.json#/myElement", + "../document.json#/myElement", + "../another-folder/document.json#/myElement", + ], + "url_references": [ + "http://path/to/your/resource", + "http://path/to/your/resource.json#myElement", + "//anotherserver.com/files/example.json", + ], + "relative_references": [ + "#/definitions/myElement", + "document.json#/myElement", + "../document.json#/myElement", + "../another-folder/document.json#/myElement", + ], + "absolute_references": [ + "http://path/to/your/resource", + "http://path/to/your/resource.json#myElement", + "//anotherserver.com/files/example.json", + ], + "full_document_references": [ + "http://path/to/your/resource", + "//anotherserver.com/files/example.json", + ], + "not_full_document_references": [ + "#/definitions/myElement", + "document.json#/myElement", + "../document.json#/myElement", + "../another-folder/document.json#/myElement", + "http://path/to/your/resource.json#myElement", + ], + "path_by_reference": { + "#/definitions/myElement": "", + "document.json#/myElement": "document.json", + "../document.json#/myElement": "../document.json", + "../another-folder/document.json#/myElement": "../another-folder/document.json", + "http://path/to/your/resource": "http://path/to/your/resource", + "http://path/to/your/resource.json#myElement": "http://path/to/your/resource.json", + "//anotherserver.com/files/example.json": "//anotherserver.com/files/example.json", + }, + "pointer_by_reference": { + "#/definitions/myElement": "/definitions/myElement", + "document.json#/myElement": "/myElement", + "../document.json#/myElement": "/myElement", + "../another-folder/document.json#/myElement": "/myElement", + "http://path/to/your/resource": "", + "http://path/to/your/resource.json#myElement": "/myElement", + "//anotherserver.com/files/example.json": "", + }, + "pointerparent_by_reference": { + "#/definitions/myElement": "/definitions", + "document.json#/myElement": "", + "../document.json#/myElement": "", + "../another-folder/document.json#/myElement": "", + "http://path/to/your/resource": None, + "http://path/to/your/resource.json#myElement": "", + "//anotherserver.com/files/example.json": None, + }, + } + + +def test_is_local(): + from openapi_python_client.resolver.reference import Reference + + data_set = get_data_set() + + for ref_str in data_set["local_references"]: + ref = Reference(ref_str) + assert ref.is_local() == True + + for ref_str in data_set["remote_references"]: + ref = Reference(ref_str) + assert ref.is_local() == False + + for ref_str in data_set["url_references"]: + ref = Reference(ref_str) + assert ref.is_local() == False + + +def test_is_remote(): + from openapi_python_client.resolver.reference import Reference + + data_set = get_data_set() + + for ref_str in data_set["local_references"]: + ref = Reference(ref_str) + assert ref.is_remote() == False + + for ref_str in data_set["remote_references"]: + ref = Reference(ref_str) + assert ref.is_remote() == True + + for ref_str in data_set["url_references"]: + ref = Reference(ref_str) + assert ref.is_remote() == True + + +def test_is_url(): + from openapi_python_client.resolver.reference import Reference + + data_set = get_data_set() + + for ref_str in data_set["local_references"]: + ref = Reference(ref_str) + assert ref.is_url() == False + + for ref_str in data_set["remote_references"]: + ref = Reference(ref_str) + assert ref.is_url() == False + + for ref_str in data_set["url_references"]: + ref = Reference(ref_str) + assert ref.is_url() == True + + +def test_is_absolute(): + from openapi_python_client.resolver.reference import Reference + + data_set = get_data_set() + + for ref_str in data_set["absolute_references"]: + ref = Reference(ref_str) + assert ref.is_absolute() == True + + for ref_str in data_set["relative_references"]: + ref = Reference(ref_str) + assert ref.is_absolute() == False + + +def test_is_relative(): + from openapi_python_client.resolver.reference import Reference + + data_set = get_data_set() + + for ref_str in data_set["absolute_references"]: + ref = Reference(ref_str) + assert ref.is_relative() == False + + for ref_str in data_set["relative_references"]: + ref = Reference(ref_str) + assert ref.is_relative() == True + + +def test_pointer(): + from openapi_python_client.resolver.reference import Reference + + data_set = get_data_set() + + for ref_str in data_set["pointer_by_reference"].keys(): + ref = Reference(ref_str) + pointer = data_set["pointer_by_reference"][ref_str] + assert ref.pointer.value == pointer + + +def test_pointer_parent(): + from openapi_python_client.resolver.reference import Reference + + data_set = get_data_set() + + for ref_str in data_set["pointerparent_by_reference"].keys(): + ref = Reference(ref_str) + pointer_parent = data_set["pointerparent_by_reference"][ref_str] + + if pointer_parent is not None: + assert ref.pointer.parent.value == pointer_parent + else: + assert ref.pointer.parent == None + + +def test_path(): + from openapi_python_client.resolver.reference import Reference + + data_set = get_data_set() + + for ref_str in data_set["path_by_reference"].keys(): + ref = Reference(ref_str) + path = data_set["path_by_reference"][ref_str] + assert ref.path == path + + +def test_abs_path(): + + from openapi_python_client.resolver.reference import Reference + + ref = Reference("foo.yaml#/foo") + ref_with_parent = Reference("foo.yaml#/foo", "/home/user") + + assert ref.abs_path == "foo.yaml" + assert ref_with_parent.abs_path == "/home/user/foo.yaml" + + +def test_is_full_document(): + from openapi_python_client.resolver.reference import Reference + + data_set = get_data_set() + + for ref_str in data_set["full_document_references"]: + ref = Reference(ref_str) + assert ref.is_full_document() == True + assert ref.pointer.parent == None + + for ref_str in data_set["not_full_document_references"]: + ref = Reference(ref_str) + assert ref.is_full_document() == False + assert ref.pointer.parent != None + + +def test_value(): + from openapi_python_client.resolver.reference import Reference + + ref = Reference("fooBaR") + assert ref.value == "fooBaR" + + ref = Reference("FooBAR") + assert ref.value == "FooBAR" diff --git a/tests/test_resolver/test_resolver_resolved_schema.py b/tests/test_resolver/test_resolver_resolved_schema.py new file mode 100644 index 000000000..3b3e6b9d8 --- /dev/null +++ b/tests/test_resolver/test_resolver_resolved_schema.py @@ -0,0 +1,170 @@ +import pathlib +import urllib +import urllib.parse + +import pytest + + +def test__resolved_schema_with_resolved_external_references(): + + from openapi_python_client.resolver.resolved_schema import ResolvedSchema + + root_schema = {"foobar": {"$ref": "foobar.yaml#/foo"}} + + external_schemas = { + "/home/user/foobar.yaml": {"foo": {"$ref": "/home/user/foobar_2.yaml#/foo"}}, + "/home/user/foobar_2.yaml": {"foo": {"description": "foobar_description"}}, + } + errors = [] + + resolved_schema = ResolvedSchema(root_schema, external_schemas, errors, "/home/user").schema + + assert len(errors) == 0 + assert "foo" in resolved_schema + assert "foobar" in resolved_schema + assert "$ref" in resolved_schema["foobar"] + assert "#/foo" in resolved_schema["foobar"]["$ref"] + assert "description" in resolved_schema["foo"] + assert "foobar_description" in resolved_schema["foo"]["description"] + + +def test__resolved_schema_with_depth_refs(): + + from openapi_python_client.resolver.resolved_schema import ResolvedSchema + + root_schema = {"foo": {"$ref": "foo.yaml#/foo"}, "bar": {"$ref": "bar.yaml#/bar"}} + + external_schemas = { + "/home/user/foo.yaml": {"foo": {"$ref": "bar.yaml#/bar"}}, + "/home/user/bar.yaml": {"bar": {"description": "bar"}}, + } + + errors = [] + + expected_result = {"foo": {"$ref": "#/bar"}, "bar": {"description": "bar"}} + + resolved_schema = ResolvedSchema(root_schema, external_schemas, errors, "/home/user").schema + + assert len(errors) == 0 + assert resolved_schema == expected_result + + +def test__resolved_schema_with_duplicate_ref(): + + from openapi_python_client.resolver.resolved_schema import ResolvedSchema + + root_schema = { + "foo": {"$ref": "foobar.yaml#/foo"}, + "bar": {"$ref": "foobar.yaml#/foo"}, + "list": [{"foobar": {"$ref": "foobar.yaml#/bar"}}, {"barfoo": {"$ref": "foobar.yaml#/bar2/foo"}}], + } + + external_schemas = { + "/home/user/foobar.yaml": { + "foo": {"description": "foo_description"}, + "bar": {"$ref": "#/foo"}, + "bar2": {"foo": {"description": "foo_second_description"}}, + }, + } + + errors = [] + + resolved_schema = ResolvedSchema(root_schema, external_schemas, errors, "/home/user").schema + + assert len(errors) == 0 + + +def test__resolved_schema_with_malformed_schema(): + + from openapi_python_client.resolver.resolved_schema import ResolvedSchema + + root_schema = { + "paths": { + "/foo/bar": {"$ref": "inexistant.yaml#/paths/~1foo~1bar"}, + "/bar": {"$ref": "foobar.yaml#/paths/~1bar"}, + }, + "foo": {"$ref": "inexistant.yaml#/foo"}, + } + + external_schemas = { + "/home/user/foobar.yaml": { + "paths": { + "/foo/bar": {"description": "foobar_description"}, + }, + }, + } + + errors = [] + + resolved_schema = ResolvedSchema(root_schema, external_schemas, errors, "/home/user").schema + + assert len(errors) == 4 + assert errors == [ + "Failed to resolve remote reference > /home/user/inexistant.yaml", + "Failed to read remote value /paths//bar, in remote ref /home/user/foobar.yaml", + "Failed to resolve remote reference > /home/user/inexistant.yaml", + "Failed to resolve remote reference > /home/user/inexistant.yaml", + ] + + +def test__resolved_schema_with_remote_paths(): + + from openapi_python_client.resolver.resolved_schema import ResolvedSchema + + root_schema = { + "paths": { + "/foo/bar": {"$ref": "foobar.yaml#/paths/~1foo~1bar"}, + "/foo/bar2": {"$ref": "#/bar2"}, + }, + "bar2": {"description": "bar2_description"}, + } + + external_schemas = { + "/home/user/foobar.yaml": { + "paths": { + "/foo/bar": {"description": "foobar_description"}, + }, + }, + } + + expected_result = { + "paths": {"/foo/bar": {"description": "foobar_description"}, "/foo/bar2": {"$ref": "#/bar2"}}, + "bar2": {"description": "bar2_description"}, + } + + errors = [] + + resolved_schema = ResolvedSchema(root_schema, external_schemas, errors, "/home/user").schema + + assert len(errors) == 0 + assert resolved_schema == expected_result + + +def test__resolved_schema_with_absolute_paths(): + + from openapi_python_client.resolver.resolved_schema import ResolvedSchema + + root_schema = {"foobar": {"$ref": "foobar.yaml#/foo"}, "barfoo": {"$ref": "../barfoo.yaml#/bar"}} + + external_schemas = { + "/home/user/foobar.yaml": {"foo": {"description": "foobar_description"}}, + "/home/barfoo.yaml": {"bar": {"description": "barfoo_description"}}, + } + + errors = [] + + resolved_schema = ResolvedSchema(root_schema, external_schemas, errors, "/home/user").schema + + assert len(errors) == 0 + assert "foo" in resolved_schema + assert "bar" in resolved_schema + assert "foobar" in resolved_schema + assert "barfoo" in resolved_schema + assert "$ref" in resolved_schema["foobar"] + assert "#/foo" in resolved_schema["foobar"]["$ref"] + assert "$ref" in resolved_schema["barfoo"] + assert "#/bar" in resolved_schema["barfoo"]["$ref"] + assert "description" in resolved_schema["foo"] + assert "foobar_description" in resolved_schema["foo"]["description"] + assert "description" in resolved_schema["bar"] + assert "barfoo_description" in resolved_schema["bar"]["description"] diff --git a/tests/test_resolver/test_resolver_schema_resolver.py b/tests/test_resolver/test_resolver_schema_resolver.py new file mode 100644 index 000000000..36caa3d7e --- /dev/null +++ b/tests/test_resolver/test_resolver_schema_resolver.py @@ -0,0 +1,267 @@ +import pathlib +import urllib +import urllib.parse + +import pytest + + +def test___init__invalid_data(mocker): + from openapi_python_client.resolver.schema_resolver import SchemaResolver + + with pytest.raises(ValueError): + SchemaResolver(None) + + invalid_url = "foobar" + with pytest.raises(ValueError): + SchemaResolver(invalid_url) + + invalid_url = 42 + with pytest.raises(urllib.error.URLError): + SchemaResolver(invalid_url) + + invalid_url = mocker.Mock() + with pytest.raises(urllib.error.URLError): + SchemaResolver(invalid_url) + + +def test__init_with_filepath(mocker): + mocker.patch("openapi_python_client.resolver.schema_resolver.SchemaResolver._isapath", return_value=True) + mocker.patch("openapi_python_client.resolver.schema_resolver.DataLoader.load", return_value={}) + path = mocker.MagicMock() + + from openapi_python_client.resolver.schema_resolver import SchemaResolver + + resolver = SchemaResolver(path) + resolver.resolve() + + path.absolute().read_bytes.assert_called_once() + + +def test__init_with_url(mocker): + mocker.patch("openapi_python_client.resolver.schema_resolver.DataLoader.load", return_value={}) + url_parse = mocker.patch( + "urllib.parse.urlparse", + return_value=urllib.parse.ParseResult( + scheme="http", netloc="foobar.io", path="foo", params="", query="", fragment="/bar" + ), + ) + get = mocker.patch("httpx.get") + + url = mocker.MagicMock() + + from openapi_python_client.resolver.schema_resolver import SchemaResolver + + resolver = SchemaResolver(url) + resolver.resolve() + + url_parse.assert_called_once_with(url) + get.assert_called_once() + + +def test__resolve_schema_references_with_path(mocker): + read_bytes = mocker.patch("pathlib.Path.read_bytes") + + from openapi_python_client.resolver.schema_resolver import SchemaResolver + + path = pathlib.Path("/foo/bar/foobar") + path_parent = str(path.parent) + schema = {"foo": {"$ref": "foobar#/foobar"}} + external_schemas = {} + errors = [] + + def _datalaod_mocked_result(path, data): + if path == "/foo/bar/foobar": + return {"foobar": "bar", "bar": {"$ref": "bar#/foobar"}, "local": {"$ref": "#/toto"}} + + if path == "/foo/bar/bar": + return {"foobar": "bar", "bar": {"$ref": "../bar#/foobar"}} + + if path == "/foo/bar": + return {"foobar": "bar/bar", "bar": {"$ref": "/barfoo.io/foobar#foobar"}} + + if path == "/barfoo.io/foobar": + return {"foobar": "barfoo.io/foobar", "bar": {"$ref": "./bar#foobar"}} + + if path == "/barfoo.io/bar": + return {"foobar": "barfoo.io/bar", "bar": {"$ref": "/bar.foo/foobar"}} + + if path == "/bar.foo/foobar": + return {"foobar": "bar.foo/foobar", "bar": {"$ref": "/foo.bar/foobar"}} + + if path == "/foo.bar/foobar": + return {"foobar": "foo.bar/foobar", "bar": {"$ref": "/foo/bar/foobar"}} # Loop to first path + + raise ValueError(f"Unexpected path {path}") + + mocker.patch("openapi_python_client.resolver.schema_resolver.DataLoader.load", _datalaod_mocked_result) + resolver = SchemaResolver(path) + resolver._resolve_schema_references(path_parent, schema, external_schemas, errors, True) + + assert len(errors) == 0 + assert "/foo/bar/foobar" in external_schemas + assert "/foo/bar/bar" in external_schemas + assert "/foo/bar" in external_schemas + assert "/barfoo.io/foobar" in external_schemas + assert "/barfoo.io/bar" in external_schemas + assert "/bar.foo/foobar" in external_schemas + assert "/foo.bar/foobar" in external_schemas + + +def test__resolve_schema_references_with_url(mocker): + get = mocker.patch("httpx.get") + + from openapi_python_client.resolver.schema_resolver import SchemaResolver + + url = "http://foobar.io/foo/bar/foobar" + url_parent = "http://foobar.io/foo/bar/" + schema = {"foo": {"$ref": "foobar#/foobar"}} + external_schemas = {} + errors = [] + + def _datalaod_mocked_result(url, data): + if url == "http://foobar.io/foo/bar/foobar": + return {"foobar": "bar", "bar": {"$ref": "bar#/foobar"}, "local": {"$ref": "#/toto"}} + + if url == "http://foobar.io/foo/bar/bar": + return {"foobar": "bar", "bar": {"$ref": "../bar#/foobar"}} + + if url == "http://foobar.io/foo/bar": + return {"foobar": "bar/bar", "bar": {"$ref": "//barfoo.io/foobar#foobar"}} + + if url == "http://barfoo.io/foobar": + return {"foobar": "barfoo.io/foobar", "bar": {"$ref": "./bar#foobar"}} + + if url == "http://barfoo.io/bar": + return {"foobar": "barfoo.io/bar", "bar": {"$ref": "https://bar.foo/foobar"}} + + if url == "https://bar.foo/foobar": + return {"foobar": "bar.foo/foobar", "bar": {"$ref": "//foo.bar/foobar"}} + + if url == "https://foo.bar/foobar": + return {"foobar": "foo.bar/foobar", "bar": {"$ref": "http://foobar.io/foo/bar/foobar"}} # Loop to first uri + + raise ValueError(f"Unexpected url {url}") + + mocker.patch("openapi_python_client.resolver.schema_resolver.DataLoader.load", _datalaod_mocked_result) + + resolver = SchemaResolver(url) + resolver._resolve_schema_references(url_parent, schema, external_schemas, errors, True) + + assert len(errors) == 0 + assert "http://foobar.io/foo/bar/bar" in external_schemas + assert "http://foobar.io/foo/bar" in external_schemas + assert "http://barfoo.io/foobar" in external_schemas + assert "http://barfoo.io/foobar" in external_schemas + assert "http://barfoo.io/bar" in external_schemas + assert "https://bar.foo/foobar" in external_schemas + assert "https://foo.bar/foobar" in external_schemas + + +def test__resolve_schema_references_mix_path_and_url(mocker): + read_bytes = mocker.patch("pathlib.Path.read_bytes") + get = mocker.patch("httpx.get") + + from openapi_python_client.resolver.schema_resolver import SchemaResolver + + path = pathlib.Path("/foo/bar/foobar") + path_parent = str(path.parent) + schema = {"foo": {"$ref": "foobar#/foobar"}} + external_schemas = {} + errors = [] + + def _datalaod_mocked_result(path, data): + if path == "/foo/bar/foobar": + return {"foobar": "bar", "bar": {"$ref": "bar#/foobar"}, "local": {"$ref": "#/toto"}} + + if path == "/foo/bar/bar": + return {"foobar": "bar", "bar": {"$ref": "../bar#/foobar"}} + + if path == "/foo/bar": + return {"foobar": "bar/bar", "bar": {"$ref": "//barfoo.io/foobar#foobar"}} + + if path == "http://barfoo.io/foobar": + return {"foobar": "barfoo.io/foobar", "bar": {"$ref": "./bar#foobar"}} + + if path == "http://barfoo.io/bar": + return {"foobar": "barfoo.io/bar", "bar": {"$ref": "https://bar.foo/foobar"}} + + if path == "https://bar.foo/foobar": + return {"foobar": "bar.foo/foobar", "bar": {"$ref": "//foo.bar/foobar"}} + + if path == "https://foo.bar/foobar": + return {"foobar": "foo.bar/foobar"} + + raise ValueError(f"Unexpected path {path}") + + mocker.patch("openapi_python_client.resolver.schema_resolver.DataLoader.load", _datalaod_mocked_result) + resolver = SchemaResolver(path) + resolver._resolve_schema_references(path_parent, schema, external_schemas, errors, True) + + assert len(errors) == 0 + assert "/foo/bar/foobar" in external_schemas + assert "/foo/bar/bar" in external_schemas + assert "/foo/bar" in external_schemas + assert "http://barfoo.io/foobar" in external_schemas + assert "http://barfoo.io/bar" in external_schemas + assert "https://bar.foo/foobar" in external_schemas + assert "https://foo.bar/foobar" in external_schemas + + +def test__resolve_schema_references_with_error(mocker): + get = mocker.patch("httpx.get") + + import httpcore + + from openapi_python_client.resolver.schema_resolver import SchemaResolver + + url = "http://foobar.io/foo/bar/foobar" + url_parent = "http://foobar.io/foo/bar/" + schema = {"foo": {"$ref": "foobar#/foobar"}} + external_schemas = {} + errors = [] + + def _datalaod_mocked_result(url, data): + if url == "http://foobar.io/foo/bar/foobar": + return { + "foobar": "bar", + "bar": {"$ref": "bar#/foobar"}, + "barfoor": {"$ref": "barfoo#foobar"}, + "local": {"$ref": "#/toto"}, + } + + if url == "http://foobar.io/foo/bar/bar": + raise httpcore.NetworkError("mocked error") + + if url == "http://foobar.io/foo/bar/barfoo": + return {"foobar": "foo/bar/barfoo", "bar": {"$ref": "//barfoo.io/foobar#foobar"}} + + if url == "http://barfoo.io/foobar": + return {"foobar": "foobar"} + + mocker.patch("openapi_python_client.resolver.schema_resolver.DataLoader.load", _datalaod_mocked_result) + resolver = SchemaResolver(url) + resolver._resolve_schema_references(url_parent, schema, external_schemas, errors, True) + + assert len(errors) == 1 + assert errors[0] == "Failed to gather external reference data of bar#/foobar from http://foobar.io/foo/bar/bar" + assert "http://foobar.io/foo/bar/bar" not in external_schemas + assert "http://foobar.io/foo/bar/foobar" in external_schemas + assert "http://foobar.io/foo/bar/barfoo" in external_schemas + assert "http://barfoo.io/foobar" in external_schemas + + +def test___lookup_schema_references(): + from openapi_python_client.resolver.schema_resolver import SchemaResolver + + data_set = { + "foo": {"$ref": "#/ref_1"}, + "bar": {"foobar": {"$ref": "#/ref_2"}}, + "foobar": [{"foo": {"$ref": "#/ref_3"}}, {"bar": [{"foobar": {"$ref": "#/ref_4"}}]}], + } + + resolver = SchemaResolver("http://foobar.io") + expected_references = sorted([f"#/ref_{x}" for x in range(1, 5)]) + references = sorted([x.value for x in resolver._lookup_schema_references(data_set)]) + + for idx, ref in enumerate(references): + assert expected_references[idx] == ref