From 10a78d033c3c56448c8af4e7f70a237a5826e65f Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Anders=20M=C3=A5nsson?= Date: Mon, 12 Oct 2020 23:12:48 +0200 Subject: [PATCH] Remove value enumeration when validating empty list (#397) The behaviour seems to have been introduced in commit 95489bd443e9a654 that modified the schema of an empty list in order to provide a consistent behaviour between Schema({}) and Schema([]). The commit introduced an enumeration of the incorrect values rather than the expected behaviour of showing the key with the incorrect value. This commit provides the expected behaviour, and is also consistent with the 'pathless' behaviour currently implemented, meaning that - Schema([])([1]) -> 'not a valid value @ data[1]' - Schema({'key': []})({'key': [1]) -> 'not a valid dictionary value @ data['key']. Finally, as new unit test is provided to ensure that the new behaviour remains intact. --- voluptuous/schema_builder.py | 4 ++-- voluptuous/tests/tests.py | 14 ++++++++++++++ 2 files changed, 16 insertions(+), 2 deletions(-) diff --git a/voluptuous/schema_builder.py b/voluptuous/schema_builder.py index 64da5b2..df19c8d 100644 --- a/voluptuous/schema_builder.py +++ b/voluptuous/schema_builder.py @@ -615,11 +615,11 @@ def validate_sequence(path, data): if not isinstance(data, seq_type): raise er.SequenceTypeInvalid('expected a %s' % seq_type_name, path) - # Empty seq schema, allow any data. + # Empty seq schema, reject any data. if not schema: if data: raise er.MultipleInvalid([ - er.ValueInvalid('not a valid value', [value]) for value in data + er.ValueInvalid('not a valid value', path if path else data) ]) return data diff --git a/voluptuous/tests/tests.py b/voluptuous/tests/tests.py index 01ed91b..b78c222 100644 --- a/voluptuous/tests/tests.py +++ b/voluptuous/tests/tests.py @@ -1528,3 +1528,17 @@ def test_any_with_discriminant(): assert_equal(str(e), 'expected bool for dictionary value @ data[\'implementation\'][\'c-value\']') else: assert False, "Did not raise correct Invalid" + + +def test_empty_list_raises_error_of_key_not_values(): + """ https://github.com/alecthomas/voluptuous/issues/397 """ + schema = Schema({ + Required('variables', default=[]): [] + }) + + try: + schema({'variables': ['x']}) + except MultipleInvalid as e: + assert_equal(str(e), "not a valid value for dictionary value @ data['variables']") + else: + assert False, "Did not raise correct Invalid"