From f89369f9acff505aaf92ff0e8389f6544a325703 Mon Sep 17 00:00:00 2001 From: Keryn Knight Date: Fri, 2 Aug 2013 12:23:48 +0100 Subject: [PATCH 1/2] Implement __contains__ ('x' in Choices('x')) for Choices objects. In Choices, `_choice_dict` appears to be a definitive location of all internal/DB representations, so it seems the best target for finding out if the given item is part of the sequences. --- model_utils/choices.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/model_utils/choices.py b/model_utils/choices.py index b5177cd..570f1af 100644 --- a/model_utils/choices.py +++ b/model_utils/choices.py @@ -76,3 +76,7 @@ class Choices(object): def __repr__(self): return '%s(%s)' % (self.__class__.__name__, ', '.join(("%s" % repr(i) for i in self._full))) + + def __contains__(self, item): + if item in self._choice_dict.values(): + return True From 6f0cf2a96cf9cec7cf1a0441b7d7d74fe07bf4c2 Mon Sep 17 00:00:00 2001 From: Keryn Knight Date: Fri, 2 Aug 2013 12:24:44 +0100 Subject: [PATCH 2/2] first pass at tests for the __contains__ functionality just implemented. --- model_utils/tests/tests.py | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/model_utils/tests/tests.py b/model_utils/tests/tests.py index f1fe411..ab60a62 100644 --- a/model_utils/tests/tests.py +++ b/model_utils/tests/tests.py @@ -223,6 +223,12 @@ class ChoicesTests(TestCase): def test_wrong_length_tuple(self): self.assertRaises(ValueError, Choices, ('a',)) + def test_contains_value(self): + self.assertTrue('PUBLISHED' in self.STATUS) + self.assertTrue('DRAFT' in self.STATUS) + + def test_doesnt_contain_value(self): + self.assertFalse('UNPUBLISHED' in self.STATUS) class LabelChoicesTests(ChoicesTests): @@ -265,6 +271,19 @@ class LabelChoicesTests(ChoicesTests): ('DELETED', 'DELETED', 'DELETED'), ))) + def test_contains_value(self): + self.assertTrue('PUBLISHED' in self.STATUS) + self.assertTrue('DRAFT' in self.STATUS) + # This should be True, because both the display value + # and the internal representation are both DELETED. + self.assertTrue('DELETED' in self.STATUS) + + def test_doesnt_contain_value(self): + self.assertFalse('UNPUBLISHED' in self.STATUS) + + def test_doesnt_contain_display_value(self): + self.assertFalse('is draft' in self.STATUS) + class IdentifierChoicesTests(ChoicesTests): @@ -301,6 +320,19 @@ class IdentifierChoicesTests(ChoicesTests): (2, 'DELETED', 'is deleted'), ))) + def test_contains_value(self): + self.assertTrue(0 in self.STATUS) + self.assertTrue(1 in self.STATUS) + self.assertTrue(2 in self.STATUS) + + def test_doesnt_contain_value(self): + self.assertFalse(3 in self.STATUS) + + def test_doesnt_contain_display_value(self): + self.assertFalse('is draft' in self.STATUS) + + def test_doesnt_contain_python_attr(self): + self.assertFalse('PUBLISHED' in self.STATUS) class InheritanceManagerTests(TestCase): def setUp(self):