I just converted on of my classes to a "self registering" class. It was my first foray into python metaclasses. Oddly, many tests that had been passing started failing in odd ways. Many of those failing tests would pass when run by themselves and not as a part of the suite. This led me to believe that there was some sort of "data bleed" between tests. So I created some tests to find out if that is true, and I was right.
Now the question is, how do I resolve the issue. tearDown() methods with del() don't work. Adding a desctructor (del(self)) doesn't work. How do I unregister items from the _registry so that they don't cross-contaminate other tests?
Entertainingly, the first test below passed until I added the second.
class IterateRegister(type):
def __iter__(cls):
return iter(cls._registry)
class TEST_IterateRegister_instantiation(unittest.TestCase):
class foo(metaclass=IterateRegister):
_registry = []
def __init__(self, name):
self._registry.append(self)
self.name = name
def test__iterate_register_metaclass(self):
names = ['Shaggy', 'Scooby', 'Snack']
x1 = TEST_IterateRegister_instantiation.foo(names[0])
x2 = TEST_IterateRegister_instantiation.foo(names[1])
x3 = TEST_IterateRegister_instantiation.foo(names[2])
self.assertEqual(names, [ f.name for f in TEST_IterateRegister_instantiation.foo ])
def test__destruction_deletes_class_from_registry(self):
names = ['Shaggy', 'Scooby', 'Snack']
x1 = TEST_IterateRegister_instantiation.foo(names[0])
x2 = TEST_IterateRegister_instantiation.foo(names[1])
x3 = TEST_IterateRegister_instantiation.foo(names[2])
del(x2)
names.remove('Scooby')
self.assertEqual(names, [ f.name for f in TEST_IterateRegister_instantiation.foo ])