From d0b8afc551b08fe128cb95e60fd5dd7ddf27cbf1 Mon Sep 17 00:00:00 2001 From: James Addison <55152140+jayaddison@users.noreply.github.com> Date: Sun, 3 Nov 2024 13:15:31 +0000 Subject: [PATCH] Tests: prepare test cases at module import-time (#1344) --- tests/__init__.py | 49 +++++++++++++++++++++++++++-------------------- 1 file changed, 28 insertions(+), 21 deletions(-) diff --git a/tests/__init__.py b/tests/__init__.py index c14357643..965a8895d 100644 --- a/tests/__init__.py +++ b/tests/__init__.py @@ -166,6 +166,34 @@ def test_func(self): return test_func +def prepare_test_cases(): + """ + This function dynamically generates the class definition for RecipeTestCase by adding + a test function for each pair of testhtml and testjson files found in the + tests/test_data directory. + """ + test_dir = pathlib.Path("tests/test_data") + for host in test_dir.iterdir(): + if not host.is_dir(): + continue + + for testhtml in host.glob("*.testhtml"): + testjson = testhtml.with_suffix(".json") + if not testjson.is_file(): + continue + + # Add a new function to RecipeTestCase class to test this scraper + # The name of this function the path to the testjson file. + setattr( + RecipeTestCase, + str(testjson), + test_func_factory(host.name, testhtml, testjson), + ) + + +prepare_test_cases() + + def load_tests( loader: unittest.TestLoader, standard_tests: unittest.TestSuite, pattern: str ) -> unittest.TestSuite: @@ -173,10 +201,6 @@ def load_tests( Customise the loading of tests. This function is automatically picked up by the unittest test loader. - This function dynamically generates the class definition for RecipeTestCase by adding - a test function for each pair of testhtml and testjson files found in the - tests/test_data directory. - This also includes the library tests from the tests/library folder as well. @@ -197,23 +221,6 @@ def load_tests( A TestSuite object populated with tests from the pairs of testhtml and testjson files, and the library tests. """ - test_dir = pathlib.Path("tests/test_data") - for host in test_dir.iterdir(): - if not host.is_dir(): - continue - - for testhtml in host.glob("*.testhtml"): - testjson = testhtml.with_suffix(".json") - if not testjson.is_file(): - continue - - # Add a new function to RecipeTestCase class to test this scraper - # The name of this function the path to the testjson file. - setattr( - RecipeTestCase, - str(testjson), - test_func_factory(host.name, testhtml, testjson), - ) # Create a test suite and load all tests from the RecipeTestClass definition suite = unittest.TestSuite()