-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_client.py
More file actions
293 lines (248 loc) · 10.4 KB
/
Copy pathtest_client.py
File metadata and controls
293 lines (248 loc) · 10.4 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
"""Tests for client.py — mocked subprocess + httpx."""
from __future__ import annotations
import asyncio
import json
from unittest import mock
import pytest
import httpx
from client import TailscaleCLI, TailscaleAPI, CLIError
SAMPLE_STATUS = {
"Version": "1.62.0",
"BackendState": "Running",
"TUN": True,
"TailscaleIPs": ["100.64.0.1", "fd7a:115c:a1e0::1"],
"Self": {
"ID": "self-123",
"HostName": "truffle",
"DNSName": "truffle.tail1234.ts.net.",
"TailscaleIPs": ["100.64.0.1", "fd7a:115c:a1e0::1"],
"OS": "linux",
"Online": True,
"PublicKey": "key1",
"UserID": 1,
},
"Peer": {
"key2": {
"ID": "peer-456",
"HostName": "laptop",
"DNSName": "laptop.tail1234.ts.net.",
"TailscaleIPs": ["100.64.0.2"],
"OS": "macOS",
"Online": True,
"PublicKey": "key2",
"UserID": 2,
"LastSeen": "2025-01-01T00:00:00Z",
"ExitNode": False,
"ExitNodeOption": True,
},
},
"MagicDNSSuffix": "tail1234.ts.net",
}
def _make_proc(stdout: str = "", stderr: str = "", returncode: int = 0):
"""Create a mock process for create_subprocess_exec."""
proc = mock.AsyncMock()
proc.communicate.return_value = (
stdout.encode() if stdout else b"",
stderr.encode() if stderr else b"",
)
proc.returncode = returncode
proc.kill = mock.Mock()
return proc
# --- TailscaleCLI tests ---
class TestTailscaleCLI:
@pytest.fixture
def cli(self):
return TailscaleCLI()
@pytest.mark.asyncio
async def test_status(self, cli):
proc = _make_proc(stdout=json.dumps(SAMPLE_STATUS))
with mock.patch("asyncio.create_subprocess_exec", return_value=proc):
result = await cli.status()
assert result["BackendState"] == "Running"
assert result["Self"]["HostName"] == "truffle"
@pytest.mark.asyncio
async def test_status_failure(self, cli):
proc = _make_proc(stderr="tailscale not running", returncode=1)
with mock.patch("asyncio.create_subprocess_exec", return_value=proc):
with pytest.raises(CLIError, match="tailscale not running"):
await cli.status()
@pytest.mark.asyncio
async def test_ping(self, cli):
proc = _make_proc(stdout="pong from laptop (100.64.0.2) via DERP(nyc)")
with mock.patch("asyncio.create_subprocess_exec", return_value=proc):
result = await cli.ping("laptop", count=1)
assert "pong" in result
@pytest.mark.asyncio
async def test_up(self, cli):
proc = _make_proc(stdout="Success.")
with mock.patch("asyncio.create_subprocess_exec", return_value=proc) as mock_exec:
result = await cli.up("tskey-auth-abc", hostname="mydevice")
assert result == "Success."
call_args = mock_exec.call_args[0]
assert "tailscale" in call_args
assert "up" in call_args
assert "--authkey=tskey-auth-abc" in call_args
assert "--hostname=mydevice" in call_args
@pytest.mark.asyncio
async def test_down(self, cli):
proc = _make_proc(stdout="")
with mock.patch("asyncio.create_subprocess_exec", return_value=proc):
result = await cli.down()
assert result == ""
@pytest.mark.asyncio
async def test_set_exit_node(self, cli):
proc = _make_proc(stdout="")
with mock.patch("asyncio.create_subprocess_exec", return_value=proc) as mock_exec:
await cli.set_exit_node("laptop")
call_args = mock_exec.call_args[0]
assert "--exit-node=laptop" in call_args
@pytest.mark.asyncio
async def test_clear_exit_node(self, cli):
proc = _make_proc(stdout="")
with mock.patch("asyncio.create_subprocess_exec", return_value=proc) as mock_exec:
await cli.clear_exit_node()
call_args = mock_exec.call_args[0]
assert "--exit-node=" in call_args
@pytest.mark.asyncio
async def test_ip(self, cli):
proc = _make_proc(stdout="100.64.0.1\nfd7a:115c:a1e0::1\n")
with mock.patch("asyncio.create_subprocess_exec", return_value=proc):
result = await cli.ip()
assert result == ["100.64.0.1", "fd7a:115c:a1e0::1"]
@pytest.mark.asyncio
async def test_version(self, cli):
proc = _make_proc(stdout="1.62.0")
with mock.patch("asyncio.create_subprocess_exec", return_value=proc):
result = await cli.version()
assert result == "1.62.0"
@pytest.mark.asyncio
async def test_self_node(self, cli):
proc = _make_proc(stdout=json.dumps(SAMPLE_STATUS))
with mock.patch("asyncio.create_subprocess_exec", return_value=proc):
node = await cli.self_node()
assert node["HostName"] == "truffle"
@pytest.mark.asyncio
async def test_peers(self, cli):
proc = _make_proc(stdout=json.dumps(SAMPLE_STATUS))
with mock.patch("asyncio.create_subprocess_exec", return_value=proc):
peers = await cli.peers()
assert len(peers) == 1
assert peers[0]["HostName"] == "laptop"
@pytest.mark.asyncio
async def test_is_connected_true(self, cli):
proc = _make_proc(stdout=json.dumps(SAMPLE_STATUS))
with mock.patch("asyncio.create_subprocess_exec", return_value=proc):
assert await cli.is_connected() is True
@pytest.mark.asyncio
async def test_is_connected_false_on_error(self, cli):
proc = _make_proc(stderr="not running", returncode=1)
with mock.patch("asyncio.create_subprocess_exec", return_value=proc):
assert await cli.is_connected() is False
@pytest.mark.asyncio
async def test_file_send(self, cli):
proc = _make_proc(stdout="")
with mock.patch("asyncio.create_subprocess_exec", return_value=proc) as mock_exec:
result = await cli.file_send("/tmp/test.txt", "laptop")
call_args = mock_exec.call_args[0]
assert "file" in call_args
assert "cp" in call_args
assert "/tmp/test.txt" in call_args
assert "laptop:" in call_args
@pytest.mark.asyncio
async def test_file_get(self, cli):
proc = _make_proc(stdout="received 1 file")
with mock.patch("asyncio.create_subprocess_exec", return_value=proc) as mock_exec:
result = await cli.file_get("/tmp/received")
call_args = mock_exec.call_args[0]
assert "file" in call_args
assert "get" in call_args
assert "/tmp/received" in call_args
assert "received 1 file" in result
@pytest.mark.asyncio
async def test_file_get_with_wait(self, cli):
proc = _make_proc(stdout="received 1 file")
with mock.patch("asyncio.create_subprocess_exec", return_value=proc) as mock_exec:
result = await cli.file_get("/tmp/received", wait=True)
call_args = mock_exec.call_args[0]
assert "--wait" in call_args
# --- TailscaleAPI tests ---
class TestTailscaleAPI:
@pytest.fixture
def api(self):
return TailscaleAPI(
api_key="tskey-api-test",
tailnet="example.com",
base_url="https://api.tailscale.com/api/v2",
)
@pytest.mark.asyncio
async def test_list_devices(self, api):
devices = [
{"id": "dev1", "name": "laptop", "hostname": "laptop", "os": "macOS"},
]
mock_response = mock.Mock()
mock_response.status_code = 200
mock_response.json.return_value = {"devices": devices}
mock_response.raise_for_status = mock.Mock()
with mock.patch.object(api._http, "request", return_value=mock_response):
result = await api.list_devices()
assert len(result) == 1
assert result[0]["hostname"] == "laptop"
@pytest.mark.asyncio
async def test_get_device(self, api):
device = {"id": "dev1", "name": "laptop"}
mock_response = mock.Mock()
mock_response.status_code = 200
mock_response.json.return_value = device
mock_response.raise_for_status = mock.Mock()
with mock.patch.object(api._http, "request", return_value=mock_response):
result = await api.get_device("dev1")
assert result["id"] == "dev1"
@pytest.mark.asyncio
async def test_authorize_device(self, api):
mock_response = mock.Mock()
mock_response.status_code = 200
mock_response.json.return_value = {"authorized": True}
mock_response.raise_for_status = mock.Mock()
with mock.patch.object(api._http, "request", return_value=mock_response):
result = await api.authorize_device("dev1")
assert result["authorized"] is True
@pytest.mark.asyncio
async def test_delete_device(self, api):
mock_response = mock.Mock()
mock_response.status_code = 204
mock_response.raise_for_status = mock.Mock()
with mock.patch.object(api._http, "request", return_value=mock_response):
result = await api.delete_device("dev1")
assert result is True
@pytest.mark.asyncio
async def test_get_device_routes(self, api):
mock_response = mock.Mock()
mock_response.status_code = 200
mock_response.json.return_value = {
"advertisedRoutes": ["10.0.0.0/24"],
"enabledRoutes": ["10.0.0.0/24"],
}
mock_response.raise_for_status = mock.Mock()
with mock.patch.object(api._http, "request", return_value=mock_response):
result = await api.get_device_routes("dev1")
assert "advertisedRoutes" in result
@pytest.mark.asyncio
async def test_set_device_routes(self, api):
mock_response = mock.Mock()
mock_response.status_code = 200
mock_response.json.return_value = {"routes": ["10.0.0.0/24"]}
mock_response.raise_for_status = mock.Mock()
with mock.patch.object(api._http, "request", return_value=mock_response):
result = await api.set_device_routes("dev1", ["10.0.0.0/24"])
assert "routes" in result
@pytest.mark.asyncio
async def test_no_api_key_raises(self):
api = TailscaleAPI(api_key="", tailnet="example.com")
assert api.available is False
with pytest.raises(ValueError, match="TAILSCALE_API_KEY is required"):
await api.list_devices()
@pytest.mark.asyncio
async def test_close(self, api):
with mock.patch.object(api._http, "aclose") as mock_close:
await api.close()
mock_close.assert_called_once()