Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.lang.python > #52176

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

Path csiph.com!usenet.pasdenom.info!weretis.net!feeder1.news.weretis.net!feeder.erje.net!eu.feeder.erje.net!xlned.com!feeder1.xlned.com!newsfeed.xs4all.nl!newsfeed4.news.xs4all.nl!xs4all!newsgate.cistron.nl!newsgate.news.xs4all.nl!post.news.xs4all.nl!not-for-mail
Return-Path <python-python-list@m.gmane.org>
X-Original-To python-list@python.org
Delivered-To python-list@mail.python.org
X-Spam-Status OK 0.000
X-Spam-Evidence '*H*': 1.00; '*S*': 0.00; 'assignment': 0.07; 'modify': 0.07; 'python3': 0.07; 'skip:u 30': 0.07; 'tests.': 0.07; '"__main__":': 0.09; '__name__': 0.09; 'decorator': 0.09; 'deploy': 0.09; 'instances.': 0.09; 'prefix': 0.09; 'received:80.91': 0.09; 'received:80.91.229': 0.09; 'received:gmane.org': 0.09; 'received:list': 0.09; 'sake': 0.09; 'skip:t 60': 0.09; 'subject:method': 0.09; 'tests,': 0.09; 'true)': 0.09; 'unittest': 0.09; 'def': 0.12; 'assume': 0.14; '"running': 0.16; '"test"': 0.16; '**kwargs):': 0.16; 'attr': 0.16; 'backgrounds': 0.16; 'bases,': 0.16; 'binding.': 0.16; 'consider?': 0.16; 'false):': 0.16; "function's": 0.16; 'instead:': 0.16; 'metaclass': 0.16; 'received:80.91.229.3': 0.16; 'received:dip0.t-ipconnect.de': 0.16; 'received:plane.gmane.org': 0.16; 'received:t-ipconnect.de': 0.16; 'renamed': 0.16; 'subject:make': 0.16; 'subject:possible': 0.16; 'sugar': 0.16; 'syntactic': 0.16; 'wrote:': 0.18; 'module': 0.19; 'trying': 0.19; "python's": 0.19; 'import': 0.22; 'tests': 0.22; 'print': 0.22; 'header:User-Agent:1': 0.23; 'replace': 0.24; "haven't": 0.24; 'looks': 0.24; 'this:': 0.26; 'pass': 0.26; 'header:X-Complaints- To:1': 0.27; 'tried': 0.27; 'function': 0.29; 'skip:p 30': 0.29; "doesn't": 0.30; "i'm": 0.30; 'assert': 0.31; 'discovery': 0.31; 'class': 0.32; 'skip:m 30': 0.32; 'running': 0.33; 'skip:_ 10': 0.34; 'skip:d 20': 0.34; 'subject:from': 0.34; 'could': 0.34; 'possible.': 0.35; 'test': 0.35; 'but': 0.35; 'there': 0.35; 'object,': 0.36; 'method': 0.36; "i'll": 0.36; 'should': 0.36; 'changing': 0.37; 'unit': 0.37; 'starting': 0.37; 'being': 0.38; 'convention': 0.38; 'to:addr:python-list': 0.38; 'subject:" ': 0.39; 'sure': 0.39; 'to:addr:python.org': 0.39; 'received:org': 0.40; 'skip:u 10': 0.60; 'up,': 0.60; 'identify': 0.61; 'email addr:gmail.com': 0.63; 'show': 0.63; 'name': 0.63; 'skip:n 10': 0.64; 'therefore': 0.72; 'influence': 0.74; 'hoping': 0.75; 'decorate': 0.84; 'loader.': 0.84; 'trick,': 0.84; 'do:': 0.91
X-Injected-Via-Gmane http://gmane.org/
To python-list@python.org
From Peter Otten <__peter__@web.de>
Subject Re: Is it possible to make a unittest decorator to rename a method from "x" to "testx?"
Date Thu, 08 Aug 2013 10:32:57 +0200
Organization None
References <215331fa-379f-4251-b722-44555349fbb5@googlegroups.com>
Mime-Version 1.0
Content-Type text/plain; charset="ISO-8859-1"
Content-Transfer-Encoding 7Bit
X-Gmane-NNTP-Posting-Host p50848d18.dip0.t-ipconnect.de
User-Agent KNode/4.7.3
X-BeenThere python-list@python.org
X-Mailman-Version 2.1.15
Precedence list
List-Id General discussion list for the Python programming language <python-list.python.org>
List-Unsubscribe <http://mail.python.org/mailman/options/python-list>, <mailto:python-list-request@python.org?subject=unsubscribe>
List-Archive <http://mail.python.org/pipermail/python-list/>
List-Post <mailto:python-list@python.org>
List-Help <mailto:python-list-request@python.org?subject=help>
List-Subscribe <http://mail.python.org/mailman/listinfo/python-list>, <mailto:python-list-request@python.org?subject=subscribe>
Newsgroups comp.lang.python
Message-ID <mailman.342.1375950785.1251.python-list@python.org> (permalink)
Lines 141
NNTP-Posting-Host 2001:888:2000:d::a6
X-Trace 1375950785 news.xs4all.nl 15912 [2001:888:2000:d::a6]:50576
X-Complaints-To abuse@xs4all.nl
Xref csiph.com comp.lang.python:52176

