gpt4 book ai didi

python nosetests 设置测试描述

转载 作者:行者123 更新时间:2023-11-28 17:41:02 24 4
gpt4 key购买 nike

我正在(我必须)在 python 中动态创建测试以与 nosetests 一起运行,如下所示:

def my_verification_method(param):
""" description """
assert param>0, "something bad..."

def test_apps():
""" make tests on the fly """
param1 = 1
my_verification_method.__doc__ = "test with param=%i" % param1
yield my_verification_method, param1
param1 = 2
my_verification_method.__doc__ = "test with param=%i" % param1
yield my_verification_method, param1

问题是 nosetest 打印:

make tests on the fly ... ok
make tests on the fly ... ok

这不是我想要的。我想要 nosetests 的输出说:

test with param=1 ... ok
test with param=2 ... ok

有什么想法吗?

最佳答案

这里是如何做你想做的,但它会绕过 yield 测试生成。本质上,您使用下面的 populate() 方法动态填充一个空白的 unittest.TestCase:

from unittest import TestCase

from nose.tools import istest


def my_verification_method(param):
""" description """
print "this is param=", param
assert param > 0, "something bad..."


def method_name(param):
""" this is how you name the tests from param values """
return "test_with_param(%i)" % param


def doc_name(param):
""" this is how you generate doc strings from param values """
return "test with param=%i" % param


def _create(param):
""" Helper method to make functions on the fly """

@istest
def func_name(self):
my_verification_method(param)

return func_name


def populate(cls, params):
""" Helper method that injects tests to the TestCase class """

for param in params:
_method = _create(param)
_method.__name__ = method_name(param)
_method.__doc__ = doc_name(param)
setattr(cls, _method.__name__, _method)


class AppsTest(TestCase):
""" TestCase Container """

pass

test_params = [-1, 1, 2]
populate(AppsTest, test_params)

你应该得到:

$ nosetests doc_test.py -v
test with param=-1 ... FAIL
test with param=1 ... ok
test with param=2 ... ok

您需要更改方法名称和文档字符串才能正确填充您的类。

编辑:func_name 应该有 self 作为参数,因为它现在是一个类方法。

关于python nosetests 设置测试描述,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24270342/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com