Inject fields by metaclass and add test

This commit is contained in:
ChrisLR 2024-05-13 17:16:07 -04:00
parent 3b84ec1b42
commit bda6bbe80b
2 changed files with 25 additions and 5 deletions

View file

@ -15,15 +15,14 @@ class BaseComponent(type):
This is the metaclass for components,
responsible for registering components to the listing.
"""
@classmethod
def __new__(cls, *args):
def __new__(cls, name, parents, attrs):
"""
Every class that uses this metaclass will be registered
as a component in the Component Listing using its name.
All of them require a unique name.
"""
new_type = super().__new__(*args)
attrs['_fields'] = {}
new_type = super().__new__(cls, name, parents, attrs)
if new_type.__base__ == object:
return new_type
@ -53,7 +52,7 @@ class Component(metaclass=BaseComponent):
name = ""
slot = None
_fields = {}
_fields: dict | None = None
def __init__(self, host=None):
assert self.name, "All Components must have a name"

View file

@ -85,6 +85,27 @@ class TestComponents(EvenniaTest):
self.assertTrue(self.char1.test_a)
self.assertTrue(self.char1.test_b)
def test_character_components_set_fields_properly(self):
test_a_fields = self.char1.test_a._fields
self.assertIn('my_int', test_a_fields)
self.assertIn('my_list', test_a_fields)
self.assertEqual(len(test_a_fields), 2)
test_b_fields = self.char1.test_b._fields
self.assertIn('my_int', test_b_fields)
self.assertIn('my_list', test_b_fields)
self.assertIn('default_tag', test_b_fields)
self.assertIn('single_tag', test_b_fields)
self.assertIn('multiple_tags', test_b_fields)
self.assertIn('default_single_tag', test_b_fields)
self.assertEqual(len(test_b_fields), 6)
test_ic_a_fields = self.char1.ic_a._fields
self.assertIn('my_int', test_ic_a_fields)
self.assertIn('my_list', test_ic_a_fields)
self.assertIn('my_other_int', test_ic_a_fields)
self.assertEqual(len(test_ic_a_fields), 3)
def test_inherited_typeclass_does_not_include_child_class_components(self):
char_with_c = create.create_object(
InheritedTCWithComponents, key="char_with_c", location=self.room1, home=self.room1