Python - run all tests for __main__ - executeAllTests()

in «tip» by Michael Beard
Tags: , , , ,

This would be something useful for me when using PyCharm and pytest. I don't have (or don't know if it's possible) to have the IDE run all the tests in a file, so ... I want a way to tag all the functions to run in my executeAllTests() function that I have in all of the tests.

I found this: run all functions in class - though, for what I want, it's just all functions that would be tagged or decorated.

As Tadhg McDonald-Jensen said in an answer:

While I do not particularly recommend calling all the methods on an object since as soon as you add some that require an argument it will obviously fail, you could use a decorator to label the methods that represent a test case and then search for all the ones that have said label:

def tester_method(f):
    f._is_for_test = True #add an arbitrary attribute to the function, completely supported for exactly this reason.
    return f

def call_all_tester_methods(x):
    """finds all attributes with a ._is_for_test attribute of their 
own and calls all of them in no guaranteed order"""
    methods = {}
    for name in dir(x):
        attr = getattr(x,name)
        if getattr(attr,"_is_for_test",False):
            methods[name] = attr
    for name,method in methods.items():
        #print("calling: {}".format(name))
        method()

class Foo(object):
    def __init__(self,a,b):
        self.a = a
        self.b=b

    @tester_method
    def bar(self):
        print(self.a)

    @tester_method
    def foobar(self):
        print(self.b)

    def othermethod_not_for_test(self,arg):
        return self.a + arg #this is not included in the test case

obj = Foo('hi','bye')
call_all_tester_methods(obj)

This could certainly be adapted for what I would need. Just need to do it.