Skip to content

Commit 2cb03a4

Browse files
DiogoRibeiro7benoit-cty
authored andcommitted
test: fix auth callback coverage test and temp credentials path
1 parent dab2651 commit 2cb03a4

8 files changed

Lines changed: 169 additions & 78 deletions

File tree

tests/cli/test_cli_auth.py

Lines changed: 20 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import io
22
import json
3+
import tempfile
34
import unittest
45
from pathlib import Path
56
from unittest.mock import MagicMock, patch
@@ -183,16 +184,16 @@ def test_get_access_token_refresh_failure_deletes_credentials(
183184
self, mock_load, mock_validate, mock_refresh
184185
):
185186
original_credentials_file = auth._CREDENTIALS_FILE
186-
temp_credentials = Path("test_credentials.json")
187-
try:
187+
with tempfile.TemporaryDirectory() as tmp_dir:
188+
temp_credentials = Path(tmp_dir) / "test_credentials.json"
188189
temp_credentials.write_text("{}")
189-
auth._CREDENTIALS_FILE = temp_credentials
190-
with self.assertRaises(ValueError):
191-
auth.get_access_token()
192-
self.assertFalse(temp_credentials.exists())
193-
finally:
194-
auth._CREDENTIALS_FILE = original_credentials_file
195-
temp_credentials.unlink(missing_ok=True)
190+
try:
191+
auth._CREDENTIALS_FILE = temp_credentials
192+
with self.assertRaises(ValueError):
193+
auth.get_access_token()
194+
self.assertFalse(temp_credentials.exists())
195+
finally:
196+
auth._CREDENTIALS_FILE = original_credentials_file
196197

197198
@patch("codecarbon.cli.auth._load_credentials")
198199
def test_get_id_token(self, mock_load):
@@ -263,13 +264,21 @@ def test_authorize_raises_on_callback_error(
263264
"abc",
264265
)
265266
mock_session_cls.return_value = mock_session
266-
mock_server_cls.return_value = MagicMock()
267+
mock_server = MagicMock()
268+
mock_server.handle_request.side_effect = lambda: setattr(
269+
auth._CallbackHandler,
270+
"error",
271+
"access_denied",
272+
)
273+
mock_server_cls.return_value = mock_server
267274

268275
auth._CallbackHandler.callback_url = None
269-
auth._CallbackHandler.error = "access_denied"
276+
auth._CallbackHandler.error = None
270277

271278
with self.assertRaises(ValueError):
272279
auth.authorize()
280+
mock_server.handle_request.assert_called_once()
281+
mock_server.server_close.assert_called_once()
273282

274283
@patch("codecarbon.cli.auth.HTTPServer")
275284
@patch("codecarbon.cli.auth.OAuth2Session")

tests/cli/test_cli_utils.py

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,4 @@
11
import configparser
2-
from pathlib import Path
32

43
import pytest
54

@@ -80,7 +79,9 @@ def test_create_new_config_file_creates_parent_and_file(monkeypatch, tmp_path):
8079
target = tmp_path / "nested" / ".codecarbon.config"
8180
prompts = iter([str(target)])
8281

83-
monkeypatch.setattr(cli_utils.typer, "prompt", lambda *args, **kwargs: next(prompts))
82+
monkeypatch.setattr(
83+
cli_utils.typer, "prompt", lambda *args, **kwargs: next(prompts)
84+
)
8485
monkeypatch.setattr(cli_utils.Confirm, "ask", lambda *args, **kwargs: True)
8586

8687
created_path = cli_utils.create_new_config_file()
@@ -96,7 +97,9 @@ def test_create_new_config_file_expands_home(monkeypatch, tmp_path):
9697
target = home / ".codecarbon.config"
9798

9899
monkeypatch.setattr(cli_utils.Path, "home", lambda: home)
99-
monkeypatch.setattr(cli_utils.typer, "prompt", lambda *args, **kwargs: "~/.codecarbon.config")
100+
monkeypatch.setattr(
101+
cli_utils.typer, "prompt", lambda *args, **kwargs: "~/.codecarbon.config"
102+
)
100103

