How do you generate dynamic (parameterized) unit tests in python?

后端 未结 25 2144
面向向阳花
面向向阳花 2020-11-22 07:09

I have some kind of test data and want to create a unit test for each item. My first idea was to do it like this:

import unittest

l = [[\"foo\", \"a\", \"a\         


        
25条回答
  •  不思量自难忘°
    2020-11-22 07:46

    It can be done by using pytest. Just write the file test_me.py with content:

    import pytest
    
    @pytest.mark.parametrize('name, left, right', [['foo', 'a', 'a'],
                                                   ['bar', 'a', 'b'],
                                                   ['baz', 'b', 'b']])
    def test_me(name, left, right):
        assert left == right, name
    

    And run your test with command py.test --tb=short test_me.py. Then the output will be looks like:

    =========================== test session starts ============================
    platform darwin -- Python 2.7.6 -- py-1.4.23 -- pytest-2.6.1
    collected 3 items
    
    test_me.py .F.
    
    ================================= FAILURES =================================
    _____________________________ test_me[bar-a-b] _____________________________
    test_me.py:8: in test_me
        assert left == right, name
    E   AssertionError: bar
    ==================== 1 failed, 2 passed in 0.01 seconds ====================
    

    It simple!. Also pytest has more features like fixtures, mark, assert, etc ...

提交回复
热议问题