File: test_checks_linux.py

package info (click to toggle)
autosuspend 9.0.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 1,196 kB
  • sloc: python: 5,431; xml: 13; makefile: 10; javascript: 1
file content (616 lines) | stat: -rw-r--r-- 21,013 bytes parent folder | download
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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
import re
import socket
import sys
from collections import namedtuple
from collections.abc import Mapping
from datetime import UTC, datetime
from pathlib import Path
from typing import Any

import psutil
import pytest
import requests
from freezegun import freeze_time
from pytest_httpserver import HTTPServer
from pytest_mock import MockerFixture

from autosuspend.checks import (
    Check,
    ConfigurationError,
    SevereCheckError,
    TemporaryCheckError,
)
from autosuspend.checks.linux import (
    ActiveConnection,
    File,
    Load,
    NetworkBandwidth,
    Ping,
    Processes,
    Users,
)

from . import CheckTest
from tests.utils import config_section

try:
    from psutil._common import sconn, suser
except ImportError:
    from psutil._ntuples import sconn, suser


class TestUsers(CheckTest):
    def create_instance(self, name: str) -> Check:
        return Users(name, re.compile(".*"), re.compile(".*"), re.compile(".*"))

    @staticmethod
    def create_suser(
        name: str, terminal: str, host: str, started: float, pid: int
    ) -> suser:
        return suser(name, terminal, host, started, pid)

    def test_reports_no_activity_without_users(self, mocker: MockerFixture) -> None:
        mocker.patch("psutil.users").return_value = []

        assert (
            Users("users", re.compile(".*"), re.compile(".*"), re.compile(".*")).check()
            is None
        )

    def test_matching_users(self, mocker: MockerFixture) -> None:
        mocker.patch("psutil.users").return_value = [
            self.create_suser("foo", "pts1", "host", 12345, 12345)
        ]

        assert (
            Users("users", re.compile(".*"), re.compile(".*"), re.compile(".*")).check()
            is not None
        )

    def test_detect_no_activity_if_no_matching_user_exists(
        self, mocker: MockerFixture
    ) -> None:
        mocker.patch("psutil.users").return_value = [
            self.create_suser("foo", "pts1", "host", 12345, 12345)
        ]

        assert (
            Users(
                "users", re.compile("narf"), re.compile(".*"), re.compile(".*")
            ).check()
            is None
        )

    class TestCreate:
        def test_it_works_with_a_valid_config(self) -> None:
            check = Users.create(
                "name",
                config_section(
                    {
                        "name": "name.*name",
                        "terminal": "term.*term",
                        "host": "host.*host",
                    }
                ),
            )

            assert check._user_regex == re.compile("name.*name")
            assert check._terminal_regex == re.compile("term.*term")
            assert check._host_regex == re.compile("host.*host")

        def test_raises_with_invalid_expression(self) -> None:
            with pytest.raises(ConfigurationError):
                Users.create(
                    "name",
                    config_section(
                        {
                            "name": "name.*name",
                            "terminal": "term.[[a-9]term",
                            "host": "host.*host",
                        }
                    ),
                )


class TestProcesses(CheckTest):
    def create_instance(self, name: str) -> Check:
        return Processes(name, ["foo"])

    class StubProcess:
        def __init__(self, name: str) -> None:
            self._name = name

        def name(self) -> str:
            return self._name

    class RaisingProcess:
        def name(self) -> str:
            raise psutil.NoSuchProcess(42)

    def test_detects_activity_with_matching_process(
        self, mocker: MockerFixture
    ) -> None:
        mocker.patch("psutil.process_iter").return_value = [
            self.StubProcess("blubb"),
            self.StubProcess("nonmatching"),
        ]

        assert Processes("foo", ["dummy", "blubb", "other"]).check() is not None

    def test_ignores_no_such_process_errors(self, mocker: MockerFixture) -> None:
        mocker.patch("psutil.process_iter").return_value = [self.RaisingProcess()]

        Processes("foo", ["dummy"]).check()

    def test_detect_no_activity_for_non_matching_processes(
        self, mocker: MockerFixture
    ) -> None:
        mocker.patch("psutil.process_iter").return_value = [
            self.StubProcess("asdfasdf"),
            self.StubProcess("nonmatching"),
        ]

        assert Processes("foo", ["dummy", "blubb", "other"]).check() is None

    class TestCreate:
        def test_it_works_with_a_valid_config(self) -> None:
            assert Processes.create(
                "name", config_section({"processes": "foo, bar, narf"})
            )._processes == [
                "foo",
                "bar",
                "narf",
            ]

        def test_raises_if_no_processes_are_configured(self) -> None:
            with pytest.raises(ConfigurationError):
                Processes.create("name", config_section())


