Coverage for tests/util.py: 100%

21 statements  

« prev     ^ index     » next       coverage.py v7.4.4, created at 2026-03-26 09:43 +0000

1import pytest 

2import sys 

3 

4 

5@pytest.fixture 

6def module_cleanup(): 

7 """ 

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

9 

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

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

12 for ensuring test isolation when dynamically importing code. 

13 """ 

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

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

16 

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

18 yield 

19 

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

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

22 newly_added_modules = final_modules - initial_modules 

23 

24 for module_name in newly_added_modules: 

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

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

27 if module_name in sys.modules: 

28 del sys.modules[module_name] 

29 

30 

31def round_floats_in_structure(obj, precision: int): 

32 """ 

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

34 Handles nested dictionaries and lists. 

35 """ 

36 if isinstance(obj, float): 

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

38 if obj == 0: 

39 obj = 0.0 

40 return round(obj, precision) 

41 if isinstance(obj, dict): 

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

43 if isinstance(obj, list): 

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

45 return obj