From 284f9faa07941a2c804909187211cc782e7c96c9 Mon Sep 17 00:00:00 2001 From: Steven Loria Date: Fri, 11 Sep 2015 23:01:18 -0400 Subject: [PATCH] Correctly handle [] and {} as invalid inputs to BooleanField --- rest_framework/fields.py | 11 +++++++---- tests/test_fields.py | 12 ++++++++++++ 2 files changed, 19 insertions(+), 4 deletions(-) diff --git a/rest_framework/fields.py b/rest_framework/fields.py index 159784ea3..7c48c621e 100644 --- a/rest_framework/fields.py +++ b/rest_framework/fields.py @@ -608,10 +608,13 @@ class BooleanField(Field): super(BooleanField, self).__init__(**kwargs) def to_internal_value(self, data): - if data in self.TRUE_VALUES: - return True - elif data in self.FALSE_VALUES: - return False + try: + if data in self.TRUE_VALUES: + return True + elif data in self.FALSE_VALUES: + return False + except TypeError: # Input is an unhashable type + pass self.fail('invalid', input=data) def to_representation(self, value): diff --git a/tests/test_fields.py b/tests/test_fields.py index c1d3e3a49..6048f49d0 100644 --- a/tests/test_fields.py +++ b/tests/test_fields.py @@ -466,6 +466,18 @@ class TestBooleanField(FieldValues): } field = serializers.BooleanField() + def test_disallow_unhashable_collection_types(self): + inputs = ( + [], + {}, + ) + field = serializers.BooleanField() + for input_value in inputs: + with pytest.raises(serializers.ValidationError) as exc_info: + field.run_validation(input_value) + expected = ['"{0}" is not a valid boolean.'.format(input_value)] + assert exc_info.value.detail == expected + class TestNullBooleanField(FieldValues): """