mercredi 4 mars 2020

Python3 iteratively call members of class with reflection

Using Python3, I am trying to call the members of a class which contain is_ or has_. Their returns are hard coded to True.

Here's what I've implemented, I don't know how to actually call the stored members using the black_magic method. Can anybody please help? Many thanks.

import inspect
import unittest
class Foo:
    def is_bar(self):
        print(bar)
        return True
    def is_baz(self):
        print(baz)
        return True

class MyTest(unittest.TestCase):
    def setUp(self):
        self.object=Foo()
        self.object_members=inspect.getmembers(self.object)
    def test_assertions_when_typical(self):
        self.assertEqual(True,True)
        for member in self.object_members:
            member_name, member_address = member        
            if "is_" in member_name or "has_" in member_name:
                result=black_magic(member)
                self.assertEqual(result,True)

if __name__=='__main__':
    unittest.main()

I'm invoking this with:

python3 -m unittest test_python_reflection_minimal_example.py




Aucun commentaire:

Enregistrer un commentaire