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

Peter Otten __peter__ at web.de
Fri Aug 9 02:31:43 EDT 2013


adam.preble at gmail.com wrote:

> On Thursday, August 8, 2013 3:50:47 AM UTC-5, Peter Otten wrote:
>> Peter Otten wrote:
>> Oops, that's an odd class name. Fixing the name clash in Types.__new__()
>> is
>> 
>> left as an exercise...
> 
> Interesting, I got __main__.T, even though I pretty much just tried your
> code wholesale.  

I see I have to fix it myself then...

> For what it's worth, I'm using Python 2.7.  I'm glad to
> see that code since I learned a lot of tricks from it.

[My buggy code]

> class Type(type):
>     def __new__(class_, name, bases, classdict):

Here 'name' is the class name

>         newclassdict = {}
>         for name, attr in classdict.items():
>             if getattr(attr, "test", False):
>                 assert not name.startswith(PREFIX)
>                 name = PREFIX + name
>             assert name not in newclassdict
>             newclassdict[name] = attr

Here 'name' is the the last key of classdict which is passed to type.__new__ 
instead of the actual class name.

>         return type.__new__(class_, name, bases, newclassdict)

[Fixed version]

class Type(type):
    def __new__(class_, classname, bases, classdict):
        newclassdict = {}
        for name, attr in classdict.items():
            if getattr(attr, "test", False):
                assert not name.startswith(PREFIX)
                name = PREFIX + name
            assert name not in newclassdict
            newclassdict[name] = attr
        return type.__new__(class_, classname, bases, newclassdict)





More information about the Python-list mailing list