import json import os import tempfile import threading import time import unittest from kurgan import demo from kurgan.hw import client as hw_client from kurgan.hw.client import (CommanderReadings, CpuPackage, HardwareClient, HardwareUnavailable, LocalTransport, PipeTransport, RamLighting) from kurgan.hw.pipe import PipeError, PipeServer, current_user_sid, pipe_sddl from kurgan.hw.protocol import VERSION, RemoteError, Session from kurgan.telemetry.sensors import CpuSensors, SystemPower from kurgan.telemetry.service import SERVICE_SOURCE, Telemetry class Service: """The demo's hardware service (the real HardwareService on fakes) and a client to it.""" def __init__(self, test: unittest.TestCase): directory = tempfile.TemporaryDirectory() test.addCleanup(directory.cleanup) self.path = os.path.join(directory.name, "hw-settings.json") self.service = demo.hardware_service(self.path) self.service.tick(time.monotonic()) self.connects = 0 self.down = False # the next connects fail, as with no pipe self.transport: LocalTransport | None = None def connect(self): self.connects += 1 if self.down: raise PipeError("the hardware service isn't running (no pipe)", 2) self.transport = LocalTransport(self.service.dispatch) return self.transport def saved(self) -> dict: with open(self.path, encoding="utf-8") as stream: return json.load(stream) class ClientTest(unittest.TestCase): def setUp(self): self.hw = Service(self) self.client = HardwareClient(self.hw.connect) def test_reads_the_services_state(self): self.client.poll() self.assertIsNone(self.client.error) cooling = self.client.cooling() self.assertEqual([g["name"] for g in cooling["groups"]], ["GPU", "CPU"]) self.assertEqual(cooling["profile"], "balanced") self.assertEqual(len(cooling["row"]), 4) self.assertIsNotNone(self.client.cpu()["temp"]) self.assertEqual(len(self.client.fan_rpms()), 6) self.assertEqual(self.client.ram_lighting()["mode"], "off") snapshot = self.client.snapshot() self.assertTrue(snapshot["available"]) self.assertEqual(snapshot["pid"], os.getpid()) def test_changes_go_to_the_service_and_are_saved_there(self): self.client.poll() self.client.set_profile("quiet") self.assertEqual(self.client.cooling()["profile"], "quiet") # the reply's state, no poll needed self.client.set_ram_lighting("chase") self.assertEqual(RamLighting(self.client).mode, "chase") self.assertEqual(self.hw.saved()["cooling"]["profile"], "quiet") self.assertEqual(self.hw.saved()["lighting"]["memory"], "chase") def test_bad_values_are_value_errors_and_nothing_is_sent(self): self.client.poll() for call, value in ((self.client.set_profile, "turbo"), (self.client.set_ram_lighting, "rainbow")): with self.subTest(value=value), self.assertRaises(ValueError): call(value) self.assertEqual(self.hw.saved()["cooling"]["profile"], "balanced") def test_without_a_service_everything_reads_empty_and_changes_raise(self): self.hw.down = True with self.assertLogs("kurgan.hw.client", level="WARNING"): self.client.poll() self.assertIn("isn't running", self.client.error) self.assertIsNone(self.client.state) cooling = self.client.cooling() self.assertEqual((cooling["groups"], cooling["top"], cooling["row"]), ([], None, None)) self.assertIn("Hardware service unavailable", cooling["note"]) self.assertEqual(self.client.fan_rpms(), []) self.assertEqual(CpuPackage(self.client).read(), (None, None)) self.assertIn("unavailable", CpuPackage(self.client).status) self.assertIn("unavailable", RamLighting(self.client).status) self.assertFalse(self.client.snapshot()["available"]) with self.assertRaises(HardwareUnavailable): self.client.set_profile("quiet") def test_reconnects_and_greets_again_after_the_service_restarts(self): self.client.poll() self.client.set_profile("quiet") self.hw.transport.close() # the service went away mid-connection self.hw.down = True with self.assertLogs("kurgan.hw.client", level="WARNING"): self.client.poll() self.assertIsNotNone(self.client.error) self.assertEqual(self.client.cooling()["profile"], "quiet") # the last one known, for the buttons self.hw.down = False with self.assertLogs("kurgan.hw.client", level="INFO"): self.client.poll() self.assertIsNone(self.client.error) self.assertEqual(self.hw.connects, 2) # the failed poll found the old connection broken self.assertTrue(self.hw.transport._session.greeted) def test_a_different_protocol_drops_the_connection_and_says_what_to_do(self): class Old: closed = False def call(self, op, args=None, timeout=None): raise RemoteError(VERSION, "the service speaks protocol 2, the client 1") def close(self): self.closed = True old = Old() client = HardwareClient(lambda: old) with self.assertLogs("kurgan.hw.client", level="WARNING"): client.poll() self.assertIn("re-run setup.ps1", client.error) self.assertTrue(old.closed) def test_a_refusal_by_a_service_that_is_up_keeps_the_connection(self): self.client.poll() self.hw.service.settings = None # hw-settings.json turned out invalid self.hw.service.settings_error = "cooling.profile must be one of ..." with self.assertRaises(HardwareUnavailable) as raised: self.client.set_profile("quiet") self.assertIn("hw-settings.json is invalid", str(raised.exception)) self.client.poll() self.assertIsNone(self.client.error) self.assertEqual(self.hw.connects, 1) def test_a_stuck_service_loop_counts_as_unavailable(self): self.client.poll() self.hw.service._snapshot["t"] = time.time() - 60 # the loop stopped publishing a minute ago with self.assertLogs("kurgan.hw.client", level="WARNING"): self.client.poll() self.assertIn("stalled", self.client.error) self.assertIsNone(self.client.state) def test_an_old_state_is_no_state(self): self.client.poll() self.client._state_at -= hw_client.STALE_SECONDS + 1 # no poll got through since self.assertEqual(self.client.error, "no state from the hardware service") self.assertEqual(self.client.fan_rpms(), []) def test_each_poll_sends_the_chase_clock(self): self.client.chase = lambda: {"phase": 123.0, "rate": 9.0, "power": 400.0} self.client.poll() chase = self.hw.service.chase self.assertEqual((chase.phase, chase.rate), (123.0, 9.0)) def test_the_app_side_readers_take_the_services_values(self): self.client.poll() state = self.client.state self.assertEqual(CommanderReadings(self.client).read(), state["commander"]["rpms"]) cpu = CpuSensors(package=CpuPackage(self.client)) self.assertEqual(cpu.read().temp, state["cpu"]["temp"]) self.assertEqual(cpu.status, "ok") def test_telemetry_lists_the_service_once_not_also_the_cpu_temperature(self): self.hw.down = True cpu = CpuSensors(package=CpuPackage(self.client)) fake = demo.FakeGpu() telemetry = Telemetry(cpu, fake, SystemPower(fans=CommanderReadings(self.client)), hw=self.client) with self.assertLogs("kurgan", level="WARNING"): for _ in range(3): self.client.poll() sample = telemetry.read() self.assertIsNone(sample.cpu.temp) self.assertEqual(list(telemetry.health()), [SERVICE_SOURCE]) self.hw.down = False with self.assertLogs("kurgan", level="INFO"): self.client.poll() telemetry.read() self.assertEqual(telemetry.health(), {}) class PipeEndToEndTest(unittest.TestCase): def test_the_client_over_a_real_pipe(self): me = current_user_sid() hw = Service(self) name = rf"\\.\pipe\kurgan-hw-client-test-{os.getpid()}" server = PipeServer(name, pipe_sddl(me, server_sid=me), lambda: Session(hw.service.dispatch, "test")) server.start() self.addCleanup(server.close) client = HardwareClient(lambda: PipeTransport(name, trusted_owners=None)) deadline = time.monotonic() + 2 while True: # the listener may not have created the pipe yet with self.assertLogs("kurgan.hw.client", level="INFO"): client.poll() if client.error is None or time.monotonic() > deadline: break self.assertIsNone(client.error) client.set_profile("performance") self.assertEqual(hw.saved()["cooling"]["profile"], "performance") stop = threading.Event() thread = threading.Thread(target=client.run, args=(stop,)) thread.start() stop.set() thread.join(5) self.assertFalse(thread.is_alive()) if __name__ == "__main__": unittest.main()