diff --git a/ckan/lib/navl/dictization_functions.py b/ckan/lib/navl/dictization_functions.py index f21eaf89764..bae614adfb7 100644 --- a/ckan/lib/navl/dictization_functions.py +++ b/ckan/lib/navl/dictization_functions.py @@ -230,8 +230,12 @@ def validate(data, schema, context=None): # empty fields and missing fields when doing partial updates. empty_lists = [key for key, value in data.items() if value == []] + # create a copy of the context which also includes the schema keys so + # they can be used by the validators + validators_context = dict(context, schema_keys=schema.keys()) + flattened = flatten_dict(data) - converted_data, errors = _validate(flattened, schema, context) + converted_data, errors = _validate(flattened, schema, validators_context) converted_data = unflatten(converted_data) # check config for partial update fix option diff --git a/ckan/new_tests/lib/navl/test_dictization_functions.py b/ckan/new_tests/lib/navl/test_dictization_functions.py new file mode 100644 index 00000000000..226d6b3ef38 --- /dev/null +++ b/ckan/new_tests/lib/navl/test_dictization_functions.py @@ -0,0 +1,49 @@ +import nose +from ckan.lib.navl.dictization_functions import validate + + +eq_ = nose.tools.eq_ + + +class TestValidate(object): + + def test_validate_passes_a_copy_of_the_context_to_validators(self): + + # We need to pass some keys on the context, otherwise validate + # will do context = context || {}, which creates a new one, defeating + # the purpose of this test + context = {'foo': 'bar'} + + def my_validator(key, data, errors, context_in_validator): + + assert not id(context) == id(context_in_validator) + + data_dict = { + 'my_field': 'test', + } + + schema = { + 'my_field': [my_validator], + } + + data, errors = validate(data_dict, schema, context) + + def test_validate_adds_schema_keys_to_context(self): + + def my_validator(key, data, errors, context): + + assert 'schema_keys' in context + + eq_(context['schema_keys'], ['my_field']) + + data_dict = { + 'my_field': 'test', + } + + schema = { + 'my_field': [my_validator], + } + + context = {} + + data, errors = validate(data_dict, schema, context)