Show key headers only | View raw


adam.preble@gmail.com wrote:

> 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?

I think you are misunderstanding what a decorator does. You can think of

def f(...): ...

as syntactic sugar for an assignment

f = make_function(...)

A decorator intercepts that

f = decorator(make_function(...))

and therefore can modify or replace the function object, but has no 
influence on the name binding.

For unittest to allow methods bound to a name not starting with "test" you 
have to write a custom test loader.

import functools
import unittest.loader
import unittest

def test(method):
    method.unittest_method = True
    return method

class MyLoader(unittest.TestLoader):
   
    def getTestCaseNames(self, testCaseClass):
        def isTestMethod(attrname, testCaseClass=testCaseClass,
                         prefix=self.testMethodPrefix):
            attr = getattr(testCaseClass, attrname)
            if getattr(attr, "unittest_method", False):
                return True
            return attrname.startswith(prefix) and callable(attr)

        testFnNames = list(filter(isTestMethod, dir(testCaseClass)))
        if self.sortTestMethodsUsing:
            testFnNames.sort(key=functools.cmp_to_key(self.sortTestMethodsUsing))
        return testFnNames

class A(unittest.TestCase):
    def test_one(self):
        pass
    @test
    def two(self):
        pass

if __name__ == "__main__":
    unittest.main(testLoader=MyLoader())

Alternatively you can write a metaclass that *can* intercept the name 
binding process:

$ cat mytestcase.py 
import unittest

__UNITTEST = True

PREFIX = "test_"

class Type(type):
    def __new__(class_, name, 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_, name, bases, newclassdict)

class MyTestCase(unittest.TestCase, metaclass=Type):
    pass

def test(method):
    method.test = True
    return method
$ cat mytestcase_demo.py
import unittest
from mytestcase import MyTestCase, test

class T(MyTestCase):
    def test_one(self):
        pass
    @test
    def two(self):
        pass

if __name__ == "__main__":
    unittest.main()
$ python3 mytestcase_demo.py -v
test_one (__main__.test_two) ... ok
test_two (__main__.test_two) ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.000s

OK

Back to comp.lang.python | Previous | NextPrevious in thread | Next in thread | Find similar | Unroll thread


Thread

Is it possible to make a unittest decorator to rename a method from "x" to "testx?" adam.preble@gmail.com - 2013-08-07 23:32 -0700
  Re: Is it possible to make a unittest decorator to rename a method from "x" to "testx?" Terry Reedy <tjreedy@udel.edu> - 2013-08-08 04:04 -0400
    Re: Is it possible to make a unittest decorator to rename a method from "x" to "testx?" adam.preble@gmail.com - 2013-08-08 09:20 -0700
      Re: Is it possible to make a unittest decorator to rename a method from "x" to "testx?" Terry Reedy <tjreedy@udel.edu> - 2013-08-08 15:28 -0400
  Re: Is it possible to make a unittest decorator to rename a method from "x" to "testx?" Peter Otten <__peter__@web.de> - 2013-08-08 10:32 +0200
  Re: Is it possible to make a unittest decorator to rename a method from "x" to "testx?" Peter Otten <__peter__@web.de> - 2013-08-08 10:50 +0200
    Re: Is it possible to make a unittest decorator to rename a method from "x" to "testx?" adam.preble@gmail.com - 2013-08-08 09:17 -0700
      Re: Is it possible to make a unittest decorator to rename a method from "x" to "testx?" Ned Batchelder <ned@nedbatchelder.com> - 2013-08-08 13:14 -0400
    Re: Is it possible to make a unittest decorator to rename a method from "x" to "testx?" adam.preble@gmail.com - 2013-08-08 22:07 -0700
      Re: Is it possible to make a unittest decorator to rename a method from "x" to "testx?" Peter Otten <__peter__@web.de> - 2013-08-09 08:31 +0200
        Re: Is it possible to make a unittest decorator to rename a method from "x" to "testx?" adam.preble@gmail.com - 2013-08-11 21:25 -0700

csiph-web