Is it possible to make a unittest decorator to rename a method from "x" to "testx?"

adam.preble at gmail.com adam.preble at gmail.com
Thu Aug 8 02:32:44 EDT 2013


We were coming into Python's unittest module from backgrounds in nunit, where they use a decorate to identify tests. So I was hoping to avoid the convention of prepending "test" to the TestClass methods that are to be actually run. I'm sure this comes up all the time, but I mean not to have to do:
class Test(unittest.TestCase):
 def testBlablabla(self):
 self.assertEqual(True, True)
But instead:
class Test(unittest.TestCase):
 @test
 def Blablabla(self):
 self.assertEqual(True, True)
This is admittedly a petty thing. I have just about given up trying to actually deploy a decorator, but I haven't necessarily given up on trying to do it for the sake of knowing if it's possible.
Superficially, you'd think changing a function's __name__ should do the trick, but it looks like test discovery happens without looking at the transformed function. I tried a decorator like this:
def prepend_test(func):
 print "running prepend_test"
 func.__name__ = "test" + func.__name__
 
 def decorator(*args, **kwargs):
 return func(args, kwargs)
 
 return decorator
When running unit tests, I'll see "running prepend_test" show up, but a dir on the class being tested doesn't show a renamed function. I assume it only works with instances. Are there any other tricks I could consider?


More information about the Python-list mailing list

AltStyle によって変換されたページ (->オリジナル) /