重复单次或多次试验

2024-04-27 13:02:50 发布

您现在位置:Python中文网/ 问答频道 /正文

this question类似,我想让Nose运行一个测试(或所有测试)n次——但是不是并行的

我在一个项目中有几百个测试;有些是一些简单的单元测试。其他的是具有某种程度的并发性的集成测试。在调试测试时,我常常想更努力地“命中”一个测试;bash循环可以工作,但会产生很多杂乱的输出——对于每个通过的测试来说,没有更好的一个“.”。有能力在一些测试中击败被选中的测试似乎是一件很自然的事情,但我在文档中没有找到它。

什么是最简单的方法让鼻子做这个(除了一个bash循环)?


Tags: 项目方法文档bash能力单元测试this事情
3条回答

一种方法是测试本身:

更改此:

class MyTest(unittest.TestCase):

  def test_once(self):
      ...

对此:

class MyTest(unittest.TestCase):

  def assert_once(self):
      ...

  def test_many(self):
      for _ in range(5):
          self.assert_once()

您必须编写一个脚本来执行此操作,但您可以在命令行上重复测试名称X次。

nosetests testname testname testname testname testname testname testname

等等

您可以write a nose test as a generator,nose将运行每个函数 产生:

def check_something(arg):
    # some test ...

def test_something():
    for arg in some_sequence:
        yield (check_something, arg)

使用nose-testconfig,可以使测试运行的次数成为命令行参数:

from testconfig import config

# ...

def test_something():
    for n in range(int(config.get("runs", 1))):
        yield (check_something, arg)

从命令行调用

$ nosetests --tc=runs:5

。。。不止一次。

或者(也可以使用nose testconfig),您可以编写一个decorator:

from functools import wraps
from testconfig import config

def multi(fn):
    @wraps(fn)
    def wrapper():
        for n in range(int(config.get("runs", 1))):
            fn()
    return wrapper

@multi
def test_something():
    # some test ...

然后,如果要将测试划分为不同的组,每个组都有自己的命令行参数,用于指定运行次数:

from functools import wraps
from testconfig import config

def multi(cmd_line_arg):
    def wrap(fn):
        @wraps(fn)
        def wrapper():
            for n in range(int(config.get(cmd_line_arg, 1))):
                fn()
        return wrapper
    return wrap

@multi("foo")
def test_something():
    # some test ...

@multi("bar")
def test_something_else():
    # some test ...

你可以这样称呼它:

$ nosetests --tc=foo:3 --tc=bar:7

相关问题 更多 >