alecthomas / voluptuous

CONTRIBUTIONS ONLY: Voluptuous, despite the name, is a Python data validation library.
https://pypi.org/project/voluptuous
BSD 3-Clause "New" or "Revised" License
1.81k stars 219 forks source link

Allow error reporting on keys #479

Closed KenKundert closed 1 year ago

KenKundert commented 1 year ago

I tweaked the error reporting code in voluptuous/schema_builder.py so that validation errors on keys are reported with a message based on the exception raised rather than treated as an extra key. With this change exceptions on keys are treated in the same was as exceptions on values.

Before the change, when an Invalid error is raised on a key, the specifics of the error raised are ignored and the problem was reported as an extra key. This results in several problems. First, the reported error can be misleading. Second, the error could go unreported if the extra parameter is passed as REMOVE_EXTRA or ALLOW_EXTRA to Schema.

One example where this was problematic is a case where I was expecting the keys to be dates, and any invalid dates, such as February 30, should be reported as invalid dates, but instead were reported as an extra key, which is confusing.

Here is a short program that illustrates the problem:

import arrow
from voluptuous import Schema, Invalid, MultipleInvalid

def as_date(arg):
    return arrow.get(arg, 'D MMMM YYYY')

data = {
    "29 February 2020": "...",
    "29 February 2021": "...",
    "29 February 2022": "...",
    "29 February 2023": "...",
}

validate = Schema({as_date: str})

try:
    validate(data)
except MultipleInvalid as e:
    for error in e.errors:
        print(error)
alecthomas commented 1 year ago

Thanks!