snic = namedtuple("snic", ["family", "address", "netmask", "broadcast", "ptp"])


class TestActiveConnection(CheckTest):
    MY_PORT = 22
    MY_ADDRESS = "123.456.123.456"
    MY_ADDRESS_IPV6 = "fe80::5193:518c:5c69:aedb"
    # this might sometimes happen:
    # https://superuser.com/a/99753/227177
    MY_ADDRESS_IPV6_SCOPED = "fe80::5193:518c:5c69:cccc%eth0"

    def create_instance(self, name: str) -> Check:
        return ActiveConnection(name, [10])

    @pytest.mark.parametrize(
        "connection",
        [
            # ipv4
            sconn(
                -1,
                socket.AF_INET,
                socket.SOCK_STREAM,
                (MY_ADDRESS, MY_PORT),
                ("42.42.42.42", 42),
                "ESTABLISHED",
                None,
            ),
            # ipv6
            sconn(
                -1,
                socket.AF_INET6,
                socket.SOCK_STREAM,
                (MY_ADDRESS_IPV6, MY_PORT),
                ("42.42.42.42", 42),
                "ESTABLISHED",
                None,
            ),
            # ipv6 where local address has scope
            sconn(
                -1,
                socket.AF_INET6,
                socket.SOCK_STREAM,
                (MY_ADDRESS_IPV6_SCOPED.split("%")[0], MY_PORT),
                ("42.42.42.42", 42),
                "ESTABLISHED",
                None,
            ),
            # ipv6 with mapping to ipv4
            # https://github.com/languitar/autosuspend/issues/116
            sconn(
                -1,
                socket.AF_INET6,
                socket.SOCK_STREAM,
                (f"::ffff:{MY_ADDRESS}", MY_PORT),
                ("42.42.42.42", 42),
                "ESTABLISHED",
                None,
            ),
        ],
    )
    def test_detect_activity_if_port_is_connected(
        self, mocker: MockerFixture, connection: sconn
    ) -> None:
        mocker.patch("psutil.net_if_addrs").return_value = {
            "dummy": [
                snic(socket.AF_INET, self.MY_ADDRESS, "255.255.255.0", None, None),
                snic(
                    socket.AF_INET6,
                    self.MY_ADDRESS_IPV6,
                    "ffff:ffff:ffff:ffff::",
                    None,
                    None,
                ),
                snic(
                    socket.AF_INET6,
                    self.MY_ADDRESS_IPV6_SCOPED,
                    "ffff:ffff:ffff:ffff::",
                    None,
                    None,
                ),
            ],
        }
        mocker.patch("psutil.net_connections").return_value = [connection]

        assert ActiveConnection("foo", [10, self.MY_PORT, 30]).check() is not None

    @pytest.mark.parametrize(
        "connection",
        [
            # not my port
            sconn(
                -1,
                socket.AF_INET,
                socket.SOCK_STREAM,
                (MY_ADDRESS, 32),
                ("42.42.42.42", 42),
                "ESTABLISHED",
                None,
            ),
            # not my local address
            sconn(
                -1,
                socket.AF_INET,
                socket.SOCK_STREAM,
                ("33.33.33.33", MY_PORT),
                ("42.42.42.42", 42),
                "ESTABLISHED",
                None,
            ),
            # not established
            sconn(
                -1,
                socket.AF_INET,
                socket.SOCK_STREAM,
                (MY_ADDRESS, MY_PORT),
                ("42.42.42.42", 42),
                "NARF",
                None,
            ),
            # I am the client
            sconn(
                -1,
                socket.AF_INET,
                socket.SOCK_STREAM,
                ("42.42.42.42", 42),
                (MY_ADDRESS, MY_PORT),
                "NARF",
                None,
            ),
        ],
    )
    def test_detects_no_activity_if_port_is_not_connected(
        self, mocker: MockerFixture, connection: sconn
    ) -> None:
        mocker.patch("psutil.net_if_addrs").return_value = {
            "dummy": [
                snic(socket.AF_INET, self.MY_ADDRESS, "255.255.255.0", None, None)
            ]
        }
        mocker.patch("psutil.net_connections").return_value = [connection]

        assert ActiveConnection("foo", [10, self.MY_PORT, 30]).check() is None

    class TestCreate:
        def test_it_works_with_a_valid_config(self) -> None:
            assert ActiveConnection.create(
                "name", config_section({"ports": "10,20,30"})
            )._ports == {10, 20, 30}

        def test_raises_if_no_ports_are_configured(self) -> None:
            with pytest.raises(ConfigurationError):
                ActiveConnection.create("name", config_section())

        def test_raises_if_ports_are_not_numeric(self) -> None:
            with pytest.raises(ConfigurationError):
                ActiveConnection.create("name", config_section({"ports": "10,20xx,30"}))


