Added Choices().subset().

This commit is contained in:
asday 2019-08-19 22:29:19 +01:00
parent d3d0881de0
commit 383740e8ab
2 changed files with 41 additions and 0 deletions

View file

@ -142,3 +142,17 @@ class Choices(object):
def __deepcopy__(self, memo):
return self.__class__(*copy.deepcopy(self._triples, memo))
def subset(self, *new_identifiers):
identifiers = set(self._identifier_map.keys())
if not identifiers.issuperset(new_identifiers):
raise ValueError(
'The following identifiers are not present: %s' %
identifiers.symmetric_difference(new_identifiers),
)
return self.__class__(*[
choice for choice in self._triples
if choice[1] in new_identifiers
])

View file

@ -279,3 +279,30 @@ class IdentifierChoicesTests(ChoicesTests):
('group b', [(3, 'three')]),
],
)
class SubsetChoicesTest(TestCase):
def setUp(self):
self.choices = Choices(
(0, 'a', 'A'),
(1, 'b', 'B'),
)
def test_nonexistent_identifiers_raise(self):
with self.assertRaises(ValueError):
self.choices.subset('a', 'c')
def test_solo_nonexistent_identifiers_raise(self):
with self.assertRaises(ValueError):
self.choices.subset('c')
def test_empty_subset_passes(self):
subset = self.choices.subset()
self.assertEqual(subset, Choices())
def test_subset_returns_correct_subset(self):
subset = self.choices.subset('a')
self.assertEqual(subset, Choices((0, 'a', 'A')))