Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

marshmallow_utils: include DynamicSanitizedHTML #191

Merged
merged 1 commit into from
Dec 7, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 42 additions & 8 deletions invenio_administration/marshmallow_utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
#
# This file is part of Invenio.
# Copyright (C) 2022 CERN.
#
# Copyright (C) 2023 KTH Royal Institute of Technology.
# Invenio is free software; you can redistribute it and/or modify it
# under the terms of the MIT License; see LICENSE file for more details.

Expand Down Expand Up @@ -55,6 +55,29 @@
}


def find_type_in_mapping(field_type, custom_mapping):
"""
Find a field type by traversing the inheritance chain.

Args:
field_type (Type): The field type to be searched.
custom_mapping (dict): The mapping of types.

Returns:
The mapped value for the found field type.

Raises:
KeyError: If the field type is not found in the mapping.
"""
current_type = field_type
while current_type:
if current_type in custom_mapping:
return custom_mapping[current_type]
current_type = current_type.__base__

raise KeyError(f"Unrecognized field type: {field_type}")


def jsonify_schema(schema):
"""Marshmallow schema to dict."""
schema_dict = {}
Expand Down Expand Up @@ -105,15 +128,26 @@ def jsonify_schema(schema):
})
elif list_field and not isinstance(field_type.inner, fields.Nested):
# list of plain types
schema_dict[field].update({
"type": "array",
"items": {"type": custom_mapping[field_type.inner.__class__]},
})
schema_dict[field].update(
{
"type": "array",
"items": {"type": find_type_in_mapping(
field_type.inner.__class__,
custom_mapping
)},
}
)
else:
try:
schema_dict[field].update({
"type": custom_mapping[field_type_name],
})
field_type_mapping = find_type_in_mapping(
field_type_name,
custom_mapping
)
schema_dict[field].update(
{
"type": field_type_mapping,
}
)
except KeyError:
raise Exception(f"Unrecognised schema field {field}: {field_type_name}")
return schema_dict
92 changes: 92 additions & 0 deletions tests/test_marshmallow_utils.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,92 @@
# -*- coding: utf-8 -*-
#
# Copyright (C) 2023 CERN.
# Copyright (C) 2023 KTH Royal Institute of Technology.
#
# invenio-administration is free software; you can redistribute it and/or
# modify it under the terms of the MIT License; see LICENSE file for more
# details.

import pytest
from marshmallow import Schema, fields

from invenio_administration.marshmallow_utils import custom_mapping, jsonify_schema


class CustomField(fields.Field):
"""A custom field class that extends the base Field class."""

pass


class CustomInheritedField(CustomField):
"""An inherited custom field class derived from CustomField."""

pass


class UnrecognizedField(fields.Field):
"""A custom field class that is not recognized in the custom mapping."""

pass


class TestSchema(Schema):
"""Schema class for testing, with various field types."""

string_field = fields.Str()
integer_field = fields.Integer()
custom_field = CustomField()
inherited_field = CustomInheritedField()


@pytest.fixture
def update_custom_mapping():
"""
Pytest fixture to temporarily update the custom mapping for field types.
Restores the original mapping after the test.
"""
original_mapping = custom_mapping.copy()
custom_mapping[CustomField] = "custom"
custom_mapping[CustomInheritedField] = "custom"
yield
custom_mapping.clear()
custom_mapping.update(original_mapping)


def test_jsonify_schema_with_standard_fields(update_custom_mapping):
"""Assert standard field types are correctly identified."""
schema = TestSchema()
result = jsonify_schema(schema)
assert result["string_field"]["type"] == "string"
assert result["integer_field"]["type"] == "integer"


def test_jsonify_schema_with_custom_field(update_custom_mapping):
"""Assert custom_field is identified as 'custom'."""
schema = TestSchema()
result = jsonify_schema(schema)
assert result["custom_field"]["type"] == "custom"


def test_jsonify_schema_with_inherited_field(update_custom_mapping):
"""
Assert inherited_field is correctly identified as 'custom'.
"""
schema = TestSchema()
result = jsonify_schema(schema)
assert result["inherited_field"]["type"] == "custom"


def test_jsonify_schema_with_unrecognized_field(update_custom_mapping):
"""
Assert jsonify_schema raises an exception for an unrecognized field in the schema.
"""

class UnrecognizedSchema(TestSchema):
unrecognized_field = UnrecognizedField()

schema = UnrecognizedSchema()
with pytest.raises(Exception) as excinfo:
jsonify_schema(schema)
assert "Unrecognised schema field" in str(excinfo.value)
Loading