Merge branch 'tag-handler-has' of https://github.com/ChrisLR/evennia into ChrisLR-tag-handler-has

This commit is contained in:
Griatch 2020-10-08 18:40:57 +02:00
commit da6628120c
2 changed files with 57 additions and 0 deletions

View file

@ -319,6 +319,37 @@ class TagHandler(object):
getattr(self.obj, self._m2m_fieldname).add(tagobj)
self._setcache(tagstr, category, tagobj)
def has(self, tag=None, category=None, return_list=False):
"""
Checks if the given Tag (or list of Tags) exists on the object.
Args:
tag (str or iterable): The Tag key or tags to check for.
If `None`, search by category.
category (str or None): Limit the check to Tags with this
category (note, that `None` is the default category).
Returns:
has_tag (bool or list): If the Tag exists on this object or not.
If `tag` was given as an iterable then the return is a list of booleans.
"""
ret = []
category = category.strip().lower() if category is not None else None
if tag:
for tag_str in make_iter(tag):
tag_str = tag_str.strip().lower()
ret.extend(bool(tag) for tag in self._getcache(tag_str, category))
elif category:
ret.extend(bool(tag) for tag in self._getcache(category=category))
else:
raise ValueError("Either tag or category must be provided.")
if return_list:
return ret
return ret[0] if len(ret) == 1 else ret
def get(self, key=None, default=None, category=None, return_tagobj=False, return_list=False):
"""
Get the tag for the given key, category or combination of the two.

View file

@ -145,3 +145,29 @@ class TestTypedObjectManager(EvenniaTest):
self.assertEqual(tagobj.db_key, "tag4")
self.assertEqual(tagobj.db_category, "category4")
self.assertEqual(tagobj.db_data, "data4")
class TestTags(EvenniaTest):
def test_has_tag_key_only(self):
self.obj1.tags.add("tagC")
self.assertTrue(self.obj1.tags.has("tagC"))
def test_has_tag_key_with_category(self):
self.obj1.tags.add("tagC", "categoryC")
self.assertTrue(self.obj1.tags.has("tagC", "categoryC"))
def test_does_not_have_tag_key_only(self):
self.obj1.tags.add("tagC")
self.assertFalse(self.obj1.tags.has("tagD"))
def test_does_not_have_tag_key_with_category(self):
self.obj1.tags.add("tagC", "categoryC")
self.assertFalse(self.obj1.tags.has("tagD", "categoryD"))
def test_has_tag_category_only(self):
self.obj1.tags.add("tagC", "categoryC")
self.assertTrue(self.obj1.tags.has(category="categoryC"))
def test_does_not_have_tag_category_only(self):
self.obj1.tags.add("tagC", "categoryC")
self.assertFalse(self.obj1.tags.has(category="categoryD"))