pythonmetadataunittest2

Is there a way to add metadata in py files for grouping tests?


Lets say I have the following testcases in different files

Each of which inherits from unittest.TestCase. Is there any ability in python to embed metadata information within these files, so that I can have a main.py script to search for those tags and execute only those testcases?

For Eg: If I want to execute testcases with {tags: Two} then only testcases TestOne.py and TestTwo.py should be executed.


Solution

  • The py.test testing framework has support for meta data, via what they call markers.

    For py.test test cases are functions that have names starting with "test", and which are in modules with names starting with "test". The tests themselves are simple assert statements. py.test can also run tests for the unittest library, and IIRC Nose tests.

    The meta data consists of dynamically generated decorators for the test functions. The decorators have the form: @pytest.mark.my_meta_name. You can choose anything for my_meta_name. There are a few predefined markers that you can see with py.test --markers.

    Here is an adapted snippet from their documentation:

    # content of test_server.py
    
    import pytest
    
    @pytest.mark.webtest
    def test_send_http():
        pass # perform some webtest test for your app
    
    def test_always_succeeds():
        assert 2 == 3 - 1
    
    def test_will_always_fail():
        assert 4 == 5
    

    You select marked tests with the -m command line option of the test runner. To selectively run test_send_http() you enter this into a shell:

    py.test -v -m webtest