From ca73bcbdc3c05b8baad55683938aa98c91e31baa Mon Sep 17 00:00:00 2001 From: Edward Viaene Date: Fri, 20 Nov 2026 21:19:35 -0600 Subject: [PATCH] TCP transport: resolve a host name once, IPv4 first; pod names connect BenchPod("benchpod-c2f662.local") took about 50 s on macOS: every command dials a new connection and looked the name up again, and a default (AF_UNSPEC) lookup of a .local name waits about 5 s for an AAAA answer an IPv4-only pod never sends. - TcpTransport resolves a name once (AF_INET first, AF_UNSPEC only without an IPv4 answer) and reuses the address; a failed connect drops it so the next attempt resolves again (new DHCP lease). TLS still gets the name as given: same pin key and SNI. - parse_connection: a pod name (benchpod-a1b2c3, a1b2c3) is found over mDNS (discovery.find_pod, which stops as soon as the pod answers), else usb:, like the CLI. Without zeroconf it is benchpod-.local. A .local name stays a host name. Co-Authored-By: Claude Opus 5.5 --- packages/embeddedci-mcp/README.md | 2 +- packages/embeddedci/CHANGELOG.md | 15 ++ packages/embeddedci/README.md | 1 + .../src/embeddedci/benchpod/client.py | 4 +- .../src/embeddedci/benchpod/connection.py | 48 ++++- .../src/embeddedci/benchpod/discovery.py | 35 ++- .../src/embeddedci/benchpod/transport/tcp.py | 71 ++++++- packages/embeddedci/tests/test_tcp_resolve.py | 199 ++++++++++++++++++ 8 files changed, 358 insertions(+), 17 deletions(-) create mode 100644 packages/embeddedci/tests/test_tcp_resolve.py diff --git a/packages/embeddedci-mcp/README.md b/packages/embeddedci-mcp/README.md index 43f6f59..6d5c698 100644 --- a/packages/embeddedci-mcp/README.md +++ b/packages/embeddedci-mcp/README.md @@ -140,7 +140,7 @@ transparently, so an idle chat never blocks CI on that pod. `status` shows the p | Flag | Environment | Default | | | --- | --- | --- | --- | -| `--connection` | `BENCHPOD_CONNECTION` | the CLI's saved connection, else mDNS | host[:port], serial device, `usb`, `usb:`, `discover`, `saved`, or `embeddedci:`; unset = `benchpod set-connection`'s saved one, else find the one pod on the LAN | +| `--connection` | `BENCHPOD_CONNECTION` | the CLI's saved connection, else mDNS | host[:port], a pod name (`benchpod-a1b2c3`: mDNS, else USB), serial device, `usb`, `usb:`, `discover`, `saved`, or `embeddedci:`; unset = `benchpod set-connection`'s saved one, else find the one pod on the LAN | | `--la-voltage` | `BENCHPOD_LA_VOLTAGE` | — | LA I/O voltage (1.8 or 3.3; 5.0 on a digital v3r4 pod) applied on connect | | `--wiring-autosave` | `BENCHPOD_WIRING_AUTOSAVE` | off | `set_wiring` also stores the profile on the pod (not a change of the I/O voltage, power rail or SWD target: those need `save_wiring`) | | — | `BENCHPOD_API_KEY` | — | cloud pods and the waveform library (without it, cloud tools use the `benchpod login` session) | diff --git a/packages/embeddedci/CHANGELOG.md b/packages/embeddedci/CHANGELOG.md index 1fc3b6a..be3fc43 100644 --- a/packages/embeddedci/CHANGELOG.md +++ b/packages/embeddedci/CHANGELOG.md @@ -1,5 +1,20 @@ # Changelog — `embeddedci` +## 4.0.2, not released yet + +- **Connecting by host name is fast again.** The SDK opens a new connection per command and + looked the host name up every time. On macOS a default lookup of a `.local` name waits about + 5 s for an IPv6 answer an IPv4-only pod never sends, so `BenchPod("benchpod-c2f662.local")` took + about 50 s (10 lookups) against 0.8 s by IP address. Now a transport looks a name up once, + IPv4 first (any address family only when there is no IPv4 answer), and reuses the address. A + connect that fails looks the name up again, so a pod that gets a new DHCP lease is still found. + The TLS pin in `known_pods.json` stays keyed by the name you gave, and the SNI is unchanged. +- **A pod name works as a connection.** `BenchPod("benchpod-c2f662")` (or `"c2f662"`) finds the + pod on the LAN over mDNS (`[discovery]` extra), else on USB (`usb:benchpod-c2f662`), as the + `benchpod` CLI does. Without `[discovery]` it is the host name `benchpod-c2f662.local`. + `benchpod-c2f662.local` stays a host name. New: `discovery.find_pod(short)`, which stops + browsing as soon as that pod answers. + ## 4.0.1 For BenchPod firmware 4.0.1. Works with firmware 4.0.0 too. diff --git a/packages/embeddedci/README.md b/packages/embeddedci/README.md index cf94cf7..80126da 100644 --- a/packages/embeddedci/README.md +++ b/packages/embeddedci/README.md @@ -218,6 +218,7 @@ explicitly. The pytest plugin does **not** fall back to it (see [pytest plugin]( | `192.168.1.213`, `benchpod-baea06.local`, `[fe80::1]` | network: JSON over TLS on port 8443 (see [TLS on the LAN](#tls-on-the-lan)); an address on the pod's USB network adapter (`10.237.x.y`) is plaintext 8080 | | `host:8080`, `host:8443` | network on that port: `:8080` is plaintext (refused on Ethernet and Wi-Fi unless the pod's HTTPS-only is off), `:8443` TLS | | `/dev/ttyACM0`, `COM3`, `\\.\COM10` | USB console, explicit device path | +| `benchpod-baea06`, `baea06` | the pod with that name (as on its label and in `discover`): its address found on the LAN over mDNS, else `usb:benchpod-baea06`. Without `[discovery]` it is the host name `benchpod-baea06.local` | | `usb` | USB pod, auto-detected by probing the serial ports: its USB network adapter (full API), else its USB console (status only) | | `usb:` | the USB pod with that name when several are plugged into one computer: `usb:baea06`, `usb:benchpod-baea06` (any case, optional `.local`); otherwise as `usb` | | `discover` (or `mdns`, `auto`) | find exactly one pod on the LAN via mDNS (needs `[discovery]`); errors on zero or several | diff --git a/packages/embeddedci/src/embeddedci/benchpod/client.py b/packages/embeddedci/src/embeddedci/benchpod/client.py index 1bb7313..917cfaa 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/client.py +++ b/packages/embeddedci/src/embeddedci/benchpod/client.py @@ -318,7 +318,9 @@ def __init__( """Open a BenchPod. ``connection`` is a host[:port], a serial device path, ``"usb"`` (auto-detect the USB - pod), ``"usb:"`` (one of several USB pods, by name), ``"discover"`` (find one pod on the LAN via mDNS), or ``"embeddedci:"`` + pod), ``"usb:"`` (one of several USB pods, by name), a pod name (``"benchpod-a1b2c3"``: + found on the LAN over mDNS, else on USB), ``"discover"`` (find one pod on the LAN via + mDNS), or ``"embeddedci:"`` to drive a named device through embeddedci.com. When omitted ``BENCHPOD_CONNECTION`` is used, else the default connection ``benchpod-cli`` saved (``benchpod set-connection``); ``"saved"`` names that one explicitly. Pass ``transport`` to inject a custom backend diff --git a/packages/embeddedci/src/embeddedci/benchpod/connection.py b/packages/embeddedci/src/embeddedci/benchpod/connection.py index b4d3851..e671d5e 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/connection.py +++ b/packages/embeddedci/src/embeddedci/benchpod/connection.py @@ -12,6 +12,9 @@ :func:`~embeddedci.benchpod.transport.open_transport`) * ``usb:`` -> the USB pod with that name, when several are plugged in (``usb:baea06``, ``usb:benchpod-baea06``) +* ``benchpod-a1b2c3`` / ``a1b2c3`` -> the pod with that name: its address found on the LAN over + mDNS, else ``usb:`` (as the ``benchpod`` CLI does). + ``benchpod-a1b2c3.local`` stays a host name. * ``discover`` / ``mdns`` / ``auto`` -> find a single pod on the LAN via mDNS * ``embeddedci:`` -> drive a named device through embeddedci.com (an API key anywhere, or GitHub Actions OIDC) @@ -43,6 +46,10 @@ USB_PREFIX = "usb:" _COM_RE = re.compile(r"^COM[0-9]+$", re.IGNORECASE) +#: A pod's name as on its label and in ``discover``: ``benchpod-a1b2c3`` or ``a1b2c3`` (its identity +#: short id). Only this exact shape is a pod name; ``benchpod-a1b2c3.local`` and every other host +#: name go to the OS resolver (the pin of a ``.local`` name stays keyed by that name). +_POD_NAME_RE = re.compile(r"^(?:benchpod-)?[0-9a-f]{6}$", re.IGNORECASE) @dataclass @@ -140,9 +147,40 @@ def parse_connection(raw: str) -> ConnSpec: return _discover_one() if _is_device_path(s): return ConnSpec(kind="serial", device=s) + if _POD_NAME_RE.match(s): + return _find_named_pod(normalize_pod_name(s)) return ConnSpec(kind="tcp", addr=_normalize_addr(s)) +def _find_named_pod(short: str) -> ConnSpec: + """The pod named ``benchpod-``: its address when it answers on the LAN over mDNS, else + ``usb:``, which finds it on USB. Without the ``discovery`` extra (zeroconf) it is the + host name ``benchpod-.local``, left to the OS resolver.""" + from .discovery import find_pod + + try: + pod = find_pod(short) + except RuntimeError: # no zeroconf + return ConnSpec(kind="tcp", addr=_normalize_addr(f"benchpod-{short}.local")) + if pod is None: + return ConnSpec(kind="serial", device="", pod=short) + _refuse_firmware_3(pod) + return ConnSpec(kind="tcp", addr=_normalize_addr(pod.addr)) + + +def _refuse_firmware_3(pod) -> None: # noqa: ANN001 - a DiscoveredPod + if pod.supported: + return + from .errors import FirmwareTooOldError + from .feature_map import MIN_FIRMWARE + + raise FirmwareTooOldError( + f"the BenchPod found on the LAN ({pod.name}, {pod.hostname}) announces no client API " + f"2: it runs firmware 3.x, and this SDK needs firmware {MIN_FIRMWARE} or later. Update " + "it with the BenchPod CLI (`benchpod flash-self`) or the firmware update in the web " + "app, or use embeddedci 3.x with it", api=pod.api or 1) + + def _discover_one() -> ConnSpec: """Resolve a single LAN pod via mDNS, or raise a helpful error. @@ -167,15 +205,7 @@ def _discover_one() -> ConnSpec: f"hostname (e.g. {pods[0].hostname}):\n{listing}" ) pod = pods[0] - if not pod.supported: - from .errors import FirmwareTooOldError - from .feature_map import MIN_FIRMWARE - - raise FirmwareTooOldError( - f"the BenchPod found on the LAN ({pod.name}, {pod.hostname}) announces no client API " - f"2: it runs firmware 3.x, and this SDK needs firmware {MIN_FIRMWARE} or later. Update " - "it with the BenchPod CLI (`benchpod flash-self`) or the firmware update in the web " - "app, or use embeddedci 3.x with it", api=pod.api or 1) + _refuse_firmware_3(pod) return ConnSpec(kind="tcp", addr=_normalize_addr(pod.addr)) diff --git a/packages/embeddedci/src/embeddedci/benchpod/discovery.py b/packages/embeddedci/src/embeddedci/benchpod/discovery.py index 9c41479..861a935 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/discovery.py +++ b/packages/embeddedci/src/embeddedci/benchpod/discovery.py @@ -18,9 +18,9 @@ from __future__ import annotations import ipaddress -import time +import threading from dataclasses import dataclass, field -from typing import Dict, List +from typing import Dict, List, Optional #: DNS-SD service type the firmware advertises. SERVICE_TYPE = "_benchpod._tcp.local." @@ -96,6 +96,30 @@ def discover(timeout: float = DEFAULT_TIMEOUT) -> List[DiscoveredPod]: Raises :class:`RuntimeError` with an install hint if ``zeroconf`` is not installed. Returns an empty list when nothing answers. """ + return sorted(_browse(timeout).values(), key=lambda p: p.name) + + +def names_pod(pod: DiscoveredPod, short: str) -> bool: + """Whether ``pod`` is the pod with the short id ``short`` (``"a1b2c3"``), by its DNS-SD + instance (``"BenchPod a1b2c3"``) or host name (``"benchpod-a1b2c3.local"``).""" + from .connection import normalize_pod_name + + return normalize_pod_name(pod.name) == short or normalize_pod_name(pod.hostname) == short + + +def find_pod(short: str, timeout: float = DEFAULT_TIMEOUT) -> Optional[DiscoveredPod]: + """Browse the LAN for the pod with the short id ``short`` (``"a1b2c3"``), stopping as soon as + it answers; None when it does not within ``timeout`` seconds. Raises :class:`RuntimeError` + without ``zeroconf``, like :func:`discover`.""" + for pod in _browse(timeout, want=short).values(): + if names_pod(pod, short) and pod.addresses: + return pod + return None + + +def _browse(timeout: float, want: str = "") -> Dict[str, DiscoveredPod]: + """The pods heard within ``timeout`` seconds, by service name; with ``want`` (a short id) the + browse ends as soon as that pod answers with an address.""" try: from zeroconf import ServiceBrowser, Zeroconf except ImportError as exc: # pragma: no cover - exercised via install extra @@ -105,6 +129,7 @@ def discover(timeout: float = DEFAULT_TIMEOUT) -> List[DiscoveredPod]: ) from exc found: Dict[str, DiscoveredPod] = {} + done = threading.Event() zc = Zeroconf() def _record(zeroconf, type_: str, name: str) -> None: @@ -129,6 +154,8 @@ def _record(zeroconf, type_: str, name: str) -> None: api=_txt_int(txt, "api"), https_only=txt.get("https_only", "") == "1", ) + if want and found[name].addresses and names_pod(found[name], want): + done.set() class _Listener: def add_service(self, zeroconf, type_, name): @@ -142,8 +169,8 @@ def remove_service(self, zeroconf, type_, name): ServiceBrowser(zc, SERVICE_TYPE, _Listener()) try: - time.sleep(timeout) + done.wait(timeout) finally: zc.close() - return sorted(found.values(), key=lambda p: p.name) + return dict(found) diff --git a/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py b/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py index b6b1b20..c862334 100644 --- a/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py +++ b/packages/embeddedci/src/embeddedci/benchpod/transport/tcp.py @@ -6,10 +6,16 @@ reads the reply. ``dap_start`` is special — after its ack the same socket switches to a raw length-framed CMSIS-DAP stream, so the ack must be read one byte at a time so no DAP bytes are swallowed. + +A host name is resolved once per transport (IPv4 first, see :func:`resolve_host`) and the address +is reused for the following connections; a connect that fails resolves the name again, so a pod +that got a new DHCP lease is still found. TLS still uses the name as given: the certificate pin is +keyed by it, and it is the SNI for a name. """ from __future__ import annotations +import ipaddress import json import os import socket @@ -53,6 +59,35 @@ def _io_errors(what: str, timeout: Optional[float]) -> Iterator[None]: except OSError as exc: raise TransportError(f"{what}: {exc}") from exc + +def _is_ip_literal(host: str) -> bool: + try: + ipaddress.ip_address(host) + return True + except ValueError: + return False + + +def resolve_host(host: str, port: int) -> List[str]: + """The addresses of ``host``, IPv4 first: an ``AF_INET`` lookup, and an ``AF_UNSPEC`` one only + when that has no answer. A default lookup of a ``.local`` name waits about 5 s on macOS for an + AAAA answer an IPv4-only pod never sends; the ``AF_INET`` one takes milliseconds.""" + try: + infos = socket.getaddrinfo(host, port, socket.AF_INET, socket.SOCK_STREAM) + except socket.gaierror: + infos = [] + if not infos: + infos = socket.getaddrinfo(host, port, socket.AF_UNSPEC, socket.SOCK_STREAM) + out: List[str] = [] + for info in infos: + ip = str(info[4][0]) + if ip not in out: + out.append(ip) + if not out: + raise socket.gaierror(f"{host}: no address") + return out + + class _SocketRawLink: """Adapts a connected socket to :class:`RawLink` for the flash bridge.""" @@ -119,6 +154,8 @@ def __init__(self, addr: str, *, timeout: float = 30.0, self.dial_timeout = dial_timeout self.tls = _tls.tls_mode(tls) self.tls_ca = tls_ca if tls_ca is not None else (os.environ.get("BENCHPOD_TLS_CA") or None) + #: Host name -> its resolved addresses, reused until a connect to them fails. + self._resolved: Dict[str, List[str]] = {} # -- connection helpers ------------------------------------------------- @@ -161,12 +198,14 @@ def _dial(self, timeout: Optional[float] = None, kind: Optional[str] = None) -> def _connect(self, addr: "tuple[str, int]", budget: float, io_timeout: Optional[float], *, retry: bool = True, attempt_timeout: float = _DIAL_ATTEMPT_TIMEOUT) -> socket.socket: - """A TCP connection to ``addr``, re-probing within ``budget`` seconds.""" + """A TCP connection to ``addr``, re-probing within ``budget`` seconds. A host name is + resolved once (:meth:`_addresses`) and resolved again only after a failed connect.""" deadline = time.monotonic() + budget last: Optional[Exception] = None + host, port = addr while True: try: - sock = socket.create_connection(addr, timeout=attempt_timeout) + sock = self._connect_resolved(host, port, attempt_timeout) sock.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) sock.settimeout(io_timeout) return sock @@ -181,6 +220,34 @@ def _connect(self, addr: "tuple[str, int]", budget: float, io_timeout: Optional[ "(TLS on 8443), or over USB") raise TransportError(f"could not connect to {addr[0]}:{addr[1]}: {last}{hint}") from last + def _addresses(self, host: str) -> List[str]: + """The addresses to connect to for ``host``: the literal itself, else the cached + resolution, else a new one (IPv4 first, :func:`resolve_host`).""" + if _is_ip_literal(host): + return [host] + ips = self._resolved.get(host) + if ips is None: + ips = resolve_host(host, 0) + self._resolved[host] = ips + return ips + + def _connect_resolved(self, host: str, port: int, attempt_timeout: float) -> socket.socket: + """One connect attempt to each address of ``host`` in turn. When none answers the cached + resolution is dropped, so the next attempt resolves the name again (a new DHCP lease).""" + last: Optional[OSError] = None + try: + for ip in self._addresses(host): + try: + return socket.create_connection((ip, port), timeout=attempt_timeout) + except OSError as exc: + last = exc + except OSError: # the lookup itself failed + self._resolved.pop(host, None) + raise + self._resolved.pop(host, None) + assert last is not None + raise last + @staticmethod def _recv_line(sock: socket.socket, buf: bytearray) -> bytes: """Read one newline-terminated line, buffering any overshoot in ``buf``.""" diff --git a/packages/embeddedci/tests/test_tcp_resolve.py b/packages/embeddedci/tests/test_tcp_resolve.py new file mode 100644 index 0000000..cca427c --- /dev/null +++ b/packages/embeddedci/tests/test_tcp_resolve.py @@ -0,0 +1,199 @@ +"""TcpTransport resolves a host name once (IPv4 first) and again only after a failed connect; +TLS keeps the name as given. Plus a bare pod name (``benchpod-a1b2c3``) in parse_connection.""" + +import socket + +import pytest + +from embeddedci.benchpod.connection import parse_connection +from embeddedci.benchpod.discovery import DiscoveredPod, names_pod +from embeddedci.benchpod.errors import TransportError +from embeddedci.benchpod.transport import tcp as tcp_mod +from embeddedci.benchpod.transport.tcp import TcpTransport, resolve_host + +NAME = "benchpod-c2f662.local" +#: What the lookups cost on macOS against an IPv4-only pod (measured): a default (AF_UNSPEC) +#: lookup of a .local name waits for an AAAA answer that never comes. +COST = {socket.AF_UNSPEC: 5.0, socket.AF_INET: 0.04} + + +class _FakeSock: + """A connected socket that answers every command with ``pong``.""" + + def __init__(self, addr): + self.addr = addr + self._reply = b'{"status":"ok","data":"pong"}\n' + + def setsockopt(self, *a): + pass + + def settimeout(self, t): + pass + + def gettimeout(self): + return None + + def sendall(self, data): + pass + + def recv(self, n): + out, self._reply = self._reply, b"" + return out + + def close(self): + pass + + +class _Net: + """A patched resolver and connect: records each lookup (and its simulated cost) and each + connect; ``answers`` are the IPv4 answers of successive lookups, ``down`` the addresses that + refuse a connect.""" + + def __init__(self, monkeypatch, answers=(("192.168.1.164",),), v6=(), down=()): + self.answers = list(answers) + self.v6 = list(v6) + self.down = set(down) + self.lookups = [] + self.connects = [] + self.seconds = 0.0 + monkeypatch.setattr(socket, "getaddrinfo", self.getaddrinfo) + monkeypatch.setattr(socket, "create_connection", self.create_connection) + + def getaddrinfo(self, host, port, family=0, type=0, *a, **kw): + self.lookups.append((host, family)) + self.seconds += COST.get(family, 0.0) + v4 = self.answers[min(len(self.lookups) - 1, len(self.answers) - 1)] if self.answers else () + infos = [(socket.AF_INET, socket.SOCK_STREAM, 6, "", (ip, port)) for ip in v4] + if family == socket.AF_UNSPEC: + infos += [(socket.AF_INET6, socket.SOCK_STREAM, 6, "", (ip, port, 0, 0)) for ip in self.v6] + if not infos: + raise socket.gaierror(socket.EAI_NONAME, "nodename nor servname provided") + return infos + + def create_connection(self, addr, timeout=None): + self.connects.append(addr) + if addr[0] in self.down: + raise ConnectionRefusedError("refused") + return _FakeSock(addr) + + +def test_a_name_is_resolved_once_for_many_commands(monkeypatch): + net = _Net(monkeypatch) + t = TcpTransport(f"{NAME}:8080") + for _ in range(10): + assert t.ping() == "pong" + assert net.lookups == [(NAME, socket.AF_INET)] + assert net.connects == [("192.168.1.164", 8080)] * 10 + # 10 commands cost one 0.04 s IPv4 lookup; before, each did a 5 s AF_UNSPEC one (50 s). + assert net.seconds == pytest.approx(0.04) + + +def test_ipv4_first_and_unspec_only_without_an_ipv4_answer(monkeypatch): + net = _Net(monkeypatch, answers=(), v6=("fd00::5",)) + assert resolve_host("pod.example", 8443) == ["fd00::5"] + assert net.lookups == [("pod.example", socket.AF_INET), ("pod.example", socket.AF_UNSPEC)] + + net = _Net(monkeypatch, answers=(("192.168.1.164",),), v6=("fd00::5",)) + assert resolve_host("pod.example", 8443) == ["192.168.1.164"] + assert net.lookups == [("pod.example", socket.AF_INET)] + + +def test_a_failed_connect_resolves_again(monkeypatch): + """The pod got a new DHCP lease: the cached address refuses, the next attempt resolves the + name again and connects to the new one, which is then reused.""" + net = _Net(monkeypatch, answers=(("192.168.1.164",), ("192.168.1.165",))) + t = TcpTransport(f"{NAME}:8080") + assert t.ping() == "pong" + net.down.add("192.168.1.164") + assert t.ping() == "pong" + assert t.ping() == "pong" + assert [h for h, _ in net.lookups] == [NAME, NAME] + assert net.connects == [("192.168.1.164", 8080), ("192.168.1.164", 8080), + ("192.168.1.165", 8080), ("192.168.1.165", 8080)] + + +def test_an_unreachable_name_still_names_the_host(monkeypatch): + net = _Net(monkeypatch, down=("192.168.1.164",)) + with pytest.raises(TransportError, match=f"could not connect to {NAME}:8080"): + TcpTransport(f"{NAME}:8080", dial_timeout=0.05)._dial() + assert len(net.lookups) >= 2 # every retry resolves again after the refused connect + + +def test_an_ip_literal_is_not_looked_up(monkeypatch): + net = _Net(monkeypatch) + t = TcpTransport("192.168.1.164:8080") + t.ping() + t.ping() + assert net.lookups == [] + assert net.connects == [("192.168.1.164", 8080)] * 2 + + +def test_tls_keeps_the_name_for_the_pin_and_sni(monkeypatch): + """The connect goes to the resolved address; TLS (the pin key, SNI) gets the name as given.""" + net = _Net(monkeypatch) + wrapped = [] + + def fake_wrap(sock, host, port, ca=None, **kw): + wrapped.append((sock.addr, host, port)) + return sock + + monkeypatch.setattr(tcp_mod._tls, "wrap", fake_wrap) + t = TcpTransport(f"{NAME}:8443") + for _ in range(3): + assert t.ping() == "pong" + assert wrapped == [(("192.168.1.164", 8443), NAME, 8443)] * 3 + assert len(net.lookups) == 1 + + +# -- a bare pod name ------------------------------------------------------------------------------ + + +def _pod(addresses=("192.168.1.164",), api=2): + return DiscoveredPod(name="BenchPod c2f662", hostname="benchpod-c2f662.local", + addresses=list(addresses), port=8080, tls_port=8443, api=api) + + +@pytest.mark.parametrize("raw", ["benchpod-c2f662", "c2f662", "BenchPod-C2F662"]) +def test_a_pod_name_is_found_over_mdns(raw, monkeypatch): + asked = [] + monkeypatch.setattr("embeddedci.benchpod.discovery.find_pod", + lambda short, timeout=3.0: asked.append(short) or _pod()) + spec = parse_connection(raw) + assert asked == ["c2f662"] + assert spec.kind == "tcp" and spec.addr == "192.168.1.164:8443" + + +def test_a_pod_name_not_on_the_lan_is_looked_for_on_usb(monkeypatch): + monkeypatch.setattr("embeddedci.benchpod.discovery.find_pod", lambda short, timeout=3.0: None) + spec = parse_connection("benchpod-c2f662") + assert spec.kind == "serial" and spec.device == "" and spec.pod == "c2f662" + + +def test_a_pod_name_without_zeroconf_is_its_local_host_name(monkeypatch): + def no_zeroconf(short, timeout=3.0): + raise RuntimeError("mDNS discovery needs the 'zeroconf' package") + + monkeypatch.setattr("embeddedci.benchpod.discovery.find_pod", no_zeroconf) + assert parse_connection("benchpod-c2f662").addr == "benchpod-c2f662.local:8443" + + +def test_a_pod_name_on_firmware_3_is_refused(monkeypatch): + from embeddedci.benchpod.errors import FirmwareTooOldError + + monkeypatch.setattr("embeddedci.benchpod.discovery.find_pod", lambda short, timeout=3.0: _pod(api=0)) + with pytest.raises(FirmwareTooOldError): + parse_connection("benchpod-c2f662") + + +@pytest.mark.parametrize("raw", ["benchpod-c2f662.local", "benchpod-c2f662x", "my-pod", "c2f6621"]) +def test_other_names_stay_host_names(raw, monkeypatch): + monkeypatch.setattr("embeddedci.benchpod.discovery.find_pod", + lambda *a, **k: pytest.fail("not a pod name")) + assert parse_connection(raw).addr == f"{raw}:8443" + + +def test_names_pod_matches_instance_or_host_name(): + assert names_pod(_pod(), "c2f662") + assert names_pod(DiscoveredPod(name="x", hostname="benchpod-c2f662.local"), "c2f662") + assert not names_pod(_pod(), "baea06") +