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

re.error not wrapped in ValidationError when invalid regex is provided for Pattern field #579

Closed
mrburrito opened this issue Aug 22, 2023 · 1 comment · Fixed by #597
Closed

Comments

@mrburrito
Copy link

I have a data model that accepts a user-provided regular expression with the model defined as:

@dataclass
class Regex:
    pattern: Pattern = field(metadata=schema(min_len=1))
    group: int = field(default=0, metadata=schema(min=0))

I have several validation tests to confirm expected behavior and, when I try to verify that a pattern of "(unclosed" results in a ValidationError, my tests fail because the re.error thrown by re.compile() is being raised instead.

I tried defining a custom deserializer for Pattern, but it isn't getting executed

@deserializer
def to_pattern(pattern: str) -> Pattern:
    try:
        return re.compile(pattern)
    except re.error as err:
        raise ValidationError(f"invalid regex pattern '{pattern}': {err}")

Not sure if I'm doing something wrong with the configuration or if the default deserializer for re.Pattern needs to be updated.

@mrburrito
Copy link
Author

This works as a workaround, but was hoping to have the more semantically correct typing.

@dataclass
class Regex:
    pattern: str = field(metadata=schema(min_len=1))
    group: int = field(default=0, metadata=schema(min=0))

    @validator
    def check_regex_pattern(self):
        try:
            re.compile(self.pattern)
        except re.error as err:
            raise ValidationError(f"invalid regex pattern '{self.pattern}': {err}")

wyfo added a commit that referenced this issue Oct 18, 2023
@wyfo wyfo closed this as completed in #597 Oct 18, 2023
wyfo added a commit that referenced this issue Oct 18, 2023
…r instead (#597)

* fix: catch re.error in re.Pattern compilation to raise ValidationError instead

Fixes #579

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

Successfully merging a pull request may close this issue.

1 participant