Skip to content

Commit

Permalink
fix: ordering of generated schema
Browse files Browse the repository at this point in the history
  • Loading branch information
ketozhang committed Aug 26, 2024
1 parent e5eb795 commit 21962f9
Show file tree
Hide file tree
Showing 4 changed files with 44 additions and 3 deletions.
6 changes: 6 additions & 0 deletions .pre-commit-config.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,12 @@ repos:
hooks:
- id: black

- repo: https://github.com/compilerla/conventional-pre-commit
rev: v3.4.0
hooks:
- id: conventional-pre-commit
stages: [commit-msg]

ci:
# autofix_commit_msg: |
# [pre-commit.ci] auto fixes from pre-commit.com hooks
Expand Down
2 changes: 1 addition & 1 deletion asdf_pydantic/model.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,7 +72,7 @@ def model_asdf_schema(
)
json_schema = schema_generator_instance.generate(cls.__pydantic_core_schema__)

return f"%YAML 1.1\n---\n{yaml.safe_dump(json_schema)}"
return f"%YAML 1.1\n---\n{yaml.safe_dump(json_schema, sort_keys=False)}"

@classmethod
@deprecated(
Expand Down
22 changes: 21 additions & 1 deletion asdf_pydantic/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,17 @@
from pydantic.json_schema import GenerateJsonSchema

DEFAULT_ASDF_SCHEMA_REF_TEMPLATE = "#/definitions/{model}"
DESIRED_ASDF_SCHEMA_KEY_ORDER = (
"$schema",
"id",
"title",
"type",
"properties",
"allOf",
"anyOf",
"required",
"$defs",
)


class GenerateAsdfSchema(GenerateJsonSchema):
Expand Down Expand Up @@ -33,7 +44,16 @@ def generate(self, schema, mode="validation"):
if self.tag_uri:
json_schema["$schema"] = self.schema_dialect
json_schema["id"] = f"{self.tag_uri}/schema"
json_schema["tag"] = f"tag:{self.tag_uri.split('://', maxsplit=2)[-1]}"

# Order keys
json_schema = {
**{
key: json_schema[key]
for key in DESIRED_ASDF_SCHEMA_KEY_ORDER
if key in json_schema
},
**json_schema, # Rest of the keys not in order list
}

# TODO: Convert jsonschema 2020-12 to ASDF schema
return json_schema
17 changes: 16 additions & 1 deletion tests/test_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,8 +52,23 @@ class TestModel(AsdfPydanticModel):


########################################################################################
# SCHEMA
# GENERATED SCHEMA
########################################################################################
def test_generated_schema_keys_in_order():
class TestModel(AsdfPydanticModel):
_tag = "asdf://asdf-pydantic/tags/test-0.0.1"
foo: str

assert list(yaml.safe_load(TestModel.model_asdf_schema()).keys()) == [
"$schema",
"id",
"title",
"type",
"properties",
"required",
]


def test_generated_schema_id_uses_tag_in_pattern():
class TestModel(AsdfPydanticModel):
_tag = "asdf://asdf-pydantic/tags/test-0.0.1"
Expand Down

0 comments on commit 21962f9

Please sign in to comment.