python参数化是什么意思_在python中参数化测试的最简单方法?

本文探讨了在进行参数化测试时遇到的问题,特别是针对一组具有相似行为的对象进行测试的情况。作者提出了一种使用装饰器来标记嵌套测试的方法,并讨论了nose和pytest等测试框架的功能限制。最终建议采用动态添加测试函数到类的方法来实现目标。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

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)

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.

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 also provides test generators, which seems closer, but still not as clear as I would hope.

解决方案

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

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.

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值