Skip to content

Commit

Permalink
chore: ruff migrations
Browse files Browse the repository at this point in the history
  • Loading branch information
azmeuk committed Oct 15, 2024
1 parent 0a7d451 commit c1db105
Show file tree
Hide file tree
Showing 19 changed files with 76 additions and 103 deletions.
28 changes: 12 additions & 16 deletions scim2_models/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,12 +4,8 @@
from inspect import isclass
from typing import Annotated
from typing import Any
from typing import Dict
from typing import Generic
from typing import List
from typing import Optional
from typing import Tuple
from typing import Type
from typing import TypeVar
from typing import Union
from typing import get_args
Expand Down Expand Up @@ -41,7 +37,7 @@
ExternalReference = NewType("ExternalReference", str)


def validate_model_attribute(model: Type, attribute_base: str) -> None:
def validate_model_attribute(model: type["BaseModel"], attribute_base: str) -> None:
"""Validate that an attribute name or a sub-attribute path exist for a
given model."""

Expand All @@ -68,7 +64,7 @@ def validate_model_attribute(model: Type, attribute_base: str) -> None:
validate_model_attribute(attribute_type, sub_attribute_base)


def extract_schema_and_attribute_base(attribute_urn: str) -> Tuple[str, str]:
def extract_schema_and_attribute_base(attribute_urn: str) -> tuple[str, str]:
# Extract the schema urn part and the attribute name part from attribute
# name, as defined in :rfc:`RFC7644 §3.10 <7644#section-3.10>`.

Expand All @@ -79,8 +75,8 @@ def extract_schema_and_attribute_base(attribute_urn: str) -> Tuple[str, str]:

def validate_attribute_urn(
attribute_name: str,
default_resource: Optional[Type] = None,
resource_types: Optional[List[Type]] = None,
default_resource: Optional[type["BaseModel"]] = None,
resource_types: Optional[list[type["BaseModel"]]] = None,
) -> str:
"""Validate that an attribute urn is valid or not.
Expand Down Expand Up @@ -120,7 +116,7 @@ def validate_attribute_urn(
return f"{schema}:{attribute_base}"


def contains_attribute_or_subattributes(attribute_urns: List[str], attribute_urn: str):
def contains_attribute_or_subattributes(attribute_urns: list[str], attribute_urn: str):
return attribute_urn in attribute_urns or any(
item.startswith(f"{attribute_urn}.") or item.startswith(f"{attribute_urn}:")
for item in attribute_urns
Expand Down Expand Up @@ -424,7 +420,7 @@ class BaseModel(PydanticBaseModel):
)

@classmethod
def get_field_annotation(cls, field_name: str, annotation_type: Type) -> Any:
def get_field_annotation(cls, field_name: str, annotation_type: type) -> Any:
"""Return the annotation of type 'annotation_type' of the field
'field_name'."""
field_metadata = cls.model_fields[field_name].metadata
Expand All @@ -440,7 +436,7 @@ def annotation_type_filter(item):
return field_annotation

@classmethod
def get_field_root_type(cls, attribute_name: str) -> Type:
def get_field_root_type(cls, attribute_name: str) -> type:
"""Extract the root type from a model field.
For example, return 'GroupMember' for
Expand All @@ -455,7 +451,7 @@ def get_field_root_type(cls, attribute_name: str) -> Type:

# extract 'x' from 'List[x]'
if isclass(get_origin(attribute_type)) and issubclass(
get_origin(attribute_type), List
get_origin(attribute_type), list
):
attribute_type = get_args(attribute_type)[0]

Expand Down Expand Up @@ -727,7 +723,7 @@ def scim_response_serializer(self, value: Any, info: SerializationInfo) -> Any:
@model_serializer(mode="wrap")
def model_serializer_exclude_none(
self, handler, info: SerializationInfo
) -> Dict[str, Any]:
) -> dict[str, Any]:
"""Remove `None` values inserted by the
:meth:`~scim2_models.base.BaseModel.scim_serializer`."""

Expand All @@ -749,8 +745,8 @@ def model_dump(
self,
*args,
scim_ctx: Optional[Context] = Context.DEFAULT,
attributes: Optional[List[str]] = None,
excluded_attributes: Optional[List[str]] = None,
attributes: Optional[list[str]] = None,
excluded_attributes: Optional[list[str]] = None,
**kwargs,
):
"""Create a model representation that can be included in SCIM messages
Expand Down Expand Up @@ -834,4 +830,4 @@ def is_complex_attribute(type) -> bool:
)


BaseModelType: Type = type(BaseModel)
BaseModelType: type = type(BaseModel)
3 changes: 1 addition & 2 deletions scim2_models/rfc7643/enterprise_user.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from typing import Annotated
from typing import List
from typing import Literal
from typing import Optional

Expand Down Expand Up @@ -27,7 +26,7 @@ class Manager(ComplexAttribute):


class EnterpriseUser(Extension):
schemas: List[str] = ["urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"]
schemas: list[str] = ["urn:ietf:params:scim:schemas:extension:enterprise:2.0:User"]

employee_number: Optional[str] = None
"""Numeric or alphanumeric identifier assigned to a person, typically based
Expand Down
5 changes: 2 additions & 3 deletions scim2_models/rfc7643/group.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from typing import Annotated
from typing import List
from typing import Literal
from typing import Optional
from typing import Union
Expand Down Expand Up @@ -32,10 +31,10 @@ class GroupMember(MultiValuedComplexAttribute):


