在python中参数化测试的最简单方法? [英] simplest way of parameterizing tests in python?

查看:209
本文介绍了在python中参数化测试的最简单方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含一堆不同对象的库,这些对象具有相似的预期行为,因此我想对它们运行类似的测试,但不一定要对它们进行相同的测试.

I have a library with a bunch of different objects that have similar expected behavior, thus I want to run similar tests on them, but not necessarily identical tests on them.

具体来说,我有一些排序功能,还有一个用于检查排序功能是否实际排序的测试.某些排序功能旨在用于某些输入,但不适用于其他输入.

To be specific lets say I have some sorting functions, and a test for checking if a sorting function actually sorts. Some sorting functions are intended to work on some inputs, but not others.

我想写一些类似于下面的代码.但是,鼻子不能很好地告诉我测试失败的确切位置以及输入的内容.如果对case2的sort2的check_sort失败,我将看不到它.

I'd like to write something close to the code below. However, nose won't do a good job of telling me exactly where the tests failed and with what inputs. If check_sort fails for sort2 on case2, I won't be able to see that.

def check_sort(sortalg, vals):
     assert sortalg(vals) == sort(vals)


def test_sorts(): 
    case1 = [1,3,2]
    case2 = [2,31,1]

    check_sort(sort1, case1)

    for c in [case1, case2]: 
        check_sort(sort2, c)

我希望能够简单地向check_sort添加一个装饰器,以告诉鼻子它是一个嵌套测试.像

I would like to be able to simply add a decorator to check_sort to tell nose that it's a nested test. Something like

@nested_test
def check_sort(sortalg, vals):
     assert sortalg(vals) == sort(vals)

这个想法是,当它被调用时,它会用鼻子注册自己,如果失败则将报告其输入.

The idea being that when it gets called, it registers itself with nose and will report its inputs if it fails.

看起来pytest提供了 pytest.mark.parameterized ,但是对我来说似乎很尴尬.我必须将所有参数放在函数上方,因此不能在测试中重复调用它.我也不认为这支持嵌套多个级别.

It looks like pytest provides pytest.mark.parameterized, but that seems rather awkward to me. I have to put all my arguments above the function in one spot, so I can't call it repeatedly in my tests. I also don't think this supports nesting more than one level.

Nose还提供了测试生成器,它看起来更近了,但仍然没有如我所愿.

Nose also provides test generators, which seems closer, but still not as clear as I would hope.

推荐答案

使用提供的 生成测试 功能是使用鼻子和py.test进行测试的可能预期方式.

Using the provided generative test feature is the likely intended way to do it with nose and py.test.

也就是说,您可以在创建类后向其动态添加函数(测试).这就是 Lib/test/test_decimal.py 标准库中的代码.

That said, you can dynamically add functions (tests) to a class after it has been created. That is the technique used by the Lib/test/test_decimal.py code in the standard library.

这篇关于在python中参数化测试的最简单方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