101104
created_path = cli_utils.create_new_config_file()
102105

tests/cli/test_monitor.py

Lines changed: 4 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -22,9 +22,7 @@ def stop(self):
2222

2323
def test_run_and_monitor_requires_command(monkeypatch):
2424
monkeypatch.setattr(monitor_module, "EmissionsTracker", FakeTracker)
25-
monkeypatch.setattr(
26-
monitor_module, "print", lambda *args, **kwargs: None
27-
)
25+
monkeypatch.setattr(monitor_module, "print", lambda *args, **kwargs: None)
2826

2927
with pytest.raises(typer.Exit) as exc_info:
3028
monitor_module.run_and_monitor(SimpleNamespace(args=[]))
@@ -39,9 +37,7 @@ def __init__(self, command, text=True):
3937

4038
monkeypatch.setattr(monitor_module, "EmissionsTracker", FakeTracker)
4139
monkeypatch.setattr(monitor_module.subprocess, "Popen", FakePopen)
42-
monkeypatch.setattr(
43-
monitor_module, "print", lambda *args, **kwargs: None
44-
)
40+
monkeypatch.setattr(monitor_module, "print", lambda *args, **kwargs: None)
4541

4642
with pytest.raises(typer.Exit) as exc_info:
4743
monitor_module.run_and_monitor(SimpleNamespace(args=["missing-command"]))
@@ -56,9 +52,7 @@ def __init__(self, command, text=True):
5652

5753
monkeypatch.setattr(monitor_module, "EmissionsTracker", FakeTracker)
5854
monkeypatch.setattr(monitor_module.subprocess, "Popen", FakePopen)
59-
monkeypatch.setattr(
60-
monitor_module, "print", lambda *args, **kwargs: None
61-
)
55+
monkeypatch.setattr(monitor_module, "print", lambda *args, **kwargs: None)
6256

6357
with pytest.raises(typer.Exit) as exc_info:
6458
monitor_module.run_and_monitor(SimpleNamespace(args=["python"]))
@@ -86,9 +80,7 @@ def kill(self):
8680

8781
monkeypatch.setattr(monitor_module, "EmissionsTracker", FakeTracker)
8882
monkeypatch.setattr(monitor_module.subprocess, "Popen", FakePopen)
89-
monkeypatch.setattr(
90-
monitor_module, "print", lambda *args, **kwargs: None
91-
)
83+
monkeypatch.setattr(monitor_module, "print", lambda *args, **kwargs: None)
9284

9385
with pytest.raises(typer.Exit) as exc_info:
9486
monitor_module.run_and_monitor(SimpleNamespace(args=["python"]))

tests/test_api_call.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -260,7 +260,11 @@ def test_create_run_returns_none_on_unsuccessful_status(self):
260260

