Hey everyone,

Ever found yourself writing a for-loop in a test, and wondering if there's a better way to do it? Kinda like this?

def test_media_length(media_env):
     """
     Check the duration of a few different files via MediaInfo
     """
    for test_data in TEST_MEDIA:
        # GIVEN: a media file
        full_path = str(TEST_PATH / test_data[0])

        # WHEN the media data is retrieved
        results = media_env.media_controller.media_length(full_path)

        # THEN you can determine the run time
assert results == test_data[1], 'The correct duration is returned for ' + test_data[0]


Yes, there is a better way! It's called "parametrization". Here's how you fix the test above:


@pytest.mark.parametrize('file_name,media_length', TEST_MEDIA)
def test_media_length(file_name, media_length, media_env):
     """
     Check the duration of a few different files via MediaInfo
     """
    # GIVEN: a media file
    full_path = TEST_PATH / file_name

    # WHEN the media data is retrieved
    results = media_env.media_controller.media_length(full_path)

    # THEN you can determine the run time
assert results == media_length, f'The correct duration for {file_name} should be {media_length}, was {results}'


Now pytest will take care of running the test multiple times using the parameters you supplied.


--
Raoul Snyman
_______________________________________________
openlp-dev mailing list
openlp-dev@openlp.io
https://lists.openlp.io/mailman/listinfo/openlp-dev

Reply via email to