Search code examples
pythonunit-testingtestingtddautomated-tests

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. 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? Can I assert this in some way while still getting meaningful results (i.e. 7 out of 10 tests finished successfully, 10 out of 10 tests finished successfully)?


Solution

  • The parametrize decorator does this. 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