class TestLoad(CheckTest):
    def create_instance(self, name: str) -> Check:
        return Load(name, 0.4)

    def test_detects_no_activity_below_threshold(self, mocker: Any) -> None:
        threshold = 1.34
        mocker.patch("os.getloadavg").return_value = [0, threshold - 0.2, 0]

        assert Load("foo", threshold).check() is None

    def test_detects_activity_above_threshold(self, mocker: MockerFixture) -> None:
        threshold = 1.34
        mocker.patch("os.getloadavg").return_value = [0, threshold + 0.2, 0]

        assert Load("foo", threshold).check() is not None

    class TestCreate:
        def test_it_works_with_a_valid_config(self) -> None:
            assert (
                Load.create("name", config_section({"threshold": "3.2"}))._threshold
                == 3.2
            )

        def test_raises_if_threshold_is_not_numeric(self) -> None:
            with pytest.raises(ConfigurationError):
                Load.create("name", config_section({"threshold": "narf"}))


class TestNetworkBandwidth(CheckTest):
    def create_instance(self, name: str) -> Check:
        return NetworkBandwidth(name, psutil.net_if_addrs().keys(), 0, 0)

    @staticmethod
    @pytest.fixture
    def serve_data_url(httpserver: HTTPServer) -> str:
        httpserver.expect_request("").respond_with_json({"foo": "bar"})
        return httpserver.url_for("")

    def test_detects_non_mocked_activity(self, serve_data_url: str) -> None:
        check = NetworkBandwidth("name", psutil.net_if_addrs().keys(), 0, 0)
        # make some traffic
        requests.get(serve_data_url, timeout=5)
        assert check.check() is not None

    @pytest.fixture
    def _mock_interfaces(self, mocker: MockerFixture) -> None:
        mock = mocker.patch("psutil.net_if_addrs")
        mock.return_value = {"foo": None, "bar": None, "baz": None}

    class TestCreate:
        @pytest.mark.usefixtures("_mock_interfaces")
        def test_it_works_with_a_valid_config(self) -> None:
            check = NetworkBandwidth.create(
                "name",
                config_section(
                    {
                        "interfaces": "foo, baz",
                        "threshold_send": "200",
                        "threshold_receive": "300",
                    }
                ),
            )
            assert set(check._interfaces) == {"foo", "baz"}
            assert check._threshold_send == 200
            assert check._threshold_receive == 300

        @pytest.mark.usefixtures("_mock_interfaces")
        def test_default_values_work(self) -> None:
            check = NetworkBandwidth.create(
                "name", config_section({"interfaces": "foo, baz"})
            )
            assert set(check._interfaces) == {"foo", "baz"}
            assert check._threshold_send == 100
            assert check._threshold_receive == 100

        @pytest.mark.parametrize(
            ("config", "error_match"),
            [
                (
                    {
                        "interfaces": "foo, NOTEXIST",
                        "threshold_send": "200",
                        "threshold_receive": "300",
                    },
                    r"does not exist",
                ),
                (
                    {
                        "threshold_send": "200",
                        "threshold_receive": "300",
                    },
                    r"configuration key: \'interfaces\'",
                ),
                (
                    {
                        "interfaces": "",
                        "threshold_send": "200",
                        "threshold_receive": "300",
                    },
                    r"No interfaces configured",
                ),
                (
                    {
                        "interfaces": "foo, bar",
                        "threshold_send": "xxx",
                    },
                    r"Threshold in wrong format",
                ),
                (
                    {
                        "interfaces": "foo, bar",
                        "threshold_receive": "xxx",
                    },
                    r"Threshold in wrong format",
                ),
            ],
        )
        @pytest.mark.usefixtures("_mock_interfaces")
        def test_raises_with_an_invalid_config(
            self, config: Mapping[str, str], error_match: str
        ) -> None:
            with pytest.raises(ConfigurationError, match=error_match):
                NetworkBandwidth.create("name", config_section(config))

    @pytest.mark.parametrize(
        ("send_threshold", "receive_threshold", "match"),
        [(sys.float_info.max, 0, "receive"), (0, sys.float_info.max, "sending")],
    )
    def test_detects_activity_in_direction(
        self,
        send_threshold: float,
        receive_threshold: float,
        match: str,
        serve_data_url: str,
    ) -> None:
        check = NetworkBandwidth(
            "name", psutil.net_if_addrs().keys(), send_threshold, receive_threshold
        )
        # make some traffic
        requests.get(serve_data_url, timeout=5)
        res = check.check()
        assert res is not None
        assert match in res

    def test_reports_no_activity_below_threshold(self, serve_data_url: str) -> None:
        check = NetworkBandwidth(
            "name", psutil.net_if_addrs().keys(), sys.float_info.max, sys.float_info.max
        )
        # make some traffic
        requests.get(serve_data_url, timeout=5)
        assert check.check() is None

    def test_internal_state_updating_works(self, serve_data_url: str) -> None:
        check = NetworkBandwidth(
            "name", psutil.net_if_addrs().keys(), sys.float_info.max, sys.float_info.max
        )
        check.check()
        old_state = check._previous_values
        requests.get(serve_data_url, timeout=5)
        check.check()
        assert old_state != check._previous_values

    def test_delta_calculation_send_work(self, mocker: MockerFixture) -> None:
        first = mocker.MagicMock()
        type(first).bytes_sent = mocker.PropertyMock(return_value=1000)
        type(first).bytes_recv = mocker.PropertyMock(return_value=800)
        mocker.patch("psutil.net_io_counters").return_value = {
            "eth0": first,
        }

        with freeze_time("2019-10-01 10:00:00"):
            check = NetworkBandwidth("name", ["eth0"], 0, sys.float_info.max)

        second = mocker.MagicMock()
        type(second).bytes_sent = mocker.PropertyMock(return_value=1222)
        type(second).bytes_recv = mocker.PropertyMock(return_value=900)
        mocker.patch("psutil.net_io_counters").return_value = {
            "eth0": second,
        }

        with freeze_time("2019-10-01 10:00:01"):
            res = check.check()
            assert res is not None
            assert " 222.0 " in res

    def test_delta_calculation_receive_work(self, mocker: MockerFixture) -> None:
        first = mocker.MagicMock()
        type(first).bytes_sent = mocker.PropertyMock(return_value=1000)
        type(first).bytes_recv = mocker.PropertyMock(return_value=800)
        mocker.patch("psutil.net_io_counters").return_value = {
            "eth0": first,
        }

        with freeze_time("2019-10-01 10:00:00"):
            check = NetworkBandwidth("name", ["eth0"], sys.float_info.max, 0)

        second = mocker.MagicMock()
        type(second).bytes_sent = mocker.PropertyMock(return_value=1222)
        type(second).bytes_recv = mocker.PropertyMock(return_value=900)
        mocker.patch("psutil.net_io_counters").return_value = {
            "eth0": second,
        }

        with freeze_time("2019-10-01 10:00:01"):
            res = check.check()
            assert res is not None
            assert " 100.0 " in res


