import io import pytest import responses from client.config import load_config from client.pair import pair @responses.activate def test_pair_posts_to_api_pair_and_writes_config(tmp_path, monkeypatch): monkeypatch.setenv("HOME", str(tmp_path)) responses.post( "https://backend.test/api/pair", json={ "device_id": "00000000-0000-0000-0000-000000000001", "device_token": "T0K3N", "backend_ws": "wss://backend.test/device", }, status=200, ) pair(backend="https://backend.test", code="ABC12345", hostname="testhost") cfg = load_config() assert cfg.device_id == "00000000-0000-0000-0000-000000000001" assert cfg.device_token == "T0K3N" assert cfg.backend_ws == "wss://backend.test/device" body = responses.calls[0].request.body assert b"ABC12345" in body assert b"testhost" in body @responses.activate def test_pair_strips_trailing_slash_from_backend(tmp_path, monkeypatch): monkeypatch.setenv("HOME", str(tmp_path)) responses.post( "https://backend.test/api/pair", json={"device_id": "x", "device_token": "y", "backend_ws": "wss://z"}, status=200, ) pair(backend="https://backend.test/", code="ABC12345", hostname="h") assert responses.calls[0].request.url == "https://backend.test/api/pair" @responses.activate def test_pair_raises_on_404(tmp_path, monkeypatch): monkeypatch.setenv("HOME", str(tmp_path)) responses.post( "https://backend.test/api/pair", json={"error": "code invalid or expired"}, status=404, ) with pytest.raises(SystemExit) as exc: pair(backend="https://backend.test", code="WRONGCOD", hostname="h") assert "code invalid or expired" in str(exc.value) def test_prompt_used_when_code_not_provided(tmp_path, monkeypatch): monkeypatch.setenv("HOME", str(tmp_path)) monkeypatch.setattr("sys.stdin", io.StringIO("FROMSTDIN\n")) called_with = {} def fake_post(url, json, timeout): called_with["json"] = json class R: status_code = 200 def json(self_): return { "device_id": "x", "device_token": "y", "backend_ws": "wss://z", } def raise_for_status(self_): pass return R() monkeypatch.setattr("client.pair.requests.post", fake_post) pair(backend="https://backend.test", code=None, hostname="h") assert called_with["json"]["code"] == "FROMSTDIN"