raise exception when item not in list

This commit is contained in:
Andreas Preikschat 2014-04-26 11:01:12 +02:00
parent aa899bfde0
commit 6bdadff334
2 changed files with 10 additions and 13 deletions

View File

@ -69,17 +69,14 @@ class CategoryActionList(object):
""" """
Implement the __getitem__() method to make this class a dictionary type Implement the __getitem__() method to make this class a dictionary type
""" """
try: return self.actions[key][1]
return self.actions[key][1]
except:
raise KeyError('Action "%s" does not exist.' % key)
def __contains__(self, item): def __contains__(self, key):
""" """
Implement the __contains__() method to make this class a dictionary type Implement the __contains__() method to make this class a dictionary type
""" """
for weight, action in self.actions: for weight, action in self.actions:
if action == item: if action == key:
return True return True
return False return False
@ -106,12 +103,6 @@ class CategoryActionList(object):
self.index += 1 self.index += 1
return self.actions[self.index - 1][1] return self.actions[self.index - 1][1]
def has_key(self, key):
"""
Implement the has_key() method to make this class a dictionary type
"""
return key in self
def append(self, action): def append(self, action):
""" """
Append an action Append an action
@ -136,6 +127,7 @@ class CategoryActionList(object):
if action[1] == remove_action: if action[1] == remove_action:
self.actions.remove(action) self.actions.remove(action)
return return
raise ValueError('Action "%s" does not exist.' % remove_action)
class CategoryList(object): class CategoryList(object):

View File

@ -72,7 +72,7 @@ class TestCategoryActionList(TestCase):
self.assertEqual(self.action1, returned_action) self.assertEqual(self.action1, returned_action)
# THEN: Test if an exception is raised when trying to access a non existing item. # THEN: Test if an exception is raised when trying to access a non existing item.
self.assertRaises(KeyError, self.list.__getitem__, 1) self.assertRaises(IndexError, self.list.__getitem__, 1)
def contains_test(self): def contains_test(self):
""" """
@ -141,12 +141,17 @@ class TestCategoryActionList(TestCase):
Test the remove() method Test the remove() method
""" """
# GIVEN: The list # GIVEN: The list
self.list.append(self.action1)
# WHEN: Delete an item from the list. # WHEN: Delete an item from the list.
self.list.remove(self.action1) self.list.remove(self.action1)
# THEN: Now the element should not be in the list anymore. # THEN: Now the element should not be in the list anymore.
self.assertFalse(self.action1 in self.list) self.assertFalse(self.action1 in self.list)
# THEN: Check if an exception is raised when trying to remove a not present action.
self.assertRaises(ValueError, self.list.remove, self.action2)
class TestActionList(TestCase, TestMixin): class TestActionList(TestCase, TestMixin):
""" """