Debian Codegraph @

tests/test_util.py

raw symbols SCIP
1 import os.path
2 import re
3 import subprocess
4 import socket
5 import atexit
6 import warnings
7
8 from shutil import which
9
10 import attr
11 import pytest
12 import logging
13
14 from labgrid.util import diff_dict, flat_dict, filter_dict
15 from labgrid.util.helper import get_free_port
16 from labgrid.util.ssh import ForwardError, SSHConnection, sshmanager
17 from labgrid.util.proxy import proxymanager
18 from labgrid.util.managedfile import ManagedFile, ManagedFileError
19 from labgrid.driver.exception import ExecutionError
20 from labgrid.resource.serialport import NetworkSerialPort
21 from labgrid.resource.common import Resource, NetworkResource
22 from labgrid.util import diff_dict, flat_dict, filter_dict, find_dict
23
24 @pytest.fixture
25 def connection_localhost():
26 con = SSHConnection("localhost")
27 con.connect()
28 yield con
29 con.disconnect()
30
31 @pytest.fixture
32 def connection_localhost_no_cleanup():
33 con = SSHConnection("localhost")
34 con.connect()
35 return con
36
37 @pytest.fixture
38 def sshmanager_fix():
39 yield sshmanager
40 sshmanager.close_all()
41
42 def test_diff_dict():
43 dict_a = {"a": 1,
44 "b": 2}
45 dict_b = {"a": 1,
46 "b": 3}
47 gen = diff_dict(dict_a, dict_b)
48 for res in gen:
49 assert res[0] == 'b'
50 assert res[1] == 2
51 assert res[2] == 3
52
53 def test_flat_dict():
54 dict_a = {"a":
55 {"b": 3},
56 "b": 2}
57 res = flat_dict(dict_a)
58 assert res == {"a.b": 3, "b": 2}
59
60 def test_filter_dict():
61 @attr.s
62 class A:
63 foo = attr.ib()
64
65 d_orig = {'foo': 1, 'bar': 2, 'baz': 3}
66
67 with warnings.catch_warnings():
68 warnings.simplefilter("error")
69 d_filtered = filter_dict(d_orig, A)
70 assert d_filtered is not d_orig
71 assert d_filtered == {'foo': 1}
72
73 with pytest.warns(UserWarning) as record:
74 d_filtered = filter_dict(d_orig, A, warn=True)
75 assert len(record) == 2
76 assert str(record[0].message) == "unsupported attribute 'bar' with value '2' for class 'A'"
77 assert str(record[1].message) == "unsupported attribute 'baz' with value '3' for class 'A'"
78 assert d_filtered is not d_orig
79 assert d_filtered == {'foo': 1}
80
81 def test_sshmanager_get():
82 assert sshmanager != None
83
84 def test_sshconnection_get():
85 from labgrid.util.ssh import SSHConnection
86 SSHConnection("localhost")
87
88 @pytest.mark.skipif(not which("ssh"), reason="ssh not available")
89 def test_sshconnection_inactive_raise():
90 from labgrid.util.ssh import SSHConnection
91 con = SSHConnection("localhost")
92 with pytest.raises(ExecutionError):
93 con.run_check("echo Hallo")
94
95 @pytest.mark.localsshmanager
96 def test_sshconnection_connect(connection_localhost):
97 assert connection_localhost.isconnected()
98 assert os.path.exists(connection_localhost._socket)
99
100 @pytest.mark.localsshmanager
101 def test_sshconnection_run(connection_localhost):
102 stdout, stderr, exitcode = connection_localhost.run("echo stderr >&2; echo stdout1; echo stdout2")
103 assert exitcode == 0
104 assert stderr == ["stderr"]
105 assert stdout == ["stdout1", "stdout2"]
106
107 @pytest.mark.localsshmanager
108 def test_sshconnection_run_log(connection_localhost, caplog):
109 caplog.set_level(logging.INFO)
110 stdout, stderr, exitcode = connection_localhost.run("echo stderr >&2; echo stdout1; echo stdout2",
111 stdout_loglevel=logging.INFO, stderr_loglevel=logging.WARNING)
112 assert exitcode == 0
113 assert stderr == ["stderr"]
114 assert stdout == ["stdout1", "stdout2"]
115 assert sorted([(rec[1], rec[2]) for rec in caplog.record_tuples]) == [
116 (logging.INFO, 'stdout1'),
117 (logging.INFO, 'stdout2'),
118 (logging.WARNING, 'stderr'),
119 ]
120
121 @pytest.mark.localsshmanager
122 def test_sshconnection_run_merged_stderr(connection_localhost):
123 stdout, stderr, exitcode = connection_localhost.run(
124 "echo stderr >&2; echo stdout", stderr_merge=True)
125 assert exitcode == 0
126 assert sorted(stdout) == ["stderr", "stdout"]
127 assert stderr == []
128
129 @pytest.mark.localsshmanager
130 def test_sshconnection_run_fail(connection_localhost):
131 stdout, stderr, exitcode = connection_localhost.run("false")
132 assert exitcode != 0
133
134
135 @pytest.mark.localsshmanager
136 def test_sshconnection_port_forward_add_remove(connection_localhost):
137 port = get_free_port()
138 test_string = "Hello World"
139
140 local_port = connection_localhost.add_port_forward('localhost', port)
141 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
142 server_socket.bind(("127.0.0.1", port))
143 server_socket.listen(1)
144 send_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
145 send_socket.connect(("127.0.0.1", local_port))
146 client_socket, address = server_socket.accept()
147 send_socket.send(test_string.encode('utf-8'))
148
149 assert client_socket.recv(16).decode("utf-8") == test_string
150 connection_localhost.remove_port_forward('localhost', port)
151
152 @pytest.mark.localsshmanager
153 def test_sshconnection_port_forward_remove_raise(connection_localhost):
154 port = get_free_port()
155
156 with pytest.raises(ForwardError):
157 connection_localhost.remove_port_forward('localhost', port)
158
159 @pytest.mark.localsshmanager
160 def test_sshconnection_port_forward_add_duplicate(connection_localhost):
161 port = get_free_port()
162
163 first_port = connection_localhost.add_port_forward('localhost', port)
164 second_port = connection_localhost.add_port_forward('localhost', port)
165 assert first_port == second_port
166
167
168 @pytest.mark.localsshmanager
169 def test_sshconnection_port_remote_forward_add_remove(connection_localhost):
170 rport = get_free_port()
171 lport = get_free_port()
172 test_string = "Hello World"
173
174 connection_localhost.add_remote_port_forward(rport, lport)
175 server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
176 server_socket.bind(("127.0.0.1", lport))
177 server_socket.listen(1)
178 send_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
179 send_socket.connect(("127.0.0.1", rport))
180 client_socket, address = server_socket.accept()
181 send_socket.send(test_string.encode('utf-8'))
182
183 assert client_socket.recv(16).decode("utf-8") == test_string
184 connection_localhost.remove_remote_port_forward(rport, lport)
185 assert connection_localhost._r_forwards == set()
186
187
188 @pytest.mark.localsshmanager
189 def test_sshconnection_put_file(connection_localhost, tmpdir):
190 p = tmpdir.join("config.yaml")
191 p.write(
192 """Teststring"""
193 )
194 connection_localhost.put_file(p, '/tmp/test')
195
196 assert os.path.isfile('/tmp/test')
197 assert open('/tmp/test', 'r').readlines() == [ "Teststring" ]
198
199 @pytest.mark.localsshmanager
200 def test_sshconnection_get_file(connection_localhost, tmpdir):
201
202 p = tmpdir.join("test")
203 connection_localhost.get_file('/tmp/test', p)
204
205 @pytest.mark.localsshmanager
206 def test_sshconnection_cleanup(connection_localhost_no_cleanup):
207
208 connection_localhost_no_cleanup.cleanup()
209
210 # do not call cleanup() again on termination
211 atexit.unregister(connection_localhost_no_cleanup.cleanup)
212
213 @pytest.mark.localsshmanager
214 def test_sshmanager_open(sshmanager_fix):
215 con = sshmanager_fix.open("localhost")
216
217 assert isinstance(con, SSHConnection)
218
219 @pytest.mark.localsshmanager
220 def test_sshmanager_add_forward(sshmanager_fix):
221 port = sshmanager_fix.request_forward("localhost", 'localhost', 3000)
222
223 assert port < 65536
224
225 @pytest.mark.localsshmanager
226 def test_sshmanager_remove_forward(sshmanager_fix):
227 port = sshmanager_fix.request_forward("localhost", 'localhost', 3000)
228 sshmanager_fix.remove_forward('localhost', 'localhost', 3000)
229
230 assert 3000 not in sshmanager_fix.get('localhost')._l_forwards
231
232 @pytest.mark.localsshmanager
233 def test_sshmanager_close(sshmanager_fix):
234 con = sshmanager_fix.open("localhost")
235
236 assert isinstance(con, SSHConnection)
237 sshmanager_fix.close("localhost")
238
239 @pytest.mark.localsshmanager
240 def test_sshmanager_remove_raise(sshmanager_fix):
241 con = sshmanager_fix.open("localhost")
242 con.connect()
243 with pytest.raises(ExecutionError):
244 sshmanager_fix.remove_connection(con)
245
246 @pytest.mark.skipif(not which("ssh"), reason="ssh not available")
247 def test_sshmanager_add_duplicate(sshmanager_fix):
248 host = 'localhost'
249 con = SSHConnection(host)
250 sshmanager_fix.add_connection(con)
251 con_there = sshmanager_fix._connections[host]
252 sshmanager_fix.add_connection(con)
253 con_now = sshmanager_fix._connections[host]
254
255 assert con_now == con_there
256
257 @pytest.mark.skipif(not which("ssh"), reason="ssh not available")
258 def test_sshmanager_add_new(sshmanager_fix):
259 host = 'other_host'
260 con = SSHConnection(host)
261 sshmanager_fix.add_connection(con)
262 con_now = sshmanager_fix._connections[host]
263
264 assert con_now == con
265
266 @pytest.mark.skipif(not which("ssh"), reason="ssh not available")
267 def test_sshmanager_invalid_host_raise():
268 con = SSHConnection("nosuchhost.notavailable")
269 with pytest.raises(ExecutionError):
270 con.connect()
271
272 def test_proxymanager_no_proxy(target):
273 host = 'localhost'
274 port = 5000
275 nr = NetworkSerialPort(target, host=host, port=port, name=None)
276 nr.proxy = ''
277 nr.proxy_required = False
278
279 assert (host, port) == proxymanager.get_host_and_port(nr)
280
281 @pytest.mark.localsshmanager
282 def test_proxymanager_remote_forced_proxy(target):
283 sshmanager.close_all()
284 host = 'localhost'
285 port = 5000
286 nr = NetworkSerialPort(target, host=host, port=port, name=None)
287 extras = { 'proxy': 'localhost', 'proxy_required': True }
288 nr.extra = extras
289 nhost, nport = proxymanager.get_host_and_port(nr)
290
291 assert (host, port) != (nhost, nport)
292 sshmanager.close_all()
293
294 @pytest.mark.localsshmanager
295 def test_proxymanager_local_forced_proxy(target):
296 host = 'localhost'
297 port = 5000
298 nr = NetworkSerialPort(target, host=host, port=port, name=None)
299 extras = { 'proxy': 'localhost', 'proxy_required': True }
300 nr.extra = extras
301 nhost, nport = proxymanager.get_host_and_port(nr)
302
303 assert (host, port) != (nhost, nport)
304
305 @pytest.mark.localsshmanager
306 def test_remote_managedfile(target, tmpdir):
307 import hashlib
308 import getpass
309
310 res = NetworkResource(target, "test", "localhost")
311 t = tmpdir.join("test")
312 t.write(
313 """
314 Test
315 """
316 )
317 hash = hashlib.sha256(t.read().encode("utf-8")).hexdigest()
318 mf = ManagedFile(t, res, detect_nfs=False)
319 mf.sync_to_resource()
320
321 assert os.path.isfile(f"/var/cache/labgrid/{getpass.getuser()}/{hash}/test")
322 assert hash == mf.get_hash()
323 assert f"/var/cache/labgrid/{getpass.getuser()}/{hash}/test" == mf.get_remote_path()
324
325 @pytest.mark.localsshmanager
326 def test_remote_managedfile_on_nfs(target, tmpdir):
327 res = NetworkResource(target, "test", "localhost")
328 t = tmpdir.join("test")
329 t.write(
330 """
331 Test
332 """
333 )
334 mf = ManagedFile(t, res, detect_nfs=True)
335 mf.sync_to_resource()
336
337 assert str(t) == mf.get_remote_path()
338
339 def test_local_managedfile(target, tmpdir):
340 import hashlib
341
342 res = Resource(target, "test")
343 t = tmpdir.join("test")
344 t.write(
345 """
346 Test
347 """
348 )
349 hash = hashlib.sha256(t.read().encode("utf-8")).hexdigest()
350 mf = ManagedFile(t, res, detect_nfs=False)
351 mf.sync_to_resource()
352
353 assert hash == mf.get_hash()
354 assert str(t) == mf.get_remote_path()
355
356 def test_network_managedfile_no_sync(target, tmpdir):
357 res = NetworkResource(target, "test", "localhost")
358 t = tmpdir.join("test")
359 t.write(
360 """
361 Test
362 """
363 )
364 mf = ManagedFile(t, res, detect_nfs=False)
365
366 expected = re.escape("sync_to_resource() needs to be called before the remote-path can be retrieved")
367 with pytest.raises(ManagedFileError, match=expected) as e:
368 mf.get_remote_path()
369
370 def test_local_managedfile_symlink(target, tmpdir):
371 res = Resource(target, "test")
372 t = tmpdir.join("test")
373 t.write(
374 """
375 Test
376 """
377 )
378 mf = ManagedFile(t, res, detect_nfs=False)
379 mf.sync_to_resource(symlink=tmpdir.join("link"))
380
381 assert str(t) == mf.get_remote_path()
382 assert os.path.islink(tmpdir.join("link"))
383
384 @pytest.mark.localsshmanager
385 def test_remote_managedfile_symlink(target, tmpdir):
386 res = NetworkResource(target, "test", "localhost")
387 t = tmpdir.join("test")
388 t.write(
389 """
390 Test
391 """
392 )
393 mf = ManagedFile(t, res, detect_nfs=False)
394 mf.sync_to_resource(symlink=tmpdir.join("link"))
395
396 assert os.path.islink(tmpdir.join("link"))
397
398 def test_find_dict():
399 dict_a = {"a": {"a.a": {"a.a.a": "a.a.a_val"}}, "b": "b_val"}
400 assert find_dict(dict_a, "b") == "b_val"
401 assert find_dict(dict_a, "a") == {"a.a": {"a.a.a": "a.a.a_val"}}
402 assert find_dict(dict_a, "a.a") == {"a.a.a": "a.a.a_val"}
403 assert find_dict(dict_a, "a.a.a") == "a.a.a_val"
404 assert find_dict(dict_a, "x") == None