Files
slic/tests/test_utils_pv.py
T
tligui_y c2fe04f94f
Run CI Tests / test (push) Successful in 2m41s
Update tests/test_utils_pv.py
2025-08-05 12:49:35 +02:00

103 lines
3.2 KiB
Python

# Fichier test_utils_pv.py corrigé
import pytest
from io import StringIO
import colorama
from slic.utils.pv import PV
from epics import PV as EpicsPV
class FakeEPICS(EpicsPV):
def __init__(self, pvname, **kwargs):
super().__init__(pvname, **kwargs)
self._value = 0.0 # Initial value set to 0.0
self.units = "units"
self._callbacks = {}
self.pvname = pvname # Important pour le repr
def get(self, *args, **kwargs):
return self._value
def put(self, value, *args, **kwargs):
self._value = value
# Trigger all callbacks
for callback in self._callbacks.values():
callback(value=value, **kwargs)
return value
def add_callback(self, callback, **kwargs):
cb_index = len(self._callbacks) + 1
self._callbacks[cb_index] = callback
return cb_index
def remove_callback(self, cb_index):
self._callbacks.pop(cb_index, None)
def __repr__(self):
return f"PV {self.pvname} at {self._value} {self.units}"
@pytest.fixture
def fake_epics_pv(monkeypatch):
monkeypatch.setattr("epics.PV", FakeEPICS)
pv = PV("TEST:PV")
# Force initial value
pv.put(0.0, wait=True)
return pv
@pytest.fixture
def capture_stdout(monkeypatch):
buf = StringIO()
monkeypatch.setattr("sys.stdout", buf)
return buf
@pytest.mark.parametrize("value, expected_bar, expected_color, expected_repr", [
(25.0, "██▌ ", colorama.Fore.GREEN, 'PV "TEST:PV" at 25.0 units'),
(50.0, "█████ ", colorama.Fore.GREEN, 'PV "TEST:PV" at 50.0 units'),
(75.0, "███████▌ ", colorama.Fore.GREEN, 'PV "TEST:PV" at 75.0 units'),
(100.0, "██████████", colorama.Fore.GREEN, 'PV "TEST:PV" at 100.0 units'),
(150.0, ">>>>>>>>>>", colorama.Fore.RED, 'PV "TEST:PV" at 150.0 units'),
(-50.0, "<<<<<<<<<<", colorama.Fore.RED, 'PV "TEST:PV" at -50.0 units')
])
def test_progress_and_repr(fake_epics_pv, capture_stdout, value, expected_bar, expected_color, expected_repr):
pv = fake_epics_pv
# Verify initial value is properly set to 0.0
assert pv.get() == 0.0
# Test put() with progress
pv.put(value, show_progress=True)
output = capture_stdout.getvalue()
# Verify progress bar display
assert f"|{expected_bar}|" in output
assert expected_color in output
assert str(value) in output
# Verify value was updated
assert pv.get() == pytest.approx(value)
# Test string representation
assert repr(pv) == expected_repr
assert pv.orig_repr() == f"PV TEST:PV at {value} units"
capture_stdout.truncate(0)
def test_use_callback_context_manager(fake_epics_pv):
pv = fake_epics_pv
callback_log = []
def test_callback(value, **kwargs):
callback_log.append(value)
# Verify no callbacks initially
assert len(pv._pv._callbacks) == 0
with pv.use_callback(test_callback):
# Callback should be added
assert len(pv._pv._callbacks) == 1
# Trigger callback
pv.put(10.0)
assert callback_log == [10.0]
# Callback should be removed
assert len(pv._pv._callbacks) == 0