class TestPing(CheckTest):
    def create_instance(self, name: str) -> Check:
        return Ping(name, "8.8.8.8")

    def test_calls_ping_correctly(self, mocker: MockerFixture) -> None:
        mock = mocker.patch("subprocess.call")
        mock.return_value = 1

        hosts = ["abc", "129.123.145.42"]

        assert Ping("name", hosts).check() is None

        assert mock.call_count == len(hosts)
        for (args, _), host in zip(mock.call_args_list, hosts):
            assert args[0][-1] == host

    def test_raises_if_the_ping_binary_is_missing(self, mocker: MockerFixture) -> None:
        mock = mocker.patch("subprocess.call")
        mock.side_effect = FileNotFoundError()

        with pytest.raises(SevereCheckError):
            Ping("name", ["test"]).check()

    def test_detect_activity_if_ping_succeeds(self, mocker: MockerFixture) -> None:
        mock = mocker.patch("subprocess.call")
        mock.return_value = 0
        assert Ping("name", ["foo"]).check() is not None

    class TestCreate:
        def test_raises_if_hosts_are_missing(self) -> None:
            with pytest.raises(ConfigurationError):
                Ping.create("name", config_section())

        def test_comma_separated_hosts_are_split(self) -> None:
            ping = Ping.create("name", config_section({"hosts": "a,b,c"}))
            assert ping._hosts == ["a", "b", "c"]


