tags:

views:

93

answers:

2
import re
import sys
import inspect
import testcases

testClass = re.compile(r'.*Case$')
testMethod = re.compile(r'.*Test$')

for class_name, class_obj in inspect.getmembers(testcases, inspect.isclass):
    if testClass.match(class_name):
        for method_name, method_obj in inspect.getmembers(class_obj, inspect.ismethod):
            if testMethod.match(method_name):
                # RIGHT HERE I WOULD LIKE TO INVOKE method_name
+6  A: 

Right after your code:

for class_name, class_obj in inspect.getmembers(testcases, inspect.isclass):
    if testClass.match(class_name):
        for method_name, method_obj in inspect.getmembers(class_obj, inspect.ismethod):
            if testMethod.match(method_name):
                # RIGHT HERE I WOULD LIKE TO INVOKE method_name

you could do:

            methodobj = getattr(classobj, method_name)
            methodobj("appropriate arguments go here")

if, that is, you had any clue whatsoever about what the "appropriate arguments" are. The first argument is presumably going to be an instance of the class -- which instance? How do you retrieve or create it? And, what about all the other arguments? What are they and what values do you want to pass for them?

Getting the method object, ready to be called, is the least of your issues -- getattr, as you see, does that really well and most easily!-) -- but you need sensible answers to the other questions above regarding the arguments (especially the first one, the instance on which you want to call the method) before your question actually makes much sense at all!-)

Alex Martelli
Hello alex, methodobj = getattr(class_obj, method_name) methodobj(class_obj())did the trick thank you sir.
Mozey
A: 

Thank you very much alex for the quick response.

The first argument is presumably going to be an instance of the class -- which instance? How do you retrieve or create it?

Okay, so if i understood you correctly, the first arugment of the method call methodobj should be an instance of classobj? How about the following.

methodobj = getattr(classobj, method_name)
methodobj(classobj())

What about all the other arguments? What are they and what values do you want to pass for them?

Naaah, no other arguments, Those are test cases with set variables in the methods. I just wanna be able to add test cases without having to modify other code in order to run them.

Thanks again, i haven't tried it yet, but out of what i read about getattr, it seems like its what i'm looking for. With some playing around i can make it work.