Debian Codegraph @

tests/test_widgets.py

raw symbols SCIP
1 """Tests for urwid widget wrappers: ScalableBarGraph, LabeledBarGraphVector,
2 BarGraphVector, SummaryTextList, and ViListBox."""
3
4 from collections import OrderedDict
5 from unittest.mock import MagicMock
6
7 import pytest
8 import urwid
9
10 from s_tui.sturwid.bar_graph_vector import BarGraphVector
11 from s_tui.sturwid.complex_bar_graph import LabeledBarGraphVector, ScalableBarGraph
12 from s_tui.sturwid.summary_text_list import SummaryTextList
13 from s_tui.sturwid.ui_elements import ViListBox
14
15 # =====================================================================
16 # ScalableBarGraph
17 # =====================================================================
18
19
20 class TestScalableBarGraph:
21 def test_init(self):
22 """ScalableBarGraph can be constructed with segment colours."""
23 g = ScalableBarGraph(["bg", "colA", "colB"])
24 assert isinstance(g, urwid.BarGraph)
25
26 def test_get_size_default(self):
27 """Before rendering, size is (0, 0)."""
28 g = ScalableBarGraph(["bg", "colA", "colB"])
29 assert g.get_size() == (0, 0)
30
31 def test_calculate_bar_widths_with_bar_width(self):
32 """When bar_width is set, widths are uniform."""
33 g = ScalableBarGraph(["bg", "colA", "colB"])
34 g.set_bar_width(2)
35 widths = g.calculate_bar_widths((10, 5), [[1], [2], [3]])
36 assert widths == [2, 2, 2]
37
38 def test_calculate_bar_widths_bar_width_clips(self):
39 """Bars are clipped when they don't fit."""
40 g = ScalableBarGraph(["bg", "colA", "colB"])
41 g.set_bar_width(3)
42 widths = g.calculate_bar_widths((7, 5), [[1], [2], [3], [4], [5]])
43 # Only 7//3 = 2 bars fit
44 assert len(widths) == 2
45
46 def test_calculate_bar_widths_stretch(self):
47 """When bar_width is None, bars stretch to fill space."""
48 g = ScalableBarGraph(["bg", "colA", "colB"])
49 g.set_bar_width(None)
50 widths = g.calculate_bar_widths((10, 5), [[1], [2]])
51 assert sum(widths) == 10
52
53 def test_calculate_bar_widths_more_bars_than_cols(self):
54 """When data bars >= maxcol, each bar is width 1."""
55 g = ScalableBarGraph(["bg", "colA", "colB"])
56 g.set_bar_width(None)
57 widths = g.calculate_bar_widths((3, 5), [[1], [2], [3], [4]])
58 assert widths == [1, 1, 1]
59
60
61 # =====================================================================
62 # LabeledBarGraphVector
63 # =====================================================================
64
65
66 class TestLabeledBarGraphVector:
67 def _make(self, n_graphs=2, visible=None):
68 """Helper to build a LabeledBarGraphVector."""
69 graphs = [ScalableBarGraph(["bg", "a", "b"]) for _ in range(n_graphs)]
70 if visible is None:
71 visible = [True] * n_graphs
72 return LabeledBarGraphVector(
73 "Title", [f"sub{i}" for i in range(n_graphs)], [], graphs, visible
74 )
75
76 def test_init(self):
77 """Construction succeeds with valid args."""
78 v = self._make(2)
79 assert isinstance(v, urwid.WidgetPlaceholder)
80
81 def test_rejects_non_scalable_graph(self):
82 """Constructor raises if graph is not ScalableBarGraph."""
83 with pytest.raises(Exception, match="ScalableBarGraph"):
84 LabeledBarGraphVector("T", ["s"], [], [urwid.BarGraph(["bg", "a"])], [True])
85
86 def test_set_visible_graphs(self):
87 """set_visible_graphs hides/shows sub-graphs."""
88 v = self._make(2)
89 v.set_visible_graphs([True, False])
90 assert v.visible_graph_list == [True, False]
91
92 def test_set_visible_graphs_all_false(self):
93 """When all disabled, widget is empty Pile."""
94 v = self._make(2)
95 v.set_visible_graphs([False, False])
96 assert isinstance(v.original_widget, urwid.Pile)
97
98 def test_set_title(self):
99 """set_title changes the title widget text."""
100 v = self._make(1)
101 v.set_title("New Title")
102 # Should not crash
103
104 def test_check_label_empty(self):
105 """Empty y_label is valid."""
106 v = self._make(1)
107 assert v.check_label([]) is True
108
109 def test_bar_graph_vector_stored(self):
110 """bar_graph_vector is accessible."""
111 v = self._make(3)
112 assert len(v.bar_graph_vector) == 3
113
114
115 # =====================================================================
116 # BarGraphVector
117 # =====================================================================
118
119
120 class TestBarGraphVector:
121 @pytest.fixture
122 def mock_source(self):
123 """Create a mock source for BarGraphVector."""
124 src = MagicMock()
125 src.get_source_name.return_value = "CPU Util"
126 src.get_measurement_unit.return_value = "%"
127 src.get_sensor_list.return_value = ["Avg", "Core 0"]
128 src.get_is_available.return_value = True
129 src.get_reading_list.return_value = [25.0, 30.0]
130 src.get_top.return_value = 100
131 src.get_edge_triggered.return_value = False
132 return src
133
134 def test_init(self, mock_source):
135 """BarGraphVector initializes with source data."""
136 bv = BarGraphVector(
137 mock_source,
138 ["colA", "colB", "smA", "smB"],
139 graph_count=2,
140 visible_graph_list=[True, True],
141 )
142 assert bv.graph_name == "CPU Util"
143 assert bv.measurement_unit == "%"
144
145 def test_append_latest_value(self):
146 """append_latest_value rolls the window forward."""
147 values = [1, 2, 3, 4, 5]
148 result = BarGraphVector.append_latest_value(values, 6)
149 assert result == [2, 3, 4, 5, 6]
150
151 def test_max_samples(self):
152 """MAX_SAMPLES is a reasonable constant."""
153 assert BarGraphVector.MAX_SAMPLES > 0
154
155 def test_graph_data_init(self, mock_source):
156 """Each graph track starts with MAX_SAMPLES zeros."""
157 bv = BarGraphVector(
158 mock_source,
159 ["colA", "colB", "smA", "smB"],
160 graph_count=2,
161 visible_graph_list=[True, True],
162 )
163 assert len(bv.graph_data) == 2
164 assert len(bv.graph_data[0]) == BarGraphVector.MAX_SAMPLES
165 assert all(v == 0 for v in bv.graph_data[0])
166
167 def test_alert_colors_default(self, mock_source):
168 """When no alert_colors given, falls back to regular_colors."""
169 bv = BarGraphVector(
170 mock_source,
171 ["colA", "colB", "smA", "smB"],
172 graph_count=1,
173 visible_graph_list=[True],
174 )
175 assert bv.alert_colors == bv.regular_colors
176
177 def test_alert_colors_custom(self, mock_source):
178 """Custom alert_colors override defaults."""
179 alert = ["alertA", "alertB", "alertSmA", "alertSmB"]
180 bv = BarGraphVector(
181 mock_source,
182 ["colA", "colB", "smA", "smB"],
183 graph_count=1,
184 visible_graph_list=[True],
185 alert_colors=alert,
186 )
187 assert bv.alert_colors == alert
188
189
190 # =====================================================================
191 # SummaryTextList
192 # =====================================================================
193
194
195 class TestSummaryTextList:
196 @pytest.fixture
197 def mock_source(self):
198 src = MagicMock()
199 src.get_source_name.return_value = "CPU Util"
200 src.get_is_available.return_value = True
201 summary = OrderedDict(
202 [
203 ("CPU Util", ""),
204 ("Avg", "25.0%"),
205 ("Core 0", "30.0%"),
206 ]
207 )
208 src.get_summary.return_value = summary
209 return src
210
211 def test_init(self, mock_source):
212 """SummaryTextList initializes with source and visibility."""
213 stl = SummaryTextList(mock_source, [True, True])
214 assert stl.source is mock_source
215
216 def test_get_text_item_list(self, mock_source):
217 """get_text_item_list returns urwid column widgets."""
218 stl = SummaryTextList(mock_source, [True, True])
219 items = stl.get_text_item_list()
220 assert len(items) == 3 # title + 2 sensors (all visible)
221
222 def test_hidden_sensors(self, mock_source):
223 """Hidden sensors are excluded from get_text_item_list."""
224 stl = SummaryTextList(mock_source, [True, False])
225 items = stl.get_text_item_list()
226 # Title + 1 visible sensor
227 assert len(items) == 2
228
229 def test_all_hidden_hides_title(self, mock_source):
230 """When all sensors hidden, title is hidden too."""
231 stl = SummaryTextList(mock_source, [False, False])
232 items = stl.get_text_item_list()
233 assert len(items) == 0
234
235 def test_update(self, mock_source):
236 """update() refreshes text values from source."""
237 stl = SummaryTextList(mock_source, [True, True])
238 stl.get_text_item_list() # populates summary_text_items
239
240 # Change source values
241 new_summary = OrderedDict(
242 [
243 ("CPU Util", ""),
244 ("Avg", "50.0%"),
245 ("Core 0", "60.0%"),
246 ]
247 )
248 mock_source.get_summary.return_value = new_summary
249 stl.update()
250
251 # Text widgets should be updated
252 assert stl.summary_text_items["Avg"].get_text()[0] == "50.0%"
253
254 def test_update_visibility(self, mock_source):
255 """update_visibility changes which sensors are shown."""
256 stl = SummaryTextList(mock_source, [True, True])
257 stl.update_visibility([False, True])
258 keys = list(stl.visible_summaries.keys())
259 # Title visible if any visible
260 assert stl.visible_summaries[keys[0]] is True
261 assert stl.visible_summaries[keys[1]] is False
262 assert stl.visible_summaries[keys[2]] is True
263
264 def test_get_is_available(self, mock_source):
265 """get_is_available delegates to source."""
266 stl = SummaryTextList(mock_source, [True])
267 assert stl.get_is_available() is True
268
269
270 # =====================================================================
271 # ViListBox
272 # =====================================================================
273
274
275 class TestViListBox:
276 def _make(self):
277 body = urwid.SimpleFocusListWalker([urwid.Text("line1"), urwid.Text("line2")])
278 return ViListBox(body)
279
280 def test_vi_j_maps_to_down(self):
281 """'j' key maps to 'down'."""
282 lb = self._make()
283 result = lb.keypress((10, 10), "j")
284 # If handled, returns None; if passed through, returns the remapped key
285 # The key should be remapped but may not be fully consumed
286 assert result is None or result == "down"
287
288 def test_vi_k_maps_to_up(self):
289 """'k' key maps to 'up'."""
290 lb = self._make()
291 # Focus on second item first
292 lb.set_focus(1)
293 result = lb.keypress((10, 10), "k")
294 assert result is None or result == "up"
295
296 def test_vi_h_maps_to_left(self):
297 """'h' key maps to 'left'."""
298 lb = self._make()
299 result = lb.keypress((10, 10), "h")
300 # left may not be consumed by a simple list
301 assert result in (None, "left")
302
303 def test_vi_l_maps_to_right(self):
304 """'l' key maps to 'right'."""
305 lb = self._make()
306 result = lb.keypress((10, 10), "l")
307 assert result in (None, "right")
308
309 def test_q_passthrough(self):
310 """'q' key passes through as 'q'."""
311 lb = self._make()
312 result = lb.keypress((10, 10), "q")
313 assert result == "q"
314
315 def test_normal_key_passthrough(self):
316 """Non-vi keys pass through unchanged."""
317 lb = self._make()
318 result = lb.keypress((10, 10), "a")
319 assert result == "a"