禁用Python nosetests

53 投票
5 回答
27506 浏览
提问于 2025-04-15 12:52

在使用nosetests来测试Python代码时,可以通过把测试函数的__test__属性设置为假,来禁用一个单元测试。我用下面这个装饰器实现了这个功能:

def unit_test_disabled():
    def wrapper(func):
         func.__test__ = False
         return func

    return wrapper

@unit_test_disabled
def test_my_sample_test()
    #code here ...

不过,这样做的一个副作用是,包装函数会被当作单元测试来调用。这个包装函数总是会通过测试,但它会出现在nosetests的输出中。有没有其他方法可以调整这个装饰器,让测试不运行,也不出现在nosetests的输出里呢?

5 个回答

75

你还可以使用 unittest.skip 这个装饰器:

import unittest


@unittest.skip("temporarily disabled")
class MyTestCase(unittest.TestCase):
    ...
156

Nose已经内置了一个装饰器来实现这个功能:

from nose.tools import nottest

@nottest
def test_my_sample_test()
    #code here ...

另外,别忘了看看Nose提供的其他好东西:https://nose.readthedocs.org/en/latest/testing_tools.html

-18

我觉得你还需要把你的装饰器重命名成一个不包含“test”的名字。下面的代码在我这儿只有第二个测试失败,第一项在测试列表中没有显示出来。

def unit_disabled(func):
    def wrapper(func):
         func.__test__ = False
         return func

    return wrapper

@unit_disabled
def test_my_sample_test():
    assert 1 <> 1

def test2_my_sample_test():
    assert 1 <> 1

撰写回答