80 lines
2.3 KiB
Python
80 lines
2.3 KiB
Python
"""CPU sampler unit tests (mocked psutil)."""
|
|
|
|
from __future__ import annotations
|
|
|
|
import sys
|
|
import types
|
|
from pathlib import Path
|
|
from unittest.mock import patch
|
|
|
|
import pytest
|
|
|
|
_AGENT_DIR = Path(__file__).resolve().parents[1] / "web" / "agent"
|
|
if str(_AGENT_DIR) not in sys.path:
|
|
sys.path.insert(0, str(_AGENT_DIR))
|
|
|
|
# cpu_metrics imports psutil at module load — inject stub before import
|
|
if "psutil" not in sys.modules:
|
|
sys.modules["psutil"] = types.ModuleType("psutil")
|
|
|
|
import cpu_metrics
|
|
|
|
|
|
@pytest.fixture(autouse=True)
|
|
def _reset_sampler_state():
|
|
cpu_metrics._primed = False
|
|
cpu_metrics._watch_bootstrapped = False
|
|
yield
|
|
cpu_metrics._primed = False
|
|
cpu_metrics._watch_bootstrapped = False
|
|
|
|
|
|
def test_watch_first_sample_blocks_one_second():
|
|
calls: list[object] = []
|
|
|
|
def fake_cpu(interval=None, percpu=False):
|
|
calls.append((interval, percpu))
|
|
if percpu:
|
|
return [10.0, 20.0]
|
|
return 15.0
|
|
|
|
with patch("cpu_metrics.psutil.cpu_percent", side_effect=fake_cpu, create=True):
|
|
cpu_metrics.reset_watch_cpu_bootstrap()
|
|
overall, per = cpu_metrics.sample_watch_cpu_bundle()
|
|
|
|
assert calls[0] == (None, False) # prime
|
|
assert calls[1] == (1.0, True) # bootstrap
|
|
assert overall == 15.0
|
|
assert per == [10.0, 20.0]
|
|
|
|
|
|
def test_watch_subsequent_uses_nonblocking_window():
|
|
with patch("cpu_metrics.psutil.cpu_percent", side_effect=[
|
|
0.0, # prime
|
|
[5.0, 5.0], # bootstrap percpu
|
|
[8.0, 12.0], # second sample
|
|
], create=True) as mock_cpu:
|
|
cpu_metrics.reset_watch_cpu_bootstrap()
|
|
cpu_metrics.sample_watch_cpu_bundle()
|
|
overall, per = cpu_metrics.sample_watch_cpu_bundle()
|
|
|
|
from unittest.mock import call
|
|
|
|
assert mock_cpu.call_args_list[-1] == call(interval=None, percpu=True)
|
|
assert overall == 10.0
|
|
assert per == [8.0, 12.0]
|
|
|
|
|
|
def test_reset_watch_cpu_bootstrap_reblocks():
|
|
with patch("cpu_metrics.psutil.cpu_percent", side_effect=[
|
|
0.0, # prime (first bundle)
|
|
[1.0], # bootstrap percpu
|
|
[9.0], # re-bootstrap after reset (no second prime)
|
|
], create=True):
|
|
cpu_metrics.reset_watch_cpu_bootstrap()
|
|
cpu_metrics.sample_watch_cpu_bundle()
|
|
cpu_metrics.reset_watch_cpu_bootstrap()
|
|
overall, _ = cpu_metrics.sample_watch_cpu_bundle()
|
|
|
|
assert overall == 9.0
|