@@ -54,7 +54,7 @@ def test_main_rapl_permission_error(tmp_path):
5454
5555
5656@pytest .mark .skipif (not sys .platform .lower ().startswith ("lin" ), reason = "requires Linux" )
57- def test_non_main_rapl_permission_warning_and_skip (tmp_path , caplog ):
57+ def test_non_main_rapl_permission_warning_and_skip (tmp_path ):
5858 """If a non-main domain (e.g. psys) is unreadable, it should be skipped and warn."""
5959 base = tmp_path
6060 # Create proper RAPL hierarchy: base/intel-rapl/intel-rapl:N/
@@ -76,7 +76,20 @@ def test_non_main_rapl_permission_warning_and_skip(tmp_path, caplog):
7676
7777 # Make the non-main energy file unreadable
7878 mode_before = energy1 .stat ().st_mode
79- caplog .set_level (logging .WARNING , logger = "codecarbon" )
79+
80+ # Add a custom handler to capture warnings (since logger.propagate = False)
81+ from codecarbon .external .logger import logger as codecarbon_logger
82+
83+ log_records = []
84+
85+ class TestHandler (logging .Handler ):
86+ def emit (self , record ):
87+ log_records .append (record )
88+
89+ test_handler = TestHandler ()
90+ test_handler .setLevel (logging .WARNING )
91+ codecarbon_logger .addHandler (test_handler )
92+
8093 try :
8194 os .chmod (energy1 , 0 )
8295 rapl = IntelRAPL (rapl_dir = str (base ))
@@ -85,13 +98,14 @@ def test_non_main_rapl_permission_warning_and_skip(tmp_path, caplog):
8598 assert rapl ._rapl_files [0 ].path .endswith ("intel-rapl/intel-rapl:0/energy_uj" )
8699
87100 # A warning about permission denied should be emitted
88- messages = [r .getMessage () for r in caplog . records ]
101+ messages = [r .getMessage () for r in log_records ]
89102 assert any (
90103 "Permission denied reading RAPL file" in m
91104 or "Permission denied listing" in m
92105 for m in messages
93- )
106+ ), f"Expected permission warning, got: { messages } "
94107 finally :
108+ codecarbon_logger .removeHandler (test_handler )
95109 try :
96110 os .chmod (energy1 , stat .S_IMODE (mode_before ) or 0o644 )
97111 except Exception :
0 commit comments