Ben Finney wrote:
Ethan Furman
writes: Ben Finney wrote:
How can composition add test cases detectable by Python's ‘unittest’?
Metaclasses, if's that an option... […] or a class decorator […]
Both interesting, thank you. But Python 3 isn't an option for several projects where I'd like to use this.
Well, I'm sure there's a way to do it -- alas, I lack the time to find it either in the docs, archives, or by experimentation. What I did find is that if you have your functions in modules, instead of in classes, it works fine in Python 2.6+. 8<---spam.py------------------------------------------------------- def test_spam_01(self): print('testing spam_01') def test_spam_02(self): print('testing spam_02') 8<----------------------------------------------------------------- 8<---eggs.py------------------------------------------------------- def test_eggs_01(self): print('testing eggs_01') def test_eggs_02(self): print('testing eggs_02') 8<----------------------------------------------------------------- 8<---test_compose.py----------------------------------------------- import unittest class Compose(object): # 2.6-2.7, functions must be in modules def __init__(self, *parts): self.parts = parts def __call__(self, func): for part in self.parts: for attr in dir(part): if attr[:2] == attr[-2:] == '__': continue if getattr(cls, attr, None): raise AttributeError( "%s already exists in %s" % (attr, cls)) setattr(func, attr, getattr(part, attr)) return func @Compose(spam, eggs) class TestAll(unittest.TestCase): def setUp(self): print('Setting up...') def tearDown(self): print('Tearing down...') def test_something(self): print('testing something') if __name__ == '__main__': unittest.main() 8<---test_compose.py----------------------------------------------- Compose now has rudimentary error checking, and if can live with your extras living in their own .py files, this might work for you. ~Ethan~