From raoul at snyman.info Wed Jun 15 13:56:03 2022 From: raoul at snyman.info (Raoul Snyman) Date: Wed, 15 Jun 2022 17:56:03 +0000 Subject: [openlp-dev] Parametrize Your Tests Message-ID: <168a3e3f083b8dabc403dfc418cab20b@snyman.info> 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