aboutsummaryrefslogtreecommitdiffstats
path: root/tests/test_sleep.py
blob: ced176d350634c1e8668f4226e721abef79e5fc4 (plain)
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
# deck-it - tests for sleep
# Copyright (C) 2026 Danilo M. <danix@danix.xyz>
#
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License version 2 as
# published by the Free Software Foundation.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program; if not, write to the Free Software Foundation, Inc.,
# 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.

import sys
from pathlib import Path

sys.path.insert(0, str(Path(__file__).resolve().parent.parent))

import os
import shutil
import stat
import subprocess
import tempfile
import threading
import time
import unittest

from deckit import sleep


def until(fn, secs=3):
    end = time.monotonic() + secs
    while time.monotonic() < end:
        if fn():
            return True
        time.sleep(0.02)
    return False


SIG = "signal time=1 sender=:1.2 -> destination=(null destination) serial=9 path=/org/freedesktop/login1; interface=org.freedesktop.login1.Manager; member="


class Watch(unittest.TestCase):
    def watch(self, script):
        bin_ = tempfile.mkdtemp(dir="/tmp")
        self.addCleanup(shutil.rmtree, bin_)
        log = Path(bin_) / "log"
        for name, body in {
            "dbus-monitor": script,
            "elogind-inhibit": f"echo \"$1\" >> {log}; exec sleep 100",
        }.items():
            p = Path(bin_) / name
            p.write_text("#!/bin/sh\n" + body + "\n")
            p.chmod(p.stat().st_mode | stat.S_IXUSR)
        path = os.environ["PATH"]
        os.environ["PATH"] = bin_ + ":" + path
        self.addCleanup(os.environ.__setitem__, "PATH", path)
        sleep.SHOW = 0.2
        sleep.why = ""
        taken = []
        real = sleep._inhibit
        sleep._inhibit = lambda: taken.append(real()) or taken[-1]
        self.addCleanup(setattr, sleep, "_inhibit", real)
        self.addCleanup(lambda: [subprocess.run(["pkill", "-g", str(p.pid)]) for p in taken])
        threading.Thread(target=sleep.watch, daemon=True).start()
        return taken, log

    def announce(self, member, at, back):
        # member announced (true) at `at` s, taken back (false) `back` s later
        return (f"sleep {at}; echo '{SIG}{member}'; echo '   boolean true'; "
                f"sleep {back}; echo '{SIG}{member}'; echo '   boolean false'; sleep 1")

    def check(self, member, why):
        taken, log = self.watch(self.announce(member, 0.3, 0.9))
        self.assertTrue(until(lambda: sleep.why == why))
        self.assertTrue(until(lambda: taken[0].poll() is not None))   # let go: the PC may go
        self.assertTrue(until(lambda: sleep.why == ""))
        self.assertTrue(until(lambda: len(taken) == 2 and taken[1].poll() is None))
        self.assertTrue(until(lambda: log.read_text().split() == ["--what=sleep:shutdown"] * 2))

    def test_suspend_flags_then_releases_and_takes_the_lock_again(self):
        self.check("PrepareForSleep", "asleep")

    def test_shutdown_flags_then_releases(self):
        self.check("PrepareForShutdown", "shutting down")

    def test_other_signals_are_ignored(self):
        taken, _ = self.watch(f"echo '{SIG}SessionNew'; echo '   boolean true'; sleep 1")
        time.sleep(0.4)
        self.assertEqual(sleep.why, "")
        self.assertIsNone(taken[0].poll())


if __name__ == "__main__":
    unittest.main()