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

Whitebox testing an error raising custom validation rule is not supported #617

Open
weshouman opened this issue Apr 17, 2024 · 0 comments
Open

Comments

@weshouman
Copy link

Brief

Adding errors in a custom validator rule prevents direct trigger of this rule

Current Behaviour

Creating a validation rule like

    def _validate_is_duration(self, is_duration, field, value):
        """ 
        Test if a field's value is a valid duration format 
        The rule's arguments are validated against this schema:
            {'type': 'boolean'}
        """
        if is_duration:
            duration_pattern = r'^(\d+-\d+ weeks|\d+ weeks|\d+-\d+ months|\d+ months|\d+-\d+ years|\d+ years)$'
            if not re.match(duration_pattern, value):
                self._error(field, f"Duration '{value}' is invalid")

and trying to trigger it using

    def setUp(self):
        self.validator = MyValidator({
            'duration': {'type': 'string', 'is_duration': True}
        })

    def test_duration_invalid(self):
        self.validator._validate_is_duration(True, 'duration', '6 decades')
        ...

Would give the error

  File "/path/to/project/venv/lib/python3.11/site-packages/cerberus/validator.py", line 280, in _error
    self._error(args[0], errors.CUSTOM, args[1])
  File "/path/to/project/venv/lib/python3.11/site-packages/cerberus/validator.py", line 308, in _error
    value = self.document.get(field)
            ^^^^^^^^^^^^^^^^^
AttributeError: 'NoneType' object has no attribute 'get'

Expected Behaviour

Either:

  • Validation occurs and error is captured instead of accessing get on None
  • A not-initialized validator exception be raised

Workarounds

The following workarounds would work

Content Initialization

Initializing the validator.document to a dictionary would suppress the exception (with a wrong value set)

    def test_duration_invalid(self):
        self.validator.document = {}
        self.validator._validate_is_duration(True, 'duration', '6 decades')
        print(self.validator.recent_error)

Validating Whole Content

In more complete scenarios that may unnecessarily test other aspects''

    def test_duration_invalid(self):
        self.validator.validate({"duration": "6 decades"})
        print(self.validator.errors)
        print(self.validator.recent_error)
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

No branches or pull requests

1 participant