From 7983f882e96211ac27a723a28ab95280cae160a2 Mon Sep 17 00:00:00 2001 From: Jon Lund Steffensen Date: Wed, 1 Jun 2022 13:43:33 -0700 Subject: [PATCH] Try to fix dumping with data_key --- flask_rebar/validation.py | 7 +++++-- tests/test_validation.py | 10 ++++++++++ 2 files changed, 15 insertions(+), 2 deletions(-) diff --git a/flask_rebar/validation.py b/flask_rebar/validation.py index 97b4b3b..3c5d5a8 100644 --- a/flask_rebar/validation.py +++ b/flask_rebar/validation.py @@ -35,13 +35,16 @@ def filter_dump_only(schema, data): """ # Note as of marshmallow 3.13.0, Schema.dump_only is NOT populated if fields are declared as dump_only inline, # so we'll calculate "dump_only" ourselves. ref: https://github.com/marshmallow-code/marshmallow/issues/1857 + output_to_input_keys = { + field.data_key: key for key, field in schema.fields.items() if field.data_key + } dump_only_fields = schema.dump_fields.keys() - schema.load_fields.keys() if isinstance(data, Mapping): dump_only = dict() non_dump_only = dict() # get our dump_only fields directly, and candidates for loadable: for k, v in data.items(): - if k in dump_only_fields: + if output_to_input_keys.get(k, k) in dump_only_fields: dump_only[k] = v else: non_dump_only[k] = v @@ -49,7 +52,7 @@ def filter_dump_only(schema, data): # construct loadable (a subset of non_dump_only, with recursive filter of nested dump_only fields) loadable = dict() for k, v in non_dump_only.items(): - field = schema.fields[k] + field = schema.fields[output_to_input_keys.get(k, k)] # see if we have a nested schema (using either Nested(many=True) or List(Nested()) field_schema = None if isinstance(field, fields.Nested): diff --git a/tests/test_validation.py b/tests/test_validation.py index 0be6944..a624890 100644 --- a/tests/test_validation.py +++ b/tests/test_validation.py @@ -331,3 +331,13 @@ def test_deserialize_errors(self): self.assertEqual( ctx.exception.messages, {"foos": {1: ["Not a valid integer."]}} ) + + +class DataKeySchema(RequireOnDumpMixin, Schema): + test_field = fields.String(data_key="testField") + + +class TestDataKey(TestCase): + def test_dump_and_validate_with_data_key(self): + result = compat.dump(DataKeySchema(), {"test_field": "abc"}) + self.assertEqual(result, {"testField": "abc"})