-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_native_views.py
More file actions
385 lines (273 loc) · 12.1 KB
/
test_native_views.py
File metadata and controls
385 lines (273 loc) · 12.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
"""Unit tests for the native_views package.
Tests the registry, base handler protocol, and shared utility functions.
Platform-specific handlers (android/ios) are not tested here since they
require their respective runtime environments; they are exercised by
E2E tests on device.
"""
from typing import Any, Dict, Tuple
import pytest
from pythonnative.layout import LAYOUT_STYLE_KEYS
from pythonnative.native_views import NativeViewRegistry, set_registry
from pythonnative.native_views.base import (
ViewHandler,
is_vertical,
parse_color_int,
resolve_padding,
)
# ======================================================================
# parse_color_int
# ======================================================================
def test_parse_color_hex6() -> None:
result = parse_color_int("#FF0000")
assert result == parse_color_int("FF0000")
expected = int("FFFF0000", 16)
if expected > 0x7FFFFFFF:
expected -= 0x100000000
assert result == expected
def test_parse_color_hex8() -> None:
result = parse_color_int("#80FF0000")
raw = int("80FF0000", 16)
expected = raw - 0x100000000 # signed conversion
assert result == expected
def test_parse_color_int_passthrough() -> None:
assert parse_color_int(0x00FF00) == 0x00FF00
def test_parse_color_signed_conversion() -> None:
result = parse_color_int("#FFFFFFFF")
assert result < 0
def test_parse_color_with_whitespace() -> None:
assert parse_color_int(" #FF0000 ") == parse_color_int("#FF0000")
# ======================================================================
# resolve_padding (legacy helper retained for handlers that still need it)
# ======================================================================
def test_resolve_padding_none() -> None:
assert resolve_padding(None) == (0, 0, 0, 0)
def test_resolve_padding_int() -> None:
assert resolve_padding(16) == (16, 16, 16, 16)
def test_resolve_padding_float() -> None:
assert resolve_padding(8.5) == (8, 8, 8, 8)
def test_resolve_padding_dict_horizontal_vertical() -> None:
result = resolve_padding({"horizontal": 10, "vertical": 20})
assert result == (10, 20, 10, 20)
def test_resolve_padding_dict_individual() -> None:
result = resolve_padding({"left": 1, "top": 2, "right": 3, "bottom": 4})
assert result == (1, 2, 3, 4)
def test_resolve_padding_dict_all() -> None:
result = resolve_padding({"all": 12})
assert result == (12, 12, 12, 12)
def test_resolve_padding_unsupported_type() -> None:
assert resolve_padding("invalid") == (0, 0, 0, 0)
# ======================================================================
# is_vertical
# ======================================================================
def test_is_vertical_column() -> None:
assert is_vertical("column") is True
def test_is_vertical_column_reverse() -> None:
assert is_vertical("column_reverse") is True
def test_is_vertical_row() -> None:
assert is_vertical("row") is False
def test_is_vertical_row_reverse() -> None:
assert is_vertical("row_reverse") is False
# ======================================================================
# Layout-engine ownership
# ======================================================================
def test_layout_style_keys_includes_flex_props() -> None:
"""All flex / sizing props are owned by the layout engine, not handlers."""
for key in (
"width",
"height",
"flex",
"flex_grow",
"flex_shrink",
"flex_basis",
"flex_direction",
"justify_content",
"align_items",
"align_self",
"padding",
"margin",
"spacing",
"gap",
"position",
"top",
"right",
"bottom",
"left",
"aspect_ratio",
):
assert key in LAYOUT_STYLE_KEYS
# ======================================================================
# ViewHandler protocol
# ======================================================================
def test_view_handler_create_raises() -> None:
handler = ViewHandler()
with pytest.raises(NotImplementedError):
handler.create({})
def test_view_handler_update_raises() -> None:
handler = ViewHandler()
with pytest.raises(NotImplementedError):
handler.update(None, {})
def test_view_handler_add_child_noop() -> None:
handler = ViewHandler()
handler.add_child(None, None)
def test_view_handler_remove_child_noop() -> None:
handler = ViewHandler()
handler.remove_child(None, None)
def test_view_handler_insert_child_delegates() -> None:
calls: list = []
class TestHandler(ViewHandler):
def add_child(self, parent: Any, child: Any) -> None:
calls.append(("add", parent, child))
handler = TestHandler()
handler.insert_child("parent", "child", 0)
assert calls == [("add", "parent", "child")]
def test_view_handler_set_frame_default_noop() -> None:
"""Default ``set_frame`` is a no-op so virtual nodes can opt out."""
handler = ViewHandler()
handler.set_frame(None, 0, 0, 100, 50)
def test_view_handler_measure_intrinsic_default_zero() -> None:
"""Default ``measure_intrinsic`` returns ``(0, 0)`` for handlers without intrinsic size."""
handler = ViewHandler()
assert handler.measure_intrinsic(None, 100.0, 100.0) == (0.0, 0.0)
# ======================================================================
# NativeViewRegistry
# ======================================================================
class StubView:
def __init__(self, type_name: str, props: Dict[str, Any]) -> None:
self.type_name = type_name
self.props = dict(props)
self.frame: Tuple[float, float, float, float] = (0.0, 0.0, 0.0, 0.0)
class StubHandler(ViewHandler):
def create(self, props: Dict[str, Any]) -> StubView:
return StubView("Stub", props)
def update(self, native_view: Any, changed_props: Dict[str, Any]) -> None:
native_view.props.update(changed_props)
def set_frame(self, native_view: Any, x: float, y: float, width: float, height: float) -> None:
native_view.frame = (x, y, width, height)
def measure_intrinsic(self, native_view: Any, max_width: float, max_height: float) -> Tuple[float, float]:
# Pretend the stub view is 40x10 plus its content length.
return (min(40.0 + len(native_view.props.get("text", "")), max_width), 10.0)
def test_registry_create_view() -> None:
reg = NativeViewRegistry()
reg.register("Text", StubHandler())
view = reg.create_view("Text", {"text": "hello"})
assert isinstance(view, StubView)
assert view.props["text"] == "hello"
def test_registry_unknown_type_raises() -> None:
reg = NativeViewRegistry()
with pytest.raises(ValueError, match="Unknown element type"):
reg.create_view("NonExistent", {})
def test_registry_update_view() -> None:
reg = NativeViewRegistry()
reg.register("Text", StubHandler())
view = reg.create_view("Text", {"text": "old"})
reg.update_view(view, "Text", {"text": "new"})
assert view.props["text"] == "new"
def test_registry_update_unknown_type_noop() -> None:
reg = NativeViewRegistry()
reg.update_view(StubView("X", {}), "X", {"a": 1})
def test_registry_child_ops_unknown_type_noop() -> None:
reg = NativeViewRegistry()
reg.add_child(None, None, "Unknown")
reg.remove_child(None, None, "Unknown")
reg.insert_child(None, None, "Unknown", 0)
def test_registry_set_frame_dispatches_to_handler() -> None:
reg = NativeViewRegistry()
reg.register("Text", StubHandler())
view = reg.create_view("Text", {"text": "x"})
reg.set_frame(view, "Text", 5.0, 10.0, 100.0, 50.0)
assert view.frame == (5.0, 10.0, 100.0, 50.0)
def test_registry_set_frame_unknown_type_noop() -> None:
reg = NativeViewRegistry()
reg.set_frame(None, "Unknown", 0, 0, 100, 50)
def test_registry_measure_intrinsic_dispatches() -> None:
reg = NativeViewRegistry()
reg.register("Text", StubHandler())
view = reg.create_view("Text", {"text": "abc"})
w, h = reg.measure_intrinsic(view, "Text", 1000.0, 1000.0)
assert w == 43.0 # 40 + 3
assert h == 10.0
def test_registry_measure_intrinsic_unknown_type_zero() -> None:
reg = NativeViewRegistry()
assert reg.measure_intrinsic(None, "Unknown", 1000.0, 1000.0) == (0.0, 0.0)
def test_set_registry_injects() -> None:
reg = NativeViewRegistry()
set_registry(reg)
from pythonnative.native_views import _registry
assert _registry is reg
set_registry(None)
# ======================================================================
# _tripwire_log rate limiter
# ======================================================================
@pytest.fixture
def _tripwire_state() -> Any:
"""Reset the per-label tripwire state before each test."""
import pythonnative.native_views as nv
nv._TRIPWIRE_LAST_LOG_TIME.clear()
nv._TRIPWIRE_SUPPRESSED_COUNT.clear()
yield nv
nv._TRIPWIRE_LAST_LOG_TIME.clear()
nv._TRIPWIRE_SUPPRESSED_COUNT.clear()
def test_tripwire_log_first_call_emits(capsys: pytest.CaptureFixture[str], _tripwire_state: Any) -> None:
_tripwire_state._tripwire_log("test:basic", "first message")
captured = capsys.readouterr()
assert "first message" in captured.err
def test_tripwire_log_subsequent_within_window_suppressed(
capsys: pytest.CaptureFixture[str], _tripwire_state: Any
) -> None:
_tripwire_state._tripwire_log("test:burst", "first")
capsys.readouterr()
_tripwire_state._tripwire_log("test:burst", "second")
_tripwire_state._tripwire_log("test:burst", "third")
captured = capsys.readouterr()
assert captured.err == ""
assert _tripwire_state._TRIPWIRE_SUPPRESSED_COUNT["test:burst"] == 2
def test_tripwire_log_after_window_emits_with_summary(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
_tripwire_state: Any,
) -> None:
"""After the window expires, the next emit includes a ``+N similar`` suffix."""
import time as _time
monkeypatch.setattr(_tripwire_state, "_TRIPWIRE_RATE_LIMIT_S", 0.05)
_tripwire_state._tripwire_log("test:summary", "first sample")
capsys.readouterr()
_tripwire_state._tripwire_log("test:summary", "suppressed-A")
_tripwire_state._tripwire_log("test:summary", "suppressed-B")
_time.sleep(0.06)
_tripwire_state._tripwire_log("test:summary", "third sample")
captured = capsys.readouterr()
assert "third sample" in captured.err
assert "+2 similar" in captured.err
assert _tripwire_state._TRIPWIRE_SUPPRESSED_COUNT["test:summary"] == 0
def test_tripwire_log_distinct_labels_independent(capsys: pytest.CaptureFixture[str], _tripwire_state: Any) -> None:
"""A burst on one label must not silence a different label's first emit."""
_tripwire_state._tripwire_log("test:a", "from a")
_tripwire_state._tripwire_log("test:a", "still a, suppressed")
_tripwire_state._tripwire_log("test:b", "from b")
captured = capsys.readouterr()
assert "from a" in captured.err
assert "from b" in captured.err
assert "still a" not in captured.err
def test_tripwire_log_suffix_omitted_when_zero_suppressed(
monkeypatch: pytest.MonkeyPatch,
capsys: pytest.CaptureFixture[str],
_tripwire_state: Any,
) -> None:
"""The ``+N similar`` suffix only appears when at least one was suppressed."""
import time as _time
monkeypatch.setattr(_tripwire_state, "_TRIPWIRE_RATE_LIMIT_S", 0.01)
_tripwire_state._tripwire_log("test:nosuffix", "alpha")
_time.sleep(0.02)
_tripwire_state._tripwire_log("test:nosuffix", "beta")
captured = capsys.readouterr()
assert "beta" in captured.err
assert "similar" not in captured.err
def test_registry_set_frame_nan_emits_tripwire(capsys: pytest.CaptureFixture[str], _tripwire_state: Any) -> None:
"""``set_frame`` with a NaN dimension fires the rate-limited tripwire."""
reg = NativeViewRegistry()
reg.register("Text", StubHandler())
view = reg.create_view("Text", {"text": "x"})
reg.set_frame(view, "Text", 0.0, 0.0, float("nan"), 50.0)
captured = capsys.readouterr()
assert "[set_frame:nan]" in captured.err
assert "type='Text'" in captured.err