列表理解中的测试和断言

时间:2016-02-16 10:08:04

标签: python unit-testing testing tdd automated-tests

我是python测试的新手,如果可能的话,想要使用pytest来检查我的函数是否正确。有一个输入和预期输出列表:

GO.GetComponent<Animation>().Play("Start");
GO.GetComponent<Animation>()["Start"].time = ((1f / 30f) * 0);
GO.GetComponent<Animation>()["Start"].speed = 0;

如果将 test_cases = [ ("...Guide: From Mid $1.3ms", [(1300000)]), ("OFFERS OVER $1,100,000", [(1100000)]), ("...Around $1.35million", [(1350000)]), ("Guide above $1.2m", [(1200000)]), ("...From $2.55 Million", [(2550000)]), ("Low $2 millions", [(2000000)]), ("Mid $2M's Buyers", [(2000000)]), ("$305,000 - $349,950", [(305000), (349950)]), ("...$485,000 and $510,000", [(485000), (510000)]), ("...High $300,000's", [(300000)]), ("...000 + to $625,000 +", [(625000)]), ("$299k", [(299000)]), ("... Buyers Guide $1.29M+", [(1290000)]), ("$1m", [(1000000)]), ("$1,000,000.00", [(1000000)]) ] 作为输入,那么测试我的函数返回test_cases[n][1]的最优雅的方法是什么?我能以某种方式断言这一点,同时仍能获得有意义的结果(即10个测试中有7个成功完成,10个测试中有10个成功完成)?

2 个答案:

答案 0 :(得分:4)

The parametrize decorator这样做。您给它一个输入列表,它将为输入列表的每个元素运行一次修饰测试。每个人都将被报告为个人测试。

import pytest

test_cases = [
    ("...Guide: From Mid $1.3ms", [(1300000)]),
    ("OFFERS OVER $1,100,000", [(1100000)]),
    ("...Around $1.35million", [(1350000)]),
    ("Guide above $1.2m", [(1200000)]),
    ("...From $2.55 Million", [(2550000)]),
    ("Low $2 millions", [(2000000)]),
    ("Mid $2M's Buyers", [(2000000)]),
    ("$305,000 - $349,950", [(305000), (349950)]),
    ("...$485,000 and $510,000", [(485000), (510000)]),
    ("...High $300,000's", [(300000)]),
    ("...000 + to $625,000 +", [(625000)]),
    ("$299k", [(299000)]),
    ("... Buyers Guide $1.29M+", [(1290000)]),
    ("$1m", [(1000000)]),
    ("$1,000,000.00", [(1000000)])
]

@pytest.mark.parametrize("in", "out", test_cases)
def test(in, out):
    assert f(in) == out

答案 1 :(得分:0)

reduce功能类似于其他功能语言中的fold。这是对该问题的实用观点:

from functools import reduce
from operator import and_
def test():
    assert reduce(and_, [f(x) == y for x, y in test_cases])