261261
def test_list_experiments_from_project_returns_empty_list_on_error(self):
262262
with requests_mock.Mocker() as m:
263-
m.get("http://test.com/projects/proj-1/experiments", text="bad", status_code=500)
263+
m.get(
264+
"http://test.com/projects/proj-1/experiments",
265+
text="bad",
266+
status_code=500,
267+
)
264268
api = ApiClient(
265269
endpoint_url="http://test.com",
266270
create_run_automatically=False,

tests/test_cpu.py

Lines changed: 18 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -10,18 +10,18 @@
1010
from codecarbon.core.config import normalize_gpu_ids
1111
from codecarbon.core.cpu import (
1212
DEFAULT_POWER_PER_CORE,
13+
TDP,
14+
IntelPowerGadget,
15+
IntelRAPL,
1316
_check_energy_file,
1417
_get_candidate_bases,
1518
_is_main_domain,
1619
_scan_base_for_rapl,
1720
_scan_direct_entries,
1821
_scan_domain_directories,
19-
TDP,
20-
IntelPowerGadget,
21-
IntelRAPL,
2222
is_powergadget_available,
23-
is_rapl_available,
2423
is_psutil_available,
24+
is_rapl_available,
2525
)
2626
from codecarbon.core.resource_tracker import ResourceTracker
2727
from codecarbon.core.units import Energy, Power, Time
@@ -32,7 +32,9 @@
3232

3333
class TestCPU(unittest.TestCase):
3434
@mock.patch("codecarbon.core.cpu.IntelPowerGadget", side_effect=Exception("boom"))
35-
def test_is_powergadget_available_returns_false_on_exception(self, mock_powergadget):
35+
def test_is_powergadget_available_returns_false_on_exception(
36+
self, mock_powergadget
37+
):
3638
self.assertFalse(is_powergadget_available())
3739

3840
@mock.patch("psutil.cpu_times")
@@ -141,19 +143,21 @@ def test_scan_base_for_rapl_checks_direct_entries_fallback(self):
141143
with (
142144
mock.patch("codecarbon.core.cpu.os.listdir", return_value=["intel-rapl:0"]),
143145
mock.patch("codecarbon.core.cpu.os.path.isdir", return_value=False),
144-
mock.patch("codecarbon.core.cpu._scan_domain_directories", return_value=False),
146+
mock.patch(
147+
"codecarbon.core.cpu._scan_domain_directories", return_value=False
148+
),
145149
mock.patch("codecarbon.core.cpu._scan_direct_entries", return_value=True),
146150
):
147151
assert _scan_base_for_rapl("/tmp/base", lambda _: None) is True
148152

149153
@mock.patch("codecarbon.core.cpu._scan_base_for_rapl", side_effect=[False, True])
150154
@mock.patch("codecarbon.core.cpu._get_candidate_bases", return_value=["a", "b"])
151-
def test_is_rapl_available_scans_candidate_bases(
152-
self, mock_candidates, mock_scan
153-
):
155+
def test_is_rapl_available_scans_candidate_bases(self, mock_candidates, mock_scan):
154156
assert is_rapl_available("/tmp/custom") is True
155157

156-
@mock.patch("codecarbon.core.cpu._scan_base_for_rapl", side_effect=Exception("boom"))
158+
@mock.patch(
159+
"codecarbon.core.cpu._scan_base_for_rapl", side_effect=Exception("boom")
160+
)
157161
@mock.patch("codecarbon.core.cpu._get_candidate_bases", return_value=["a"])
158162
def test_is_rapl_available_returns_false_on_unexpected_error(
159163
self, mock_candidates, mock_scan
@@ -221,9 +225,7 @@ def test_setup_cli_uses_windows_backup_when_primary_missing(self):
221225
),
222226
mock.patch(
223227
"codecarbon.core.cpu.shutil.which",
224-
side_effect=lambda path: None
225-
if path == "PowerLog3.0.exe"
226-
else path,
228+
side_effect=lambda path: None if path == "PowerLog3.0.exe" else path,
227229
),
228230
):
229231
gadget = IntelPowerGadget()
@@ -269,7 +271,9 @@ def test_log_values_warns_on_nonzero_returncode_windows(self):
269271
gadget._log_file_path = "intel.csv"
270272

271273
with (
272-
mock.patch("codecarbon.core.cpu.subprocess.call", return_value=1) as mock_call,
274+
mock.patch(
275+
"codecarbon.core.cpu.subprocess.call", return_value=1
276+
) as mock_call,
273277
mock.patch("codecarbon.core.cpu.logger.warning") as mock_warning,
274278
):
275279
gadget._log_values()

tests/test_powermetrics.py

Lines changed: 12 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,9 @@ def test_has_powermetrics_sudo_returns_false_on_password_prompt(self):
7373
),
7474
mock.patch(
7575
"codecarbon.core.powermetrics.subprocess.Popen",
76-
return_value=FakeProcess(stderr="[sudo] password for user:", returncode=0),
76+
return_value=FakeProcess(
77+
stderr="[sudo] password for user:", returncode=0
78+
),
7779
),
7880
):
7981
assert powermetrics_module._has_powermetrics_sudo() is False
@@ -106,15 +108,19 @@ def test_has_powermetrics_sudo_returns_true_on_success(self):
106108
assert powermetrics_module._has_powermetrics_sudo() is True
107109

