"""The History window: its data (routine/gui/history_cols.py) and, offscreen on fake data, the window itself (zoom by pinch / Ctrl+wheel / shortcuts, block headings folding). Run: python3 -m unittest discover tests""" import datetime as dt import os import subprocess import sys import tempfile import unittest ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) sys.path.insert(0, ROOT) from routine import model # noqa: E402 from routine.gui import history_cols as hc # noqa: E402 START = dt.date(2026, 1, 5) # a Monday def day(k, items, done=(), blocks=None): """Day k from START: items [(block, item id, label)] in its snapshot, done = item ids ticked.""" bl = {} for b, iid, label in items: bl.setdefault(b, []).append({"id": iid, "label": label, "depth": iid.count("/") - 1}) return {"date": (START + dt.timedelta(days=k)).isoformat(), "blocks": [{"id": b, "label": b.title(), "start": 7, "end": 8, "color": "#abcdef", "items": v} for b, v in bl.items()], "states": {i: {"s": model.DONE, "t": 1} for i in done}, "note": {"text": "", "t": 0}} class Order(unittest.TestCase): def test_merge_after_neighbour(self): self.assertEqual(hc.merge_order(["a", "c"], ["a", "b", "c"]), ["a", "b", "c"]) self.assertEqual(hc.merge_order(["a", "c"], ["x", "a"]), ["x", "a", "c"]) self.assertEqual(hc.merge_order(["a", "c"], ["c", "z"]), ["a", "c", "z"]) def test_columns_follow_the_schedule_removed_ones_after_their_neighbour(self): sched = {"blocks": [{"id": "m", "label": "Morning", "start": 7, "end": 9, "color": "#ff0000", "items": [{"label": "a"}, {"label": "c", "days": [1]}]}, {"id": "n", "label": "Night", "start": 20, "end": 22, "color": "#00ff00", "items": [{"label": "z"}]}]} old = [("m", "m/a", "a"), ("m", "m/b", "b"), ("m", "m/c", "c"), ("gone", "gone/q", "q")] days = [day(0, old, done=["m/a"]), day(1, [("m", "m/a", "a"), ("m", "m/c", "c")])] h = model.history(days, days[-1]["date"]) gs = hc.groups(sched, days, h, days[0]["date"], days[-1]["date"]) self.assertEqual([g.id for g in gs], ["m", "gone"]) # n never appears in the range self.assertEqual([c.id for c in gs[0].items], ["m/a", "m/b", "m/c"]) self.assertEqual([c.removed for c in gs[0].items], [False, True, False]) self.assertTrue(gs[1].removed) self.assertEqual(gs[0].color, "#ff0000") # today's colour for the block self.assertEqual(gs[0].items[0].path, ["Morning", "a"]) class Marks(unittest.TestCase): def mk(self, pattern, cheat_after=2): """D done, M missed, . off (not in the snapshot); one task a/x; newest last.""" days = [day(k, [] if c == "." else [("a", "a/x", "x")], done=["a/x"] if c == "D" else []) for k, c in enumerate(pattern)] h = model.history(days, (START + dt.timedelta(days=len(pattern))).isoformat(), cheat_after) dates = hc.dates_between(days[0]["date"], days[-1]["date"]) return hc.Marks(h.items["a/x"], dates) def test_pills_bridges_cheats(self): m = self.mk("DD.DMDDMM") # rows count back from the newest: row 0 = the last M self.assertEqual(m.misses, [0, 1]) self.assertEqual(m.pills, [(2, 5), (7, 8)]) # D D cheat D, the off day, D D self.assertEqual(m.cheats, [4]) self.assertEqual(m.bridges, [(6, 6)]) self.assertEqual(m.code(4), model.S_CHEAT) self.assertEqual(m.run(3).length, 5) def test_off_days_bridge_a_streak(self): m = self.mk("DD..DD", cheat_after=0) self.assertEqual(m.pills, [(0, 1), (4, 5)]) self.assertEqual(m.bridges, [(2, 3)]) self.assertEqual(m.day_in_run(1), 3) def test_a_streak_runs_off_the_edges(self): days = [day(k, [("a", "a/x", "x")], done=["a/x"]) for k in range(10)] h = model.history(days, "2027-01-01") dates = hc.dates_between(days[3]["date"], days[6]["date"]) self.assertEqual(hc.Marks(h.items["a/x"], dates).pills, [(-1, 4)]) GUI = r''' import os, sys, time sys.path.insert(0, %(root)r) from routine.qt.QtCore import QEvent, QPointF, QPoint, Qt from routine.qt.QtGui import QHelpEvent, QNativeGestureEvent, QPointingDevice, QWheelEvent, QMouseEvent from routine.qt.QtWidgets import QApplication, QToolTip errors = [] # an exception in an event handler: PyQt6 would abort, PySide6 prints and goes on sys.excepthook = lambda t, v, tb: errors.append(t.__name__ + ": " + str(v)) from routine import paths from routine.gui import app as appm qa = QApplication(sys.argv) cfg = paths.load_config() cfg["ranges"] = {"history": {"preset": "all"}} win = appm.Window(cfg) win.open_side("history") hw = win.side["history"] for _ in range(5): qa.processEvents() g = hw.grid vp = g.viewport() assert g.lanes and g.dates, "nothing to show" assert g.dates[0] == win.today.isoformat() from routine.qt.QtTest import QTest C, S = Qt.KeyboardModifier.ControlModifier, Qt.KeyboardModifier.ShiftModifier dev = QPointingDevice.primaryPointingDevice() def under(pt): h = g.hit(pt) return (h[1], h[2]) if h and h[0] == "grid" else None def view_pt(t, l): """A viewport point t px along the time view and l px along the lane view.""" return QPointF(g.left_w + t, g.top_h + l) if g.flip else QPointF(g.left_w + l, g.top_h + t) def click(pt): for kind in (QMouseEvent.Type.MouseButtonPress, QMouseEvent.Type.MouseButtonRelease): QApplication.sendEvent(vp, QMouseEvent(kind, pt, pt, Qt.MouseButton.LeftButton, Qt.MouseButton.LeftButton if kind == QMouseEvent.Type.MouseButtonPress else Qt.MouseButton.NoButton, Qt.KeyboardModifier.NoModifier)) # the defaults: days down, the newest at the bottom, opened on it assert not g.flip and g.newest_last assert g.time_bar() is g.verticalScrollBar() and g.time_bar().value() == g.time_bar().maximum() > 0 for swap, last in ((False, True), (False, False), (True, False), (True, True)): if g.flip != swap: hw.swap_btn.click() if g.newest_last != last: hw.order_btn.click() assert cfg.get("history_swap", False) == swap and cfg.get("history_newest_last", True) == last assert g.flip == swap and g.newest_last == last g.zoom_to(1.0) g.to_newest() tv, lv = g.views() tb = g.time_bar() assert tb is (g.horizontalScrollBar() if swap else g.verticalScrollBar()) # the newest day sits at the newest end, the oldest at the other (Home / End) near_end = view_pt(tv - g.dd / 2 - 10, g.lanes[0][1] / 2 + 6) # 10: the padding after the last day near_start = view_pt(g.dd / 2, g.lanes[0][1] / 2 + 6) assert under(near_end if last else near_start)[0] == 0, (swap, last) QTest.keyClick(g, Qt.Key.Key_Home) assert tb.value() == 0 assert under(near_start)[0] == (len(g.dates) - 1 if last else 0) QTest.keyClick(g, Qt.Key.Key_End) assert tb.value() == tb.maximum() # a pinch, then Ctrl+wheel, anchored at the pointer: the cell under it stays under it tb.setValue(tb.maximum() // 2) pt = view_pt(150, 200) before = under(pt) assert before is not None for v in (0.25, 0.25): QApplication.sendEvent(vp, QNativeGestureEvent(Qt.NativeGestureType.ZoomNativeGesture, dev, 2, pt, pt, vp.mapToGlobal(pt), v, QPointF(0, 0))) assert abs(g.zoom - 1.5625) < 1e-6, g.zoom assert under(pt) == before, (swap, last, under(pt), before) QApplication.sendEvent(vp, QWheelEvent(pt, vp.mapToGlobal(pt), QPoint(0, 0), QPoint(0, -240), Qt.MouseButton.NoButton, C, Qt.ScrollPhase.NoScrollPhase, False)) assert abs(g.zoom - 1.5625 / 1.21) < 1e-3, g.zoom assert under(pt) == before assert abs(cfg["history_zoom"] - g.zoom) < 1e-3 # dense, the smallest and the largest zoom all paint, quickly for z in (0.3, 0.08, 3.0): g.zoom_to(z) t = time.time(); vp.grab(); took = time.time() - t assert took < 0.5, (z, took) g.zoom_to(1.0) # clicking a block heading folds it into one lane, and back first = g.spans[0][2] n = len(g.lanes) l = g.spans[0][0] + 8 - g.lane_bar().value() click(QPointF(12, g.top_h + l) if swap else QPointF(g.left_w + l, 12)) assert first.id in cfg["history_collapsed"], (swap, cfg.get("history_collapsed")) assert len(g.lanes) == n - len(first.items) + 1 and g.lanes[0][2] is None g.toggle(first) assert len(g.lanes) == n and first.id not in cfg["history_collapsed"] # hover and tooltips QApplication.sendEvent(vp, QMouseEvent(QMouseEvent.Type.MouseMove, pt, pt, Qt.MouseButton.NoButton, Qt.MouseButton.NoButton, Qt.KeyboardModifier.NoModifier)) assert g.hover == under(pt) assert "" in g.tip(("grid", 1, 0)) and g.tip(("head", first, first.items[0])) # a real tooltip event (a QHelpEvent: pos() / globalPos(), no position()) over a cell QApplication.sendEvent(vp, QHelpEvent(QEvent.Type.ToolTip, pt.toPoint(), vp.mapToGlobal(pt.toPoint()))) assert not errors, errors want = g.tip(g.hit(QPointF(pt.toPoint()))) assert want and QToolTip.text() == want, (QToolTip.text(), want) assert hw.order_btn.toolTip() and hw.swap_btn.toolTip() vp.grab() # a reload (a tick in the main window) keeps the view where it was, or on the newest day tb = g.time_bar() tb.setValue(tb.maximum() // 3) mid = tb.value() hw._history = None hw.reload() assert tb.value() == mid, (tb.value(), mid) g.to_newest() hw.reload() assert tb.value() == (tb.maximum() if g.newest_last else 0) # the shortcuts, pressed g.zoom_to(1.0) hw._pointer = lambda: None for key, mod, want in ((Qt.Key.Key_Minus, C, 0.8), (Qt.Key.Key_Equal, C, 1.0), (Qt.Key.Key_Plus, C, 1.25), (Qt.Key.Key_Plus, C | S, 1.5625), (Qt.Key.Key_0, C, 1.0)): QTest.keyClick(g, key, mod) assert abs(g.zoom - want) < 1e-6, (key, mod, g.zoom) # flat dots paint too cfg["emboss_history"] = False vp.grab() assert not errors, errors print("OK") sys.stdout.flush() os._exit(0) ''' class Window(unittest.TestCase): def test_offscreen(self): with tempfile.TemporaryDirectory() as home: subprocess.run([sys.executable, os.path.join(ROOT, "tools", "fake_history.py"), home, "--days", "200"], check=True, capture_output=True) env = dict(os.environ, ROUTINE_HOME=home, QT_QPA_PLATFORM="offscreen") r = subprocess.run([sys.executable, "-c", GUI % {"root": ROOT}], env=env, capture_output=True, text=True, timeout=120) self.assertIn("OK", r.stdout, r.stderr[-3000:]) if __name__ == "__main__": unittest.main()