class TestFile(CheckTest):
    def create_instance(self, name: str) -> Check:
        return File(name, Path("asdf"))

    class TestCreate:
        def test_it_works_with_a_valid_config(self) -> None:
            check = File.create("name", config_section({"path": "/tmp/test"}))
            assert check._path == Path("/tmp/test")

        def test_raises_without_path(self) -> None:
            with pytest.raises(ConfigurationError):
                File.create("name", config_section())

    def test_extracts_data_from_file(self, tmp_path: Path) -> None:
        test_file = tmp_path / "file"
        test_file.write_text("42\n\n")
        assert File("name", test_file).check(
            datetime.now(UTC)
        ) == datetime.fromtimestamp(42, UTC)

    def test_reports_no_wakeup_if_file_does_not_exist(self, tmp_path: Path) -> None:
        assert File("name", tmp_path / "narf").check(datetime.now(UTC)) is None

    def test_raises_on_permissions_errors(self, tmp_path: Path) -> None:
        file_path = tmp_path / "test"
        file_path.write_bytes(b"2314898")
        file_path.chmod(0)
        with pytest.raises(TemporaryCheckError):
            File("name", file_path).check(datetime.now(UTC))

    def test_raises_on_io_errors(self, tmp_path: Path, mocker: MockerFixture) -> None:
        file_path = tmp_path / "test"
        file_path.write_bytes(b"2314898")
        mocker.patch("pathlib.Path.read_text").side_effect = IOError
        with pytest.raises(TemporaryCheckError):
            File("name", file_path).check(datetime.now(UTC))

    def test_raises_if_file_contents_are_not_a_timestamp(self, tmp_path: Path) -> None:
        test_file = tmp_path / "filexxx"
        test_file.write_text("nonumber\n\n")
        with pytest.raises(TemporaryCheckError):
            File("name", test_file).check(datetime.now(UTC))