schema icon indicating copy to clipboard operation
schema copied to clipboard

Reference to location within data in SchemaError

Open demux opened this issue 10 years ago • 5 comments

I would like SchemaError to tell me where in the data structure the error occurred.

Something like:

# Schema:
Schema({
    'key1': {
        'child1': {
            'child2': [
                {'pedo': bool}
            ]
        }
    },
    Optional('key2'): {
        'foo': str
    }
})

# Data:
{
    'key1': {
        'child1': {
            'child2': [
                {'pedo': 1},
                {'pedo': false},
            ]
        }
    }
}

# Error message:
{
    'key1': {
        'child1': {
            'child2': {
                0: {'pedo': 'this value should be an instance of bool not int'}
            }
        }
    }
}

# Or as a list:
['key1', 'child1', 'child2', 0, 'pedo']

This way I would be able to find the location of the error in my parsed YAML file. It's also just a lot more helpful error message. Something like 1 should be bool tells me almost nothing.

demux avatar Oct 09 '15 18:10 demux

I agree. The current message is quite useless. Having a simple list with the path to the error would be super helpful.

danielmaxx avatar Nov 18 '15 13:11 danielmaxx

Would be really helpful.

vlcinsky avatar Dec 11 '15 12:12 vlcinsky

+1

timtan avatar Mar 25 '16 08:03 timtan

Totally agree, I'm going to take a shot at a PR.

Edit: taking a quick look, I think this can be added pretty readily by doing try/except around the recursive calls and amending raised exceptions with additional information. If the validation is successful, this is basically free; if the validation fails the call stack unwinding builds up the path information.

kurtbrose avatar Jan 13 '17 19:01 kurtbrose

looks like this may be handled recently by this: https://github.com/keleshev/schema/commit/61cc0bf84dd3efc830a366fb200c386bae35c243

Here's the behavior on your example:

>>> # Schema:
... Schema({
...     'key1': {
...         'child1': {
...             'child2': [
...                 {'pedo': bool}
...             ]
...         }
...     },
...     Optional('key2'): {
...         'foo': str
...     }
... }).validate(
... # Data:
... {
...     'key1': {
...         'child1': {
...             'child2': [
...                 {'pedo': 1},
...                 {'pedo': False},
...             ]
...         }
...     }
... })
Traceback (most recent call last):
  File "<stdin>", line 20, in <module>
  File "/Users/kurtrose/schema/schema.py", line 244, in validate
    raise SchemaError([k] + x.autos, [e] + x.errors)
schema.SchemaError: Key 'key1' error:
Key 'child1' error:
Key 'child2' error:
Or({'pedo': <type 'bool'>}) did not validate {'pedo': 1}
Key 'pedo' error:
1 should be instance of 'bool'

kurtbrose avatar Jan 13 '17 21:01 kurtbrose