Append the nose @attr to the test name

孤街浪徒 提交于 2019-12-03 17:23:09

Here is how to do it with args type attributes:

rename_test.py:

import unittest 
from nose.tools import set_trace

def fancy_attr(*args, **kwargs):
    """Decorator that adds attributes to classes or functions
    for use with the Attribute (-a) plugin. It also renames functions!
    """
    def wrap_ob(ob):
        for name in args:
            setattr(ob, name, True)
            #using __doc__ instead of __name__ works for class methods tests
            ob.__doc__ = '_'.join([ob.__name__, name])
            #ob.__name__ = '_'.join([ob.__name__, name])

        return ob

    return wrap_ob


class TestLogins(unittest.TestCase):
    @fancy_attr('slow')
    def test_method():
        assert True


@fancy_attr('slow')
def test_func():
    assert True

Running test:

$ nosetests rename_test.py -v
test_method_slow ... ok
test_func_slow ... ok

----------------------------------------------------------------------
Ran 2 tests in 0.003s

OK

EDIT: For xunit reporting to work, test renaming should take place before running the test. You can do it on import, here is untested hack showing how to do it:

rename_test.py:

import unittest 

def fancy_attr(*args, **kwargs):
    """Decorator that adds attributes to classes or functions
    for use with the Attribute (-a) plugin. It also renames functions!
    """
    def wrap_ob(ob):
        for name in args:
            setattr(ob, name, True)
            ob.__doc__ = '_'.join([ob.__name__, name])

        return ob

    return wrap_ob


class TestLogins(unittest.TestCase):
    @fancy_attr('slow')
    def test_method(self):
        assert True


def make_name(orig, attrib):
    return '_'.join([orig, attrib])

def rename(cls):
    methods = []
    for key in cls.__dict__:
        method = getattr(cls, key)
        if method:
            if hasattr(cls.__dict__[key], '__dict__'):
                if 'slow' in cls.__dict__[key].__dict__:
                    methods.append(key)

    print methods

    for method in methods:
        setattr(cls, make_name(method, 'slow'),  cls.__dict__[key])
        delattr(cls, method)


rename(TestLogins)

@fancy_attr('slow')
def test_func():
    assert True
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!