108110
def test_setup_cli_raises_on_unsupported_platform(self):
109-
with mock.patch.object(ApplePowermetrics, "_setup_cli", ApplePowermetrics._setup_cli):
111+
with mock.patch.object(
112+
ApplePowermetrics, "_setup_cli", ApplePowermetrics._setup_cli
113+
):
110114
with mock.patch("codecarbon.core.powermetrics.sys.platform", "win32"):
111115
with pytest.raises(SystemError):
112116
ApplePowermetrics()
113117

114118
def test_setup_cli_raises_when_binary_missing_on_apple_silicon(self):
115119
with (
116120
mock.patch("codecarbon.core.powermetrics.sys.platform", "darwin"),
117-
mock.patch("codecarbon.core.powermetrics.detect_cpu_model", return_value="Apple M4"),
121+
mock.patch(
122+
"codecarbon.core.powermetrics.detect_cpu_model", return_value="Apple M4"
123+
),
118124
mock.patch("codecarbon.core.powermetrics.shutil.which", return_value=None),
119125
):
120126
with pytest.raises(FileNotFoundError):
@@ -134,7 +140,9 @@ def test_log_values_warns_on_nonzero_returncode(self):
134140
powermetrics._log_file_path = "powermetrics_log.txt"
135141

136142
with (
137-
mock.patch("codecarbon.core.powermetrics.subprocess.call", return_value=1) as mock_call,
143+
mock.patch(
144+
"codecarbon.core.powermetrics.subprocess.call", return_value=1
145+
) as mock_call,
138146
mock.patch("codecarbon.core.powermetrics.logger.warning") as mock_warning,
139147
):
140148
powermetrics._log_values()

tests/test_ram.py

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -148,9 +148,7 @@ def test_parse_scontrol_falls_back_to_machine_total_when_multiple_matches(
148148
mock_virtual_memory.return_value = mock.Mock(total=32 * 1024**3)
149149
ram = RAM(tracking_mode="slurm")
150150

151-
result = ram._parse_scontrol(
152-
"AllocTRES=cpu=1,mem=4G AllocTRES=cpu=1,mem=8G"
153-
)
151+
result = ram._parse_scontrol("AllocTRES=cpu=1,mem=4G AllocTRES=cpu=1,mem=8G")
154152

155153
self.assertEqual(result, mock_virtual_memory.return_value.total / (1024**3))
156154

@@ -201,7 +199,9 @@ def test_process_memory_gb_includes_children(self, mock_process):
201199
mock_process.return_value = process
202200
ram = RAM(pid=123, tracking_mode="process")
203201

204-
with mock.patch.object(ram, "_get_children_memories", return_value=[1024**3, 0]):
202+
with mock.patch.object(
203+
ram, "_get_children_memories", return_value=[1024**3, 0]
204+
):
205205
result = ram.process_memory_GB
206206

207207
self.assertEqual(result, 4.0)
@@ -222,8 +222,15 @@ def test_total_power_uses_process_memory_in_process_mode(self):
222222
ram = RAM(tracking_mode="process")
223223

224224
with (
225-
mock.patch.object(type(ram), "process_memory_GB", new_callable=mock.PropertyMock, return_value=12.0),
226-
mock.patch.object(ram, "_calculate_ram_power", return_value=18.0) as mock_calc,
225+
mock.patch.object(
226+
type(ram),
227+
"process_memory_GB",
228+
new_callable=mock.PropertyMock,
229+
return_value=12.0,
230+
),
231+
mock.patch.object(
232+
ram, "_calculate_ram_power", return_value=18.0
233+
) as mock_calc,
227234
):
228235
result = ram.total_power()
229236

@@ -234,7 +241,10 @@ def test_total_power_returns_zero_on_exception(self):
234241
ram = RAM(tracking_mode="machine")
235242

236243
with mock.patch.object(
237-
type(ram), "machine_memory_GB", new_callable=mock.PropertyMock, side_effect=RuntimeError("boom")
244+
type(ram),
245+
"machine_memory_GB",
246+
new_callable=mock.PropertyMock,
247+
side_effect=RuntimeError("boom"),
238248
):
239249
result = ram.total_power()
240250

0 commit comments

Comments
 (0)