Adding methods from one class to another, dynamically
Oltmans
rolf.oltmans at gmail.com
Mon Feb 1 15:55:38 EST 2010
Thank you for your help, Chris. Looks like I can now attach methods to
class 'tee'. However, after attaching methods to 'tee' when I try to
run them using suite.run() I don't see any of the methods running, I'm
sorry but I've no clue what's failing this. Any insights will be
highly appreciated. Here is the sample code
filename: check.py
---
import inspect
import unittest
class result(unittest.TestResult):
def addSuccess(self,test):
print str(test) + ' succeeded'
def addError(self,test,err):
print 'An error occured while running the test ' + str(test) +
' and error is = ' + str(err)
def addFailure(self,test,err):
print str(test) + " failed with an error =" + str(err)
class test(unittest.TestCase):
def test_first(self):
print 'first test'
def test_second(self):
print 'second test'
def test_third(self):
print 'third test'
import new
class tee(unittest.TestCase):
pass
if __name__=="__main__":
r = result()
for name,func in inspect.getmembers(test,inspect.ismethod):
if name.find('test_')!= -1:
setattr(tee, name, new.instancemethod(func,None,tee))
suite = unittest.defaultTestLoader.loadTestsFromName('check.tee')
suite.run(r)
---
Then line suite.run(r) should have run the methods that we just
attached, but it's not. I must be missing something here. Please
enlighten me.
Thanks.
On Feb 2, 1:25 am, Chris Rebert <c... at rebertia.com> wrote:
> On Mon, Feb 1, 2010 at 12:06 PM, Oltmans <rolf.oltm... at gmail.com> wrote:
> > Hello Python gurus,
>
> > I'm quite new when it comes to Python so I will appreciate any help.
> > Here is what I'm trying to do. I've two classes like below
>
> > import new
> > import unittest
>
> > class test(unittest.TestCase):
> > def test_first(self):
> > print 'first test'
> > def test_second(self):
> > print 'second test'
> > def test_third(self):
> > print 'third test'
>
> > class tee(unittest.TestCase):
> > pass
>
> > and I want to attach all test methods of 'test'(i.e. test_first(),
> > test_second() and test_third()) class to 'tee' class. So I'm trying to
> > do something like
>
> > if __name__=="__main__":
> > for name,func in inspect.getmembers(test,inspect.ismethod):
> > if name.find('test_')!= -1:
> > tee.name = new.instancemethod(func,None,tee)
>
> This ends up repeatedly assigning to the attribute "name" of tee; if
> you check dir(tee), you'll see the string "name" as an entry. It does
> *not* assign to the attribute named by the string in the variable
> `name`.
> You want setattr():http://docs.python.org/library/functions.html#setattr
> Assuming the rest of your code chunk is correct:
>
> setattr(tee, name, new.instancemethod(func,None,tee))
>
> Cheers,
> Chris
> --http://blog.rebertia.com- Hide quoted text -
>
> - Show quoted text -
More information about the Python-list
mailing list