class Group(Resource):
schemas: List[str] = ["urn:ietf:params:scim:schemas:core:2.0:Group"]
schemas: list[str] = ["urn:ietf:params:scim:schemas:core:2.0:Group"]

display_name: Optional[str] = None
"""A human-readable name for the Group."""

members: Optional[List[GroupMember]] = None
members: Optional[list[GroupMember]] = None
"""A list of members of the Group."""
21 changes: 9 additions & 12 deletions scim2_models/rfc7643/resource.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
from datetime import datetime
from typing import Annotated
from typing import Any
from typing import Dict
from typing import Generic
from typing import List
from typing import Optional
from typing import Type
from typing import TypeVar
from typing import Union
from typing import get_args
Expand Down Expand Up @@ -105,7 +102,7 @@ def from_schema(cls, schema) -> "Extension":
AnyExtension = TypeVar("AnyExtension", bound="Extension")


def extension_serializer(value: Any, handler, info) -> Optional[Dict[str, Any]]:
def extension_serializer(value: Any, handler, info) -> Optional[dict[str, Any]]:
"""Exclude the Resource attributes from the extension dump.
For instance, attributes 'meta', 'id' or 'schemas' should not be
Expand Down Expand Up @@ -149,7 +146,7 @@ def __new__(cls, name, bases, attrs, **kwargs):


class Resource(BaseModel, Generic[AnyExtension], metaclass=ResourceMetaclass):
schemas: List[str]
schemas: list[str]
"""The "schemas" attribute is a REQUIRED attribute and is an array of
Strings containing URIs that are used to indicate the namespaces of the
SCIM schemas that define the attributes present in the current JSON
Expand Down Expand Up @@ -190,7 +187,7 @@ def __setitem__(self, item: Any, value: "Resource"):
setattr(self, item.__name__, value)

@classmethod
def get_extension_models(cls) -> Dict[str, Type]:
def get_extension_models(cls) -> dict[str, type]:
"""Return extension a dict associating extension models with their
schemas."""

Expand All @@ -208,8 +205,8 @@ def get_extension_models(cls) -> Dict[str, Type]:

@staticmethod
def get_by_schema(
resource_types: List[Type], schema: str, with_extensions=True
) -> Optional[Type]:
resource_types: list[type[BaseModel]], schema: str, with_extensions=True
) -> Optional[type]:
"""Given a resource type list and a schema, find the matching resource
type."""

Expand All @@ -229,7 +226,7 @@ def get_by_schema(
return by_schema.get(schema.lower())

@staticmethod
def get_by_payload(resource_types: List[Type], payload: Dict, **kwargs):
def get_by_payload(resource_types: list[type], payload: dict, **kwargs):
"""Given a resource type list and a payload, find the matching resource
type."""

Expand All @@ -240,7 +237,7 @@ def get_by_payload(resource_types: List[Type], payload: Dict, **kwargs):
return Resource.get_by_schema(resource_types, schema, **kwargs)

@field_serializer("schemas")
def set_extension_schemas(self, schemas: List[str]):
def set_extension_schemas(self, schemas: list[str]):
"""Add model extension ids to the 'schemas' attribute."""

extension_schemas = self.get_extension_models().keys()
Expand Down Expand Up @@ -299,7 +296,7 @@ def compare_field_infos(fi1, fi2):
return field_infos


def model_to_schema(model: Type):
def model_to_schema(model: type[BaseModel]):
from scim2_models.rfc7643.schema import Schema

schema_urn = model.model_fields["schemas"].default[0]
Expand All @@ -318,7 +315,7 @@ def model_to_schema(model: Type):
return schema


def get_reference_types(type) -> List[str]:
def get_reference_types(type) -> list[str]:
first_arg = get_args(type)[0]
types = get_args(first_arg) if get_origin(first_arg) == Union else [first_arg]

Expand Down
5 changes: 2 additions & 3 deletions scim2_models/rfc7643/resource_type.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
from typing import Annotated
from typing import List
from typing import Optional

from pydantic import Field
Expand Down Expand Up @@ -35,7 +34,7 @@ class SchemaExtension(ComplexAttribute):


class ResourceType(Resource):
schemas: List[str] = ["urn:ietf:params:scim:schemas:core:2.0:ResourceType"]
schemas: list[str] = ["urn:ietf:params:scim:schemas:core:2.0:ResourceType"]

name: Annotated[Optional[str], Mutability.read_only, Required.true] = None
"""The resource type name.
Expand Down Expand Up @@ -71,6 +70,6 @@ class ResourceType(Resource):
"""The resource type's primary/base schema URI."""

schema_extensions: Annotated[
Optional[List[SchemaExtension]], Mutability.read_only, Required.true
Optional[list[SchemaExtension]], Mutability.read_only, Required.true
] = None
"""A list of URIs of the resource type's schema extensions."""
25 changes: 11 additions & 14 deletions scim2_models/rfc7643/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,8 @@
from enum import Enum
from typing import Annotated
from typing import Any
from typing import List
from typing import Literal
from typing import Optional
from typing import Tuple
from typing import Type
from typing import Union
from typing import get_origin

Expand Down Expand Up @@ -47,7 +44,7 @@ def make_python_identifier(identifier: str) -> str:


def make_python_model(
obj: Union["Schema", "Attribute"], base: Optional[Type] = None, multiple=False
obj: Union["Schema", "Attribute"], base: Optional[type] = None, multiple=False
) -> "Resource":
"""Build a Python model from a Schema or an Attribute object."""

Expand All @@ -66,7 +63,7 @@ def make_python_model(
if attr.name
}
pydantic_attributes["schemas"] = (
Optional[List[str]],
Optional[list[str]],
Field(default=[obj.id]),
)

Expand Down Expand Up @@ -97,8 +94,8 @@ class Type(str, Enum):
def to_python(
self,
multiple=False,
reference_types: Optional[List[str]] = None,
) -> Type:
reference_types: Optional[list[str]] = None,
) -> type:
if self.value == self.reference and reference_types is not None:
if reference_types == ["external"]:
return Reference[ExternalReference]
Expand Down Expand Up @@ -166,7 +163,7 @@ def from_python(cls, pytype) -> str:
required."""

canonical_values: Annotated[
Optional[List[str]], Mutability.read_only, CaseExact.true
Optional[list[str]], Mutability.read_only, CaseExact.true
] = None
"""A collection of suggested canonical values that MAY be used (e.g.,
"work" and "home")."""
Expand Down Expand Up @@ -197,16 +194,16 @@ def from_python(cls, pytype) -> str:
uniqueness of attribute values."""

