简体   繁体   English

列表理解中的测试和断言

[英]testing and assertion in list comprehension

I'm new to python testing, and want to use pytest if possible to check that my function does the right thing.我是 python 测试的新手,如果可能的话,我想使用pytest来检查我的函数是否正确。 There's a list of inputs and expected outputs:有一个输入和预期输出列表:

    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)])
        ]

What is the most elegant way to test that my function returns test_cases[n][1] if test_cases[n][0] was given as an input?如果test_cases[n][0]作为输入,测试我的函数是否返回test_cases[n][1]的最优雅的方法是什么? Can I assert this in some way while still getting meaningful results (ie 7 out of 10 tests finished successfully, 10 out of 10 tests finished successfully)?我能否以某种方式断言这一点,同时仍然获得有意义的结果(即 10 个测试中有 7 个成功完成,10 个测试中有 10 个成功完成)?

The parametrize decorator does this. parametrize装饰器就是这样做的。 You give it an input list, and it'll run the decorated test once for each element of the input list.你给它一个输入列表,它会为输入列表的每个元素运行一次装饰测试。 Each one will be reported as an individual test.每一项都将作为一项单独的测试报告。

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

reduce function is similar to fold in other functional languages. reduce函数类似于其他函数式语言中的fold Here is a functional take on the problem:这是对这个问题的函数式处理:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM