Coverage for tests/util.py: 100%

21 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2025-10-20 14:09 +0000

1import pytest 

2import sys 

3 

4@pytest.fixture 

5def module_cleanup(): 

6 """ 

7 A pytest fixture that cleans up any modules imported during a test. 

8 

9 This works by taking a snapshot of sys.modules before the test runs 

10 and removing any new additions after the test completes. This is useful 

11 for ensuring test isolation when dynamically importing code. 

12 """ 

13 # --- SETUP: Take a snapshot of currently loaded modules --- 

14 initial_modules = set(sys.modules.keys()) 

15 

16 # --- The test runs at this point --- 

17 yield 

18 

19 # --- TEARDOWN: Clean up newly added modules --- 

20 final_modules = set(sys.modules.keys()) 

21 newly_added_modules = final_modules - initial_modules 

22 

23 for module_name in newly_added_modules: 

24 # We check again because some modules might be part of a package 

25 # and could have been removed when the parent was removed. 

26 if module_name in sys.modules: 

27 del sys.modules[module_name] 

28 

29 

30def round_floats_in_structure(obj, precision: int): 

31 """ 

32 Recursively traverses a data structure and rounds any float values. 

33 Handles nested dictionaries and lists. 

34 """ 

35 if isinstance(obj, float): 

36 # set the value to 0.0 if it is either 0.0 or -0.0 

37 if obj == 0: 

38 obj = 0.0 

39 return round(obj, precision) 

40 if isinstance(obj, dict): 

41 return {k: round_floats_in_structure(v, precision) for k, v in obj.items()} 

42 if isinstance(obj, list): 

43 return [round_floats_in_structure(elem, precision) for elem in obj] 

44 return obj