Search code examples
pythonclasspython-class

Python Classes Understand methods


I have simple task: we have class TestingClass and we wanna simply test his methods. And we have class TestHelper for testing purpose.

class TestingClass():
    def testing_method_1(self):
        return False
    def testing_method_2(self):
        return True

class TestHelper():
    def __init__(self, class_name):
      pass
    def add(self, func_name, func_result):
      pass
    def run(self):
      pass
    
helper = TestHelper(TestingClass)
helper.add(“testing_method_1”, False)
helper.add(“testing_method_2”, True)
result = helper.run()

my target implement methods for class TestHelper . I solved it for myself but I think its bad realization. I initialize empty dictionary and test class. Next I add every method and test method result to dictionary. In run method I compare results.

class TestHelper():
    def __init__(self, class_name):
        self.test_class = class_name()
        self.func_list = {}

    def add(self, func_name, func_result):
        temp = 'self.test_class.' + func_name
        self.func_list[temp] = func_result
        
    def run(self):
        for f in self.func_list.keys():
            if eval(f)() == self.func_list[f]:
                print('yes')
            else:
                print('no')

Can I resolve it in best way? Thanks!


Solution

  • Using eval for this purpose is overkill. You could instead use the getattr() function to retrieve the function and call it. Read more: Python Docs

    class TestHelper():
        def __init__(self, class_name):
            self.test_class = class_name()
            self.func_list = {}
    
        def add(self, func_name, func_result):
            # { <function>:<desired result> }
            self.func_list[func_name] = func_result
        
        def run(self):
            for func, desired_result in self.func_list.items():
                if getattr(self.test_class, func)() is desired_result:
                    print('yes')
                else:
                    print('no')
    

    This code produces results:

    ...
    >>> helper = TestHelper(TestingClass)
    >>> helper.add("testing_method_1", False)
    >>> helper.add("testing_method_2", True)
    >>> result = helper.run()
    yes
    yes
    

    Of course you should also test if the class even has an attribute with the given function name. You can use hasattr() for this.