|
19 | 19 | import argparse |
20 | 20 | import asyncio |
21 | 21 | import logging |
| 22 | +import re |
22 | 23 | from collections.abc import Coroutine |
23 | 24 | from typing import Any |
24 | 25 | from unittest.mock import AsyncMock, MagicMock, patch |
|
28 | 29 |
|
29 | 30 | from esphome_device_builder.discover import ( |
30 | 31 | _COLUMN_NAMES, |
| 32 | + _FORMAT, |
| 33 | + _MAX_ESPHOME_DISPLAY, |
| 34 | + _MAX_NAME_DISPLAY, |
| 35 | + _MAX_PIN_DISPLAY, |
| 36 | + _MAX_PORT_DISPLAY, |
| 37 | + _MAX_SERVER_DISPLAY, |
31 | 38 | _UNKNOWN, |
32 | 39 | _build_parser, |
33 | | - _decode, |
| 40 | + _decode_mdns_label_or_unknown, |
34 | 41 | _on_service_state_change, |
35 | 42 | _run, |
| 43 | + _safe_label, |
36 | 44 | _truncate_pin, |
37 | 45 | main, |
38 | 46 | ) |
|
44 | 52 | (b"hello", "hello"), |
45 | 53 | ("plain", "plain"), |
46 | 54 | (None, _UNKNOWN), |
47 | | - # ``bytes`` containing a non-UTF-8 sequence falls through |
48 | | - # the strict decode and lands on the replacement-char path |
49 | | - # (rather than raising) so a malformed TXT entry doesn't |
50 | | - # crash the browse loop. |
| 55 | + # ``bytes`` containing a non-UTF-8 sequence falls through the |
| 56 | + # ``"replace"`` handler so a malformed TXT entry doesn't crash the |
| 57 | + # browse loop. Pin the actual U+FFFD output (one per invalid byte) |
| 58 | + # so a future refactor that silently swaps the handler for an |
| 59 | + # UNKNOWN-or-empty fallback trips a red test. |
51 | 60 | (b"\xff\xfe", "��"), |
52 | 61 | ], |
53 | 62 | ) |
54 | 63 | def test_decode_handles_every_txt_wire_shape(raw: str | bytes | None, expected: str) -> None: |
55 | | - """``_decode`` round-trips bytes, leaves strings alone, marks missing.""" |
56 | | - assert _decode(raw) == expected |
| 64 | + """``_decode_mdns_label_or_unknown`` decodes / sanitizes bytes + str, marks missing.""" |
| 65 | + assert _decode_mdns_label_or_unknown(raw) == expected |
| 66 | + |
| 67 | + |
| 68 | +def test_safe_label_strips_ansi_escape_introducer() -> None: |
| 69 | + """ESC bytes are stripped; trailing printable tail survives.""" |
| 70 | + assert _safe_label("\x1b[2Jvers1.0", 32) == "[2Jvers1.0" |
| 71 | + |
| 72 | + |
| 73 | +def test_safe_label_strips_newline_cr_null_tab() -> None: |
| 74 | + """Control bytes that could reflow or terminate the printed row are dropped.""" |
| 75 | + assert _safe_label("line1\r\nline2", 32) == "line1line2" |
| 76 | + assert _safe_label("col\tumn", 32) == "column" |
| 77 | + assert _safe_label("esp\x0032", 32) == "esp32" |
| 78 | + |
| 79 | + |
| 80 | +def test_safe_label_caps_length() -> None: |
| 81 | + """Oversized peer-supplied labels can't break the column-aligned table.""" |
| 82 | + assert _safe_label("x" * 200, 10) == "x" * 10 |
| 83 | + |
| 84 | + |
| 85 | +def test_safe_label_preserves_non_ascii_printable() -> None: |
| 86 | + """Non-ASCII printable characters survive (``str.isprintable`` is Unicode-aware).""" |
| 87 | + assert _safe_label("café", 32) == "café" |
| 88 | + |
| 89 | + |
| 90 | +def test_decode_mdns_label_or_unknown_strips_control_chars_in_bytes() -> None: |
| 91 | + """Bytes path runs the ANSI / CR / LF / NUL / TAB strip.""" |
| 92 | + assert _decode_mdns_label_or_unknown(b"\x1b[2J0.1.62", 32) == "[2J0.1.62" |
| 93 | + assert _decode_mdns_label_or_unknown(b"line1\r\nline2", 32) == "line1line2" |
| 94 | + assert _decode_mdns_label_or_unknown(b"col\tumn", 32) == "column" |
| 95 | + assert _decode_mdns_label_or_unknown(b"esp\x0032", 32) == "esp32" |
| 96 | + |
| 97 | + |
| 98 | +def test_decode_mdns_label_or_unknown_strips_control_chars_in_str() -> None: |
| 99 | + """Str path also runs the sanitizer (peer-provided strs are equally hostile).""" |
| 100 | + assert _decode_mdns_label_or_unknown("\x1b[2J0.1.62", 32) == "[2J0.1.62" |
| 101 | + |
| 102 | + |
| 103 | +def test_decode_mdns_label_or_unknown_caps_length_with_explicit_limit() -> None: |
| 104 | + assert _decode_mdns_label_or_unknown(b"x" * 200, 10) == "x" * 10 |
| 105 | + |
| 106 | + |
| 107 | +def test_decode_mdns_label_or_unknown_default_limit_caps_long_value() -> None: |
| 108 | + """Default cap is the Name column width from ``_FORMAT``.""" |
| 109 | + assert len(_decode_mdns_label_or_unknown("a" * 200)) == _MAX_NAME_DISPLAY |
| 110 | + |
| 111 | + |
| 112 | +def test_decode_mdns_label_or_unknown_unicode_printable_survives() -> None: |
| 113 | + assert _decode_mdns_label_or_unknown("café") == "café" |
| 114 | + |
| 115 | + |
| 116 | +def test_per_column_caps_match_format_widths() -> None: |
| 117 | + """Per-column caps stay locked to the ``_FORMAT`` widths. |
| 118 | +
|
| 119 | + A peer-controlled value can never widen a column past its slot; |
| 120 | + if ``_FORMAT`` changes and this fires, update the cap derivation |
| 121 | + in ``discover.py`` rather than bumping the expected values. The |
| 122 | + pin cap stays at 64 because ``_truncate_pin`` collapses to 12 |
| 123 | + chars + ellipsis at print time, bounded independently. |
| 124 | + """ |
| 125 | + widths = tuple(int(w) for w in re.findall(r"<\s*(\d+)", _FORMAT)) |
| 126 | + assert widths[_COLUMN_NAMES.index("Name")] == _MAX_NAME_DISPLAY |
| 127 | + assert widths[_COLUMN_NAMES.index("Server")] == _MAX_SERVER_DISPLAY |
| 128 | + assert widths[_COLUMN_NAMES.index("ESPHome")] == _MAX_ESPHOME_DISPLAY |
| 129 | + assert widths[_COLUMN_NAMES.index("RB Port")] == _MAX_PORT_DISPLAY |
| 130 | + assert _MAX_PIN_DISPLAY == 64 |
| 131 | + |
| 132 | + |
| 133 | +def test_on_service_state_change_sanitizes_hostile_service_name( |
| 134 | + capsys: pytest.CaptureFixture[str], |
| 135 | +) -> None: |
| 136 | + """ESC bytes in the mDNS instance name don't reach stdout.""" |
| 137 | + fake_info = MagicMock() |
| 138 | + fake_info.properties = {} |
| 139 | + fake_info.ip_addresses_by_version.return_value = ["192.168.1.10"] |
| 140 | + fake_info.port = 6052 |
| 141 | + |
| 142 | + with patch("esphome_device_builder.discover.AsyncServiceInfo", return_value=fake_info): |
| 143 | + _on_service_state_change( |
| 144 | + MagicMock(), |
| 145 | + "_esphomebuilder._tcp.local.", |
| 146 | + "\x1b[2Jevil._esphomebuilder._tcp.local.", |
| 147 | + ServiceStateChange.Added, |
| 148 | + ) |
| 149 | + |
| 150 | + captured = capsys.readouterr().out |
| 151 | + assert "\x1b" not in captured |
| 152 | + assert "[2Jevil" in captured |
| 153 | + |
| 154 | + |
| 155 | +def test_on_service_state_change_sanitizes_hostile_txt_values( |
| 156 | + capsys: pytest.CaptureFixture[str], |
| 157 | +) -> None: |
| 158 | + """ESC / CR / LF in TXT values don't reach stdout.""" |
| 159 | + fake_info = MagicMock() |
| 160 | + fake_info.properties = { |
| 161 | + b"server_version": b"\x1b[2J0.1.62", |
| 162 | + b"esphome_version": b"line1\r\nline2", |
| 163 | + b"pin_sha256": b"a" * 64, |
| 164 | + b"remote_build_port": b"6053", |
| 165 | + } |
| 166 | + fake_info.ip_addresses_by_version.return_value = ["192.168.1.10"] |
| 167 | + fake_info.port = 6052 |
| 168 | + |
| 169 | + with patch("esphome_device_builder.discover.AsyncServiceInfo", return_value=fake_info): |
| 170 | + _on_service_state_change( |
| 171 | + MagicMock(), |
| 172 | + "_esphomebuilder._tcp.local.", |
| 173 | + "build-server._esphomebuilder._tcp.local.", |
| 174 | + ServiceStateChange.Added, |
| 175 | + ) |
| 176 | + |
| 177 | + captured = capsys.readouterr().out |
| 178 | + assert "\x1b" not in captured |
| 179 | + assert "\r" not in captured |
| 180 | + assert "[2J0.1.62" in captured |
| 181 | + assert "line1line2" in captured |
57 | 182 |
|
58 | 183 |
|
59 | 184 | @pytest.mark.parametrize( |
|
0 commit comments