-
Notifications
You must be signed in to change notification settings - Fork 28
fix (schemas): move query validation to schema #105
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
Open
egabancho
wants to merge
1
commit into
inveniosoftware:master
Choose a base branch
from
egabancho:schemas
base: master
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -1,21 +1,87 @@ | ||
| # -*- coding: utf-8 -*- | ||
| # | ||
| # Copyright (C) 2024 CERN. | ||
| # Copyright (C) 2025 Ubiquity Press | ||
| # | ||
| # Invenio-Collections is free software; you can redistribute it and/or modify | ||
| # it under the terms of the MIT License; see LICENSE file for more details. | ||
| """Collections schema.""" | ||
|
|
||
| from marshmallow import Schema, fields | ||
| """Collections schemas.""" | ||
|
|
||
| import re | ||
|
|
||
| from invenio_i18n import lazy_gettext as _ | ||
| from luqum.exceptions import ParseError | ||
| from luqum.parser import parser as luqum_parser | ||
| from marshmallow import Schema, ValidationError, fields, validate | ||
| from marshmallow_utils.fields import SanitizedUnicode | ||
|
|
||
|
|
||
| def _not_blank(**kwargs): | ||
| """Returns a non-blank validation rule.""" | ||
| max_ = kwargs.get("max", "") | ||
| return validate.Length( | ||
| error=_( | ||
| "Field cannot be blank or longer than {max_} characters.".format(max_=max_) | ||
| ), | ||
| min=1, | ||
| **kwargs, | ||
| ) | ||
|
|
||
|
|
||
| class CollectionTreeSchema(Schema): | ||
| """Collection tree schema.""" | ||
|
|
||
| slug = SanitizedUnicode( | ||
| required=True, | ||
| validate=[ | ||
| _not_blank(max=255), | ||
| validate.Regexp( | ||
| r"^[-\w]+$", | ||
| flags=re.ASCII, | ||
| error=_( | ||
| "The identifier should contain only letters, numbers, or dashes." | ||
| ), | ||
| ), | ||
| ], | ||
| ) | ||
| title = SanitizedUnicode( | ||
| validate=[_not_blank(max=255)], | ||
| ) | ||
| order = fields.Int() | ||
| id = fields.Int(dump_only=True) | ||
| community_id = fields.Str(dump_only=True) | ||
|
|
||
|
|
||
| def validate_search_query(query): | ||
| """Validate a search query using luqum parser.""" | ||
| try: | ||
| luqum_parser.parse(query) | ||
| except ParseError as e: | ||
| raise ValidationError(str(e)) from e | ||
|
|
||
|
|
||
| class CollectionSchema(Schema): | ||
| """Collection schema.""" | ||
|
|
||
| slug = fields.Str() | ||
| title = fields.Str() | ||
| slug = SanitizedUnicode( | ||
| validate=[ | ||
| _not_blank(max=255), | ||
| validate.Regexp( | ||
| r"^[-\w]+$", | ||
| flags=re.ASCII, | ||
| error=_( | ||
| "The identifier should contain only letters, numbers, or dashes." | ||
| ), | ||
| ), | ||
| ], | ||
| ) | ||
| title = SanitizedUnicode( | ||
| validate=[_not_blank(max=255)], | ||
| ) | ||
|
|
||
| depth = fields.Int(dump_only=True) | ||
| order = fields.Int() | ||
| id = fields.Int(dump_only=True) | ||
| num_records = fields.Int() | ||
| search_query = fields.Str(load_only=True) | ||
| search_query = fields.Str(validate=[validate_search_query]) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,54 @@ | ||
| # -*- coding: utf-8 -*- | ||
| # | ||
| # Copyright (C) 2025 Ubiquity Press | ||
| # | ||
| # Invenio-RDM is free software; you can redistribute it and/or modify | ||
| # it under the terms of the MIT License; see LICENSE file for more details. | ||
| # | ||
| """Test suite for the collections schemas.""" | ||
|
|
||
| import pytest | ||
| from marshmallow import ValidationError | ||
|
|
||
| from invenio_collections.services.schema import CollectionSchema | ||
|
|
||
|
|
||
| def test_collection_schema_validation(): | ||
| """Test search query validation.""" | ||
| valid_input = { | ||
| "slug": "col", | ||
| "title": "Test collection", | ||
| "order": 0, | ||
| "search_query": "*:*", | ||
| } | ||
|
|
||
| schema = CollectionSchema() | ||
| collection = schema.load(valid_input) | ||
| assert valid_input == collection == schema.dump(collection) | ||
|
|
||
|
|
||
| def test_collection_schema_fail(): | ||
| """Test schema validation errors.""" | ||
| input = { | ||
| "slug": "col", | ||
| "title": "Test collection", | ||
| "order": 0, | ||
| "search_query": "*:*", | ||
| } | ||
| schema = CollectionSchema() | ||
| with pytest.raises(ValidationError) as exc_info: | ||
| input["search_query"] = "custom_fields.journal:journal.volume:'2025'" | ||
| schema.load(input) | ||
| assert exc_info.value.args[0] == { | ||
| "search_query": ["Illegal character ''2025'' at position 37"] | ||
| } | ||
|
|
||
| # Set back query | ||
| input["search_query"] = "*:*" | ||
|
|
||
| with pytest.raises(ValidationError) as exc_info: | ||
| input["slug"] = "not valid" | ||
| schema.load(input) | ||
| assert exc_info.value.args[0] == { | ||
| "slug": ["The identifier should contain only letters, numbers, or dashes."] | ||
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Some of these fields should be required, like
slug, but that would be a breaking change (more than adding these validations) and require a different schema for update operations (example).I am open to suggestions 😇