How do I concisely implement multiple similar unit tests in the Python unittest framework?

后端 未结 9 1078
予麋鹿
予麋鹿 2020-12-24 15:10

I\'m implementing unit tests for a family of functions that all share a number of invariants. For example, calling the function with two matrices produce a matrix of known s

9条回答
  •  孤城傲影
    2020-12-24 15:37

    If you're already using nose (and some of your comments suggest you are), why don't you just use Test Generators, which are the most straightforward way to implement parametric tests I've come across:

    For example:

    from binary_search import search1 as search
    
    def test_binary_search():
        data = (
            (-1, 3, []),
            (-1, 3, [1]),
            (0,  1, [1]),
            (0,  1, [1, 3, 5]),
            (1,  3, [1, 3, 5]),
            (2,  5, [1, 3, 5]),
            (-1, 0, [1, 3, 5]),
            (-1, 2, [1, 3, 5]),
            (-1, 4, [1, 3, 5]),
            (-1, 6, [1, 3, 5]),
            (0,  1, [1, 3, 5, 7]),
            (1,  3, [1, 3, 5, 7]),
            (2,  5, [1, 3, 5, 7]),
            (3,  7, [1, 3, 5, 7]),
            (-1, 0, [1, 3, 5, 7]),
            (-1, 2, [1, 3, 5, 7]),
            (-1, 4, [1, 3, 5, 7]),
            (-1, 6, [1, 3, 5, 7]),
            (-1, 8, [1, 3, 5, 7]),
        )
    
        for result, n, ns in data:
            yield check_binary_search, result, n, ns
    
    def check_binary_search(expected, n, ns):
        actual = search(n, ns)
        assert expected == actual
    

    Produces:

    $ nosetests -d
    ...................
    ----------------------------------------------------------------------
    Ran 19 tests in 0.009s
    
    OK
    

提交回复
热议问题