reference_types: Annotated[
Optional[List[str]], Mutability.read_only, Required.false, CaseExact.true
Optional[list[str]], Mutability.read_only, Required.false, CaseExact.true
] = None
"""A multi-valued array of JSON strings that indicate the SCIM resource
types that may be referenced."""

sub_attributes: Annotated[Optional[List["Attribute"]], Mutability.read_only] = None
sub_attributes: Annotated[Optional[list["Attribute"]], Mutability.read_only] = None
"""When an attribute is of type "complex", "subAttributes" defines a set of
sub-attributes."""

def to_python(self) -> Optional[Tuple[Any, Field]]:
def to_python(self) -> Optional[tuple[Any, Field]]:
"""Build tuple suited to be passed to pydantic 'create_model'."""

if not self.name:
Expand All @@ -218,7 +215,7 @@ def to_python(self) -> Optional[Tuple[Any, Field]]:
attr_type = make_python_model(obj=self, multiple=self.multi_valued)

if self.multi_valued:
attr_type = List[attr_type] # type: ignore
attr_type = list[attr_type] # type: ignore

annotation = Annotated[
Optional[attr_type], # type: ignore
Expand All @@ -241,7 +238,7 @@ def to_python(self) -> Optional[Tuple[Any, Field]]:


class Schema(Resource):
schemas: List[str] = ["urn:ietf:params:scim:schemas:core:2.0:Schema"]
schemas: list[str] = ["urn:ietf:params:scim:schemas:core:2.0:Schema"]

id: Annotated[Optional[str], Mutability.read_only, Required.true] = None
"""The unique URI of the schema."""
Expand All @@ -255,7 +252,7 @@ class Schema(Resource):
"""The schema's human-readable description."""

attributes: Annotated[
Optional[List[Attribute]], Mutability.read_only, Required.true
Optional[list[Attribute]], Mutability.read_only, Required.true
] = None
"""A complex type that defines service provider attributes and their
qualities via the following set of sub-attributes."""
Expand Down
5 changes: 2 additions & 3 deletions scim2_models/rfc7643/service_provider_config.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
from enum import Enum
from typing import Annotated
from typing import List
from typing import Optional

from pydantic import Field
Expand Down Expand Up @@ -95,7 +94,7 @@ class Type(str, Enum):


class ServiceProviderConfig(Resource):
schemas: List[str] = ["urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"]
schemas: list[str] = ["urn:ietf:params:scim:schemas:core:2.0:ServiceProviderConfig"]

id: Annotated[
Optional[str], Mutability.read_only, Returned.default, Uniqueness.global_
Expand Down Expand Up @@ -135,7 +134,7 @@ class ServiceProviderConfig(Resource):
"""A complex type that specifies ETag configuration options."""

authentication_schemes: Annotated[
Optional[List[AuthenticationScheme]], Mutability.read_only, Required.true
Optional[list[AuthenticationScheme]], Mutability.read_only, Required.true
] = None
"""A complex type that specifies supported authentication scheme
properties."""
Loading

0 comments on commit c1db105

Please sign in to comment.