okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221monitor: the classic Windows console switches to Cascadia Mono when installed, else a solid-block look with palette colours; several cards and CPUs in the Overview (totals, a Cards strip, sockets); whole card names in view 51d0397652

main
13.1 KiB232 linesraw
1"""The monitor in the classic Windows console (Cascadia Mono switch, the solid look, the tip) and with several cards / CPUs."""
2
3from __future__ import annotations
4
5import io
6import os
7import time
8import unittest
9from unittest import mock
10
11from rich.console import Console
12
13from strata_cli import consoleinfo, monitor, overview
14from tests.terminal.test_overview import GIB, metrics
15
16TIP = "For the full look, use Windows Terminal (built into Windows 11)"
17
18
19def draw(model, width=110, height=40, **kw) -> str:
20    c = Console(width=width + 2, record=True, file=io.StringIO(), force_terminal=False, legacy_windows=False)
21    c.print(overview.render(model, width=width, height=height, connection="http://127.0.0.1:8080", **kw))
22    return c.export_text()
23
24
25def three_cards(sockets=2):
26    m = metrics("generating")
27    cards = [{"index": i, "name": "NVIDIA GeForce RTX 3090", "util": u, "mem_used": used * GIB, "mem_total": 24 * GIB, "temp": t, "power": p, "power_limit": 350}
28             for i, (u, used, t, p) in enumerate(((88, 22.1, 61, 236), (71, 21.4, 58, 201), (64, 20.8, 55, 188)))]
29    m["hardware"]["gpus"] = cards
30    m["hardware_static"].update({"gpu_name": "NVIDIA GeForce RTX 3090", "gpu_count": 3, "cores": 64, "threads": 128, "sockets": sockets, "numa_nodes": 2})
31    return m
32
33
34class WhichLook(unittest.TestCase):
35    def setUp(self):
36        consoleinfo.forget_style()
37        self.addCleanup(consoleinfo.forget_style)
38
39    def test_decide_style_by_the_facts(self):
40        d = consoleinfo.decide_style(legacy=False, cascadia_ok=False, font=None)
41        self.assertEqual((d["mode"], d["tip"]), ("none", None))                       # Windows Terminal, Linux, macOS: nothing changes
42        d = consoleinfo.decide_style(legacy=True, cascadia_ok=True, font="Cascadia Mono")
43        self.assertEqual((d["mode"], d["tip"]), ("full", TIP))                        # the font was switched: the full Unicode look, the tip anyway
44        d = consoleinfo.decide_style(legacy=True, cascadia_ok=False, font="Consolas")
45        self.assertEqual((d["mode"], d["bullet"], d["tip"]), ("solid", "●", TIP))
46        d = consoleinfo.decide_style(legacy=True, cascadia_ok=False, font="Lucida Console")
47        self.assertEqual((d["mode"], d["bullet"]), ("solid", "•"))                    # Lucida has no ●
48        self.assertEqual(consoleinfo.decide_style(legacy=True, cascadia_ok=False, font=None)["bullet"], "•")
49
50    def test_classic_style_switches_the_font_once_when_cascadia_is_installed(self):
51        with mock.patch.object(consoleinfo, "legacy_console", return_value=True), mock.patch.object(consoleinfo.os, "name", "nt"), \
52                mock.patch.dict(os.environ, {"STRATA_GLYPHS": ""}), mock.patch.object(consoleinfo, "cascadia_installed", return_value=True), \
53                mock.patch.object(consoleinfo, "console_font", side_effect=["Consolas", "Cascadia Mono"]), \
54                mock.patch.object(consoleinfo, "switch_font", return_value=True) as sw:
55            s = consoleinfo.classic_style()
56            self.assertEqual(s["mode"], "full")
57            sw.assert_called_once_with("Cascadia Mono")
58            consoleinfo.classic_style()
59            sw.assert_called_once()                                                   # cached: the font API is not called again
60
61    def test_without_cascadia_or_when_the_switch_fails_the_solid_look_with_the_font_it_has(self):
62        for installed, switched in ((False, False), (True, False)):
63            consoleinfo.forget_style()
64            with mock.patch.object(consoleinfo, "legacy_console", return_value=True), mock.patch.object(consoleinfo.os, "name", "nt"), \
65                    mock.patch.dict(os.environ, {"STRATA_GLYPHS": ""}), mock.patch.object(consoleinfo, "cascadia_installed", return_value=installed), \
66                    mock.patch.object(consoleinfo, "console_font", return_value="Lucida Console"), \
67                    mock.patch.object(consoleinfo, "switch_font", return_value=switched):
68                s = consoleinfo.classic_style()
69                self.assertEqual((s["mode"], s["bullet"]), ("solid", "•"))
70
71    def test_never_in_windows_terminal_linux_or_mac(self):
72        with mock.patch.object(consoleinfo, "legacy_console", return_value=False), mock.patch.object(consoleinfo, "switch_font") as sw:
73            self.assertEqual(consoleinfo.classic_style()["mode"], "none")
74            sw.assert_not_called()
75        env = {k: v for k, v in os.environ.items() if k not in ("WT_SESSION", "TERM_PROGRAM", "STRATA_GLYPHS")}
76        env["WT_SESSION"] = "x"
77        with mock.patch.dict(os.environ, env, clear=True), mock.patch.object(consoleinfo.os, "name", "nt"), mock.patch.object(consoleinfo.sys, "platform", "win32"):
78            self.assertFalse(consoleinfo.legacy_console())                            # Windows Terminal
79        with mock.patch.dict(os.environ, {}, clear=True), mock.patch.object(consoleinfo.os, "name", "posix"), mock.patch.object(consoleinfo.sys, "platform", "linux"):
80            self.assertFalse(consoleinfo.legacy_console())
81        with mock.patch.object(consoleinfo.os, "name", "posix"):
82            self.assertIsNone(consoleinfo.console_font())
83            self.assertFalse(consoleinfo.switch_font())
84            self.assertFalse(consoleinfo.cascadia_installed())
85
86    def test_choose_glyphs(self):
87        with mock.patch.object(consoleinfo, "legacy_console", return_value=True), mock.patch.object(consoleinfo, "classic_style", return_value={"mode": "full"}):
88            self.assertEqual(monitor.choose_glyphs("auto", "utf-8", "xterm"), "unicode")
89        with mock.patch.object(consoleinfo, "legacy_console", return_value=True), mock.patch.object(consoleinfo, "classic_style", return_value={"mode": "solid"}):
90            self.assertEqual(monitor.choose_glyphs("auto", "utf-8", None), "solid")
91            with mock.patch.dict(os.environ, {"STRATA_GLYPHS": "ascii"}):
92                self.assertEqual(monitor.choose_glyphs("auto", "utf-8", None), "ascii")      # forced ASCII stays ASCII
93            self.assertEqual(monitor.choose_glyphs("unicode", "utf-8", None), "unicode")      # an explicit --glyphs wins
94        with mock.patch.object(consoleinfo, "legacy_console", return_value=False):
95            self.assertEqual(monitor.choose_glyphs("auto", "utf-8", "xterm"), "unicode")
96
97
98class SolidLook(unittest.TestCase):
99    def test_solid_blocks_only_no_dithered_shades_and_no_eighth_blocks(self):
100        text = draw(overview.build(metrics("generating")), glyphs="solid")
101        for ch in "░▒▓▁▂▃▅▆▇╭╮╰╯":
102            self.assertNotIn(ch, text, ch)
103        for ch in "█▄┌┐└┘":
104            self.assertIn(ch, text, ch)
105
106    def test_bars_use_a_thin_track_and_boxes_are_square(self):
107        bar = overview.bar(0.25, 20, "solid", "bright_green")
108        self.assertEqual(bar.plain, "█" * 5 + "▄" * 15)
109        self.assertEqual(overview.bar(None, 4, "solid", "x").plain, "▄▄▄▄")
110        self.assertEqual(overview.spark([0, 50, 100], 3, "solid", lo=0, hi=100).plain, "▄▄█")
111
112    def test_the_16_palette_names_not_hex_colours(self):
113        group = overview.render(overview.build(metrics("generating")), width=110, height=40, connection="x", glyphs="solid")
114        c = Console(width=112, record=True, file=io.StringIO(), force_terminal=True, color_system="standard", legacy_windows=False)
115        c.print(group)
116        out = c.export_text(styles=True)
117        self.assertNotIn("38;2;", out)                                          # no 24-bit colours: conhost maps them to cyan or black
118
119    def test_the_bullet_follows_the_font(self):
120        m = overview.build(metrics("generating"))
121        self.assertIn("● Generating", draw(m, glyphs="solid", bullet="●"))
122        self.assertIn("• Generating", draw(m, glyphs="solid", bullet="•"))
123
124    def test_the_other_looks_are_unchanged(self):
125        m = overview.build(metrics("generating"))
126        self.assertIn("╭", draw(m, glyphs="unicode"))
127        self.assertNotIn("╭", draw(m, glyphs="ascii"))
128
129
130class SeveralCards(unittest.TestCase):
131    def test_one_card_looks_exactly_as_before(self):
132        base = metrics("generating")
133        one = metrics("generating")
134        one["hardware"]["gpus"] = [{"index": 0, "name": "NVIDIA GeForce RTX 5070", "util": 88, "mem_used": 11.2 * GIB, "mem_total": 12 * GIB, "temp": 54, "power": 114}]
135        for glyphs in ("unicode", "ascii", "solid"):
136            self.assertEqual(draw(overview.build(base), glyphs=glyphs, now=1.0), draw(overview.build(one), glyphs=glyphs, now=1.0), glyphs)
137        self.assertNotIn("Cards", draw(overview.build(base)))
138
139    def test_the_tiles_say_it_for_the_whole_computer(self):
140        m = overview.build(three_cards())
141        g = m["gpu"]
142        self.assertEqual((g["util"], g["temp"], g["count"]), (88.0, 61.0, 3.0))                  # the busiest, the hottest
143        self.assertAlmostEqual(g["vram_used"], 64.3, places=1)
144        self.assertEqual(g["vram_total"], 72.0)                                                    # all cards
145        self.assertEqual((g["power"], g["power_limit"]), (625.0, 1050.0))
146        text = draw(m)
147        for want in ("busiest of 3 cards", "all 3 cards", "hottest card", "64.3 / 72 GB", "625 W", "of 1,050 W limit", "61 °C"):
148            self.assertIn(want, text, want)
149        self.assertNotIn("+2", text)                                                              # no more "RTX 3090 +2"
150
151    def test_the_cards_strip_one_line_per_card(self):
152        text = draw(overview.build(three_cards()))
153        lines = [ln for ln in text.splitlines() if ln.startswith("GPU ")]
154        self.assertEqual(len(lines), 3)
155        self.assertIn("Cards", text)
156        for want, line in zip(("88 %", "71 %", "64 %"), lines):
157            self.assertIn(want, line)
158        self.assertIn("22.1 / 24 GB", lines[0])
159        self.assertIn("61 °C", lines[0])
160        self.assertIn("236 W", lines[0])
161        self.assertIn("RTX 3090", lines[0])
162
163    def test_up_to_four_cards_then_a_pointer_to_view_5(self):
164        m = three_cards()
165        m["hardware"]["gpus"] += [dict(m["hardware"]["gpus"][0], index=i) for i in (3, 4, 5)]
166        text = draw(overview.build(m), height=44)
167        self.assertEqual(len([ln for ln in text.splitlines() if ln.startswith("GPU ")]), 4)
168        self.assertIn("+ 2 more cards: press 5", text)
169
170    def test_the_cpu_tile_says_how_many_cpus(self):
171        self.assertIn("2 CPUs · 64 cores", draw(overview.build(three_cards(sockets=2))))
172        one = draw(overview.build(three_cards(sockets=1)))
173        self.assertIn("64 cores · 128 threads", one)
174        self.assertNotIn("CPUs", one)
175        self.assertIn("6 cores · 12 threads", draw(overview.build(metrics("generating"))))     # no socket count reported: as before
176
177    def test_a_missing_reading_stays_missing(self):
178        m = three_cards()
179        for c in m["hardware"]["gpus"]:
180            c["temp"] = None
181            c["power"] = None
182        g = overview.build(m)["gpu"]
183        self.assertIsNone(g["temp"])
184        self.assertIsNone(g["power"])
185        self.assertIn("-- °C", draw(overview.build(m)))
186
187    def test_it_fits_the_width_and_the_classic_looks_too(self):
188        for glyphs in ("unicode", "ascii", "solid"):
189            for ln in draw(overview.build(three_cards()), glyphs=glyphs, width=100).splitlines():
190                self.assertLessEqual(len(ln.rstrip()), 102, (glyphs, ln))
191
192
193class FooterAndViews(unittest.TestCase):
194    def screen_text(self, classic):
195        import asyncio
196        from tests.terminal.test_overview import Source
197
198        async def go():
199            consoleinfo.forget_style()
200            style = consoleinfo.decide_style(legacy=bool(classic), cascadia_ok=classic == "full", font="Consolas")
201            with mock.patch.object(consoleinfo, "legacy_console", return_value=bool(classic)), mock.patch.object(consoleinfo, "classic_style", return_value=style):
202                app = monitor.MonitorApp(Source(three_cards()), None, interval=30)
203                async with app.run_test(size=(120, 40)) as pilot:
204                    await pilot.pause(0.5)
205                    return "\n".join(s.text for s in app.screen._compositor.render_strips())
206        try:
207            return asyncio.run(go())
208        finally:
209            consoleinfo.forget_style()
210
211    def test_the_tip_is_in_the_classic_console_only(self):
212        self.assertIn(TIP, self.screen_text("solid"))
213        self.assertIn(TIP, self.screen_text("full"))                  # also when the font was switched: one line, always
214        self.assertNotIn(TIP, self.screen_text(None))                  # Windows Terminal, Linux, macOS
215
216    def test_the_monitor_draws_the_several_cards_in_every_look(self):
217        for classic in ("solid", "full", None):
218            shown = self.screen_text(classic)
219            self.assertIn("busiest of 3 cards", shown, classic)
220            self.assertIn("Cards", shown, classic)
221            self.assertIn("2 CPUs", shown, classic)
222
223    def test_view_5_shows_the_whole_card_name(self):
224        from strata_cli.render import _device
225        row = {"index": 1, "name": "NVIDIA GeForce RTX 3090", "mem_used": 21.4 * GIB, "mem_total": 24 * GIB, "util": 71, "temp": 58, "power": 201}
226        line = _device(row, 100)
227        self.assertIn("RTX 3090", line)
228        self.assertNotIn("NVIDIA", line)
229
230
231if __name__ == "__main__":
232    unittest.main()