v0.23.0: Routine, first public version
This commit is contained in:
@@ -0,0 +1,228 @@
|
||||
"""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 "<b>" 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()
|
||||
@@ -0,0 +1,533 @@
|
||||
"""The R1's streak number agrees with the desktop's: model.py's streak base, the Java port
|
||||
(android/src/main/java/.../Model.java, Streaks.java, Digits.java, run on the JDK through
|
||||
android/src/test/java/.../R1Check.java with a test-only org.json), and the base travelling through
|
||||
a local routine-server (this one, and the old one from git HEAD~ when there is one).
|
||||
|
||||
Fake data only. Run: python3 -m unittest discover tests
|
||||
"""
|
||||
import atexit
|
||||
import copy
|
||||
import datetime as dt
|
||||
import glob
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import urllib.request
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
from routine import model # noqa: E402
|
||||
|
||||
JAVA_HOME = os.environ.get("JAVA_HOME", "/usr/lib/jvm/java-21-openjdk")
|
||||
JAVAC, JAVA = os.path.join(JAVA_HOME, "bin", "javac"), os.path.join(JAVA_HOME, "bin", "java")
|
||||
SRC = os.path.join(ROOT, "android", "src")
|
||||
TODAY = dt.date(2026, 11, 14)
|
||||
|
||||
SCHEDULE = {"rev": 3, "dayStartsAt": 4, "blocks": [
|
||||
{"id": "am", "label": "AM", "start": 7, "end": 9, "color": "#ffffff", "items": [
|
||||
{"id": "teeth", "label": "teeth"},
|
||||
{"id": "run", "label": "run", "days": [1, 2, 3, 4, 5]}, # weekdays only
|
||||
{"id": "tea", "label": "tea", "calm": True, "items": [{"label": "idea", "hint": True}]}]},
|
||||
{"id": "pm", "label": "PM", "start": 18, "end": 22, "color": "#000000", "days": [0, 6], "items": [
|
||||
{"id": "read", "label": "read"}]}, # weekends only
|
||||
]}
|
||||
ITEMS = ["am/teeth", "am/run", "am/tea", "pm/read"]
|
||||
|
||||
|
||||
def fake_days(rng, n, p_done):
|
||||
"""n days up to TODAY from SCHEDULE, each task done with probability p_done[item] (fake data)."""
|
||||
days = []
|
||||
for k in range(n):
|
||||
d = TODAY - dt.timedelta(days=n - 1 - k)
|
||||
day = model.new_day(SCHEDULE, d)
|
||||
for b in day["blocks"]:
|
||||
for it in b["items"]:
|
||||
if not it.get("hint"):
|
||||
r = rng.random()
|
||||
if r < p_done[it["id"]]:
|
||||
day["states"][it["id"]] = {"s": model.DONE, "t": 1}
|
||||
elif r < p_done[it["id"]] + 0.03:
|
||||
day["states"][it["id"]] = {"s": model.SKIPPED, "t": 1}
|
||||
days.append(day)
|
||||
return days
|
||||
|
||||
|
||||
def ticked(days, iid, date):
|
||||
"""days with iid ticked on date (as the app does just before asking for the streak)."""
|
||||
out = list(days)
|
||||
for k, d in enumerate(out):
|
||||
if d["date"] == date:
|
||||
d = out[k] = dict(d, states=dict(d["states"]))
|
||||
d["states"][iid] = {"s": model.DONE, "t": 2}
|
||||
return out
|
||||
|
||||
|
||||
def on(day, iid):
|
||||
return any(it["id"] == iid for b in day["blocks"] for it in b["items"])
|
||||
|
||||
|
||||
def have_java():
|
||||
return os.path.exists(JAVAC) and os.path.exists(JAVA)
|
||||
|
||||
|
||||
class Java:
|
||||
"""Compiles the R1's pure classes and R1Check once; run(cases) -> its answers."""
|
||||
dir = None
|
||||
|
||||
@classmethod
|
||||
def build(cls):
|
||||
if cls.dir:
|
||||
return
|
||||
cls.dir = tempfile.mkdtemp(prefix="r1check-")
|
||||
atexit.register(shutil.rmtree, cls.dir, True)
|
||||
main = os.path.join(SRC, "main", "java", "me", "teafry", "routine")
|
||||
srcs = [os.path.join(main, f) for f in ("Model.java", "Streaks.java", "Digits.java")]
|
||||
srcs += glob.glob(os.path.join(SRC, "test", "java", "**", "*.java"), recursive=True)
|
||||
subprocess.run([JAVAC, "--release", "11", "-Xlint:-options", "-d", os.path.join(cls.dir, "cls"), *srcs],
|
||||
check=True, capture_output=True)
|
||||
|
||||
@classmethod
|
||||
def run(cls, cases):
|
||||
cls.build()
|
||||
path = os.path.join(cls.dir, "in.json")
|
||||
with open(path, "w") as f:
|
||||
json.dump(cases, f)
|
||||
r = subprocess.run([JAVA, "-cp", os.path.join(cls.dir, "cls"), "me.teafry.routine.R1Check", path],
|
||||
check=True, capture_output=True, text=True)
|
||||
return json.loads(r.stdout)
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
"""model.streak_base + streak_ending(base=) == streak_ending over the whole history."""
|
||||
|
||||
def test_base_matches_whole_history(self):
|
||||
rng = random.Random(7)
|
||||
checked = 0
|
||||
for trial in range(12):
|
||||
p = {i: rng.choice([0.75, 0.9, 0.97]) for i in ITEMS}
|
||||
days = fake_days(rng, rng.randint(40, 140), p)
|
||||
for cheat in (0, 1, 3, 7):
|
||||
for lag in (1, 5, 30):
|
||||
asof = (TODAY - dt.timedelta(days=lag)).isoformat()
|
||||
base = model.streak_base(days, asof, cheat)
|
||||
for back in range(0, lag):
|
||||
date = (TODAY - dt.timedelta(days=back)).isoformat()
|
||||
for iid in ITEMS:
|
||||
dd = ticked(days, iid, date)
|
||||
whole = model.streak_ending(dd, iid, date, cheat)
|
||||
part = model.streak_ending([d for d in dd if d["date"] > asof], iid, date, cheat, base)
|
||||
self.assertEqual(whole, part, (trial, cheat, lag, back, iid))
|
||||
checked += whole > 0
|
||||
self.assertGreater(checked, 1000)
|
||||
|
||||
def test_pending_cheat_day_at_asof(self):
|
||||
# done x7 (a cheat day earned), a miss on asof (the cheat day used), then a miss: no rescue
|
||||
days = []
|
||||
pat = "DDDDDDDM"
|
||||
for k, c in enumerate(pat + "MD"):
|
||||
d = TODAY - dt.timedelta(days=len(pat) + 1 - k)
|
||||
day = {"date": d.isoformat(), "rev": 1, "note": {"text": "", "t": 0},
|
||||
"blocks": [{"id": "a", "label": "A", "start": 7, "end": 8, "color": "#fff",
|
||||
"items": [{"id": "a/x", "label": "x", "depth": 0}]}],
|
||||
"states": {"a/x": {"s": "done", "t": 1}} if c == "D" else {}}
|
||||
days.append(day)
|
||||
asof = days[len(pat) - 1]["date"]
|
||||
base = model.streak_base(days, asof, 7)
|
||||
self.assertEqual(base["items"]["a/x"], [7, 0, 0, 1])
|
||||
date = days[-1]["date"]
|
||||
self.assertEqual(model.streak_ending(days, "a/x", date, 7), 1)
|
||||
self.assertEqual(model.streak_ending(days[len(pat):], "a/x", date, 7, base), 1)
|
||||
# ... and with a done day after the cheat day instead, the run goes on
|
||||
days[-2]["states"] = {"a/x": {"s": "done", "t": 1}}
|
||||
self.assertEqual(model.streak_ending(days, "a/x", date, 7), 9)
|
||||
self.assertEqual(model.streak_ending(days[len(pat):], "a/x", date, 7, base), 9)
|
||||
|
||||
|
||||
@unittest.skipUnless(have_java(), "no JDK at " + JAVA_HOME)
|
||||
class R1Port(unittest.TestCase):
|
||||
"""The Java port gives the same answers as model.py / anim_paint.py."""
|
||||
|
||||
def test_levels(self):
|
||||
ns = list(range(0, 1500))
|
||||
got = Java.run({"levels": ns})["levels"]
|
||||
self.assertEqual(got, [-1 if model.streak_level(n) is None else model.streak_level(n) for n in ns])
|
||||
|
||||
def test_model_streak_ending(self):
|
||||
rng = random.Random(3)
|
||||
cases, want = [], []
|
||||
for trial in range(6):
|
||||
days = fake_days(rng, 90, {i: rng.choice([0.8, 0.95]) for i in ITEMS})
|
||||
for cheat in (0, 2, 7):
|
||||
asof = (TODAY - dt.timedelta(days=20)).isoformat()
|
||||
base = model.streak_base(days, asof, cheat)
|
||||
for back in (0, 1, 6, 19, 25, 60):
|
||||
date = (TODAY - dt.timedelta(days=back)).isoformat()
|
||||
for iid in ITEMS:
|
||||
dd = ticked(days, iid, date)
|
||||
for b in (None, base):
|
||||
cases.append({"days": dd, "item": iid, "date": date, "cheat": cheat, "base": b})
|
||||
want.append(model.streak_ending(dd, iid, date, cheat, b))
|
||||
self.assertEqual(Java.run({"model": cases})["model"], want)
|
||||
|
||||
def test_r1_streak_with_base(self):
|
||||
"""What the R1 holds (the server's last 60 days, gaps for days nobody opened) + the desktop's base
|
||||
gives exactly the desktop's number, ticking today or any day after asof."""
|
||||
rng = random.Random(11)
|
||||
cases, want = [], []
|
||||
for trial in range(10):
|
||||
days = fake_days(rng, 400, {i: rng.choice([0.85, 0.95, 0.99]) for i in ITEMS})
|
||||
cheat = rng.choice([0, 3, 7])
|
||||
asof = (TODAY - dt.timedelta(days=model.STREAK_BASE_LAG)).isoformat()
|
||||
base = model.streak_base(days, asof, cheat)
|
||||
held = [d for d in days if d["date"] >= (TODAY - dt.timedelta(days=60)).isoformat()]
|
||||
held = [d for d in held if d["states"] or rng.random() < 0.85] # untouched days may be missing
|
||||
for back in range(0, model.STREAK_BASE_LAG):
|
||||
date = (TODAY - dt.timedelta(days=back)).isoformat()
|
||||
for iid in ITEMS:
|
||||
if not on(model.new_day(SCHEDULE, dt.date.fromisoformat(date)), iid):
|
||||
continue
|
||||
whole = model.streak_ending(ticked(days, iid, date), iid, date, cheat)
|
||||
r1 = ticked(held, iid, date)
|
||||
if not any(d["date"] == date for d in r1):
|
||||
continue
|
||||
cases.append({"days": r1, "schedule": SCHEDULE, "item": iid, "date": date,
|
||||
"cheat": 99, "base": base}) # the base's cheat_after counts
|
||||
want.append(whole)
|
||||
got = Java.run({"ending": cases})["ending"]
|
||||
self.assertEqual(got, want)
|
||||
self.assertTrue(any(n > 60 for n in want), "some streaks longer than what the R1 holds")
|
||||
|
||||
def test_r1_streak_without_base(self):
|
||||
"""No base (an old server): the number is the desktop's or 0 (no streak animation), never
|
||||
another number; and runs that started in view are counted."""
|
||||
rng = random.Random(5)
|
||||
cases, want = [], []
|
||||
for trial in range(10):
|
||||
days = fake_days(rng, 200, {i: rng.choice([0.7, 0.85, 0.97]) for i in ITEMS})
|
||||
cheat = rng.choice([0, 2, 7])
|
||||
held = [d for d in days if d["date"] >= (TODAY - dt.timedelta(days=60)).isoformat()]
|
||||
for back in range(0, 40):
|
||||
date = (TODAY - dt.timedelta(days=back)).isoformat()
|
||||
for iid in ITEMS:
|
||||
if not on(model.new_day(SCHEDULE, dt.date.fromisoformat(date)), iid):
|
||||
continue
|
||||
cases.append({"days": ticked(held, iid, date), "schedule": SCHEDULE, "item": iid,
|
||||
"date": date, "cheat": cheat, "base": None})
|
||||
want.append(model.streak_ending(ticked(days, iid, date), iid, date, cheat))
|
||||
got = Java.run({"ending": cases})["ending"]
|
||||
for g, w in zip(got, want):
|
||||
self.assertIn(g, (0, w))
|
||||
self.assertGreater(sum(1 for g, w in zip(got, want) if g == w and w > 0), 100)
|
||||
self.assertGreater(sum(1 for g, w in zip(got, want) if g == 0 and w > 0), 0)
|
||||
|
||||
def test_stale_base_falls_back(self):
|
||||
"""A base older than the oldest day the R1 holds isn't used (0 or the right number)."""
|
||||
rng = random.Random(2)
|
||||
days = fake_days(rng, 300, {i: 0.99 for i in ITEMS})
|
||||
asof = (TODAY - dt.timedelta(days=100)).isoformat()
|
||||
base = model.streak_base(days, asof, 7)
|
||||
held = [d for d in days if d["date"] >= (TODAY - dt.timedelta(days=60)).isoformat()]
|
||||
date = TODAY.isoformat()
|
||||
want = model.streak_ending(ticked(days, "am/teeth", date), "am/teeth", date, 7)
|
||||
got = Java.run({"ending": [{"days": ticked(held, "am/teeth", date), "schedule": SCHEDULE,
|
||||
"item": "am/teeth", "date": date, "cheat": 7, "base": base}]})["ending"]
|
||||
self.assertIn(got[0], (0, want))
|
||||
|
||||
def test_digits(self):
|
||||
try:
|
||||
from routine.gui.anim_paint import number_strokes
|
||||
except ImportError:
|
||||
self.skipTest("no Qt binding (PySide6 or PyQt6)")
|
||||
args = [[n, cx, cy, h, rot] for n in (7, 21, 42, 66, 100, 150, 254, 365, 465, 1234567890)
|
||||
for cx, cy, h, rot in ((0, 0, 1, 0), (0.5, -1.25, 1.6, 0.3), (-2, 1, 0.8, -1.1))]
|
||||
got = Java.run({"digits": args})["digits"]
|
||||
for a, g in zip(args, got):
|
||||
w = number_strokes(*a)
|
||||
self.assertEqual(len(g), len(w))
|
||||
for gs, ws in zip(g, w):
|
||||
self.assertEqual(len(gs), len(ws))
|
||||
for x, y in zip(gs, ws):
|
||||
self.assertAlmostEqual(x, y, places=4)
|
||||
|
||||
def close(self, got, want):
|
||||
self.assertEqual(len(got), len(want))
|
||||
for g, w in zip(got, want):
|
||||
if isinstance(w, (list, tuple)):
|
||||
self.close(g, w)
|
||||
else:
|
||||
self.assertAlmostEqual(g, w, places=4)
|
||||
|
||||
def test_caption(self):
|
||||
"""The "<n> days!" caption: strokes, placement, size and pop-in, Java == anim_paint."""
|
||||
try:
|
||||
from routine.gui import anim_paint as ap
|
||||
except ImportError:
|
||||
self.skipTest("no Qt binding (PySide6 or PyQt6)")
|
||||
ns = (7, 21, 42, 66, 100, 150, 254, 365, 465, 1465, 1234567890)
|
||||
caps = [[n, cx, top, h, sc] for n in ns for cx, top, h, sc in ((0, 0, 0.9, 1), (1.5, 2.25, 0.7, 0.5), (-3, -6, 0.6, 1.08))]
|
||||
places = [[*b, n, above, h] for n in (7, 365, 1465) for b in ((-1.53, -6.62, 7.0, 0.12), (-9.04, -5.11, 6.17, 0.0),
|
||||
(-5.39, -6.28, 6.09, 7.87), (-0.2, -0.3, 0.2, 0.3))
|
||||
for above in (0, 1) for h in (0.9, 0.74)]
|
||||
hs = [0, 0.05, 0.86, 1.06, 1.3, 2.85]
|
||||
pops = [[f, st] for st in (0, 5, 14) for f in range(-1, 20)]
|
||||
starts = [[first, n] for first in (-1, 0, 3, 13, 14, 15, 23) for n in (24, 12, 6) if first < n]
|
||||
got = Java.run({"caption": caps, "place": places, "captionh": hs, "pop": pops, "start": starts})
|
||||
self.close(got["caption"], [ap.caption_strokes(*c) for c in caps])
|
||||
want = []
|
||||
for pl in places:
|
||||
cx, top, ub = ap.caption_place(pl[:4], pl[4], bool(pl[5]), pl[6])
|
||||
want.append([cx, top, *ub])
|
||||
self.close(got["place"], want)
|
||||
self.close(got["captionh"], [ap.caption_h({"frames": [[["n", 0.2, 0, 0, h, 0]]] if h else [[]]}) for h in hs])
|
||||
self.close(got["pop"], [ap.caption_scale(f, st) for f, st in pops])
|
||||
def anim(first, n):
|
||||
return {"frames": [[["n", 0.2, 0, 0, 1, 0]] if first >= 0 and k >= first else [] for k in range(n)]}
|
||||
self.assertEqual(got["start"], [ap.caption_start(anim(*a)) for a in starts])
|
||||
self.assertEqual(ap.caption_start(anim(5, 24)), 5) # starts with the number ...
|
||||
self.assertEqual(ap.caption_start(anim(20, 24)), 14) # ... but shows for the last 10 at least
|
||||
self.assertEqual(ap.caption_scale(4, 5), 0.0)
|
||||
self.assertEqual(ap.caption_text(21), "21 days!")
|
||||
|
||||
def test_caption_only_for_streaks(self):
|
||||
"""Every streak animation is sized for a caption smaller than its own number; none other has "n"."""
|
||||
try:
|
||||
from routine.gui import anim_paint as ap
|
||||
except ImportError:
|
||||
self.skipTest("no Qt binding (PySide6 or PyQt6)")
|
||||
with open(os.path.join(ROOT, "shared", "animations.json")) as f:
|
||||
data = json.load(f)
|
||||
plain = data["animations"] + data.get("calm", []) + ([data["star"]] if data.get("star") else [])
|
||||
self.assertFalse(any(sh[0] == "n" for a in plain for fr in a["frames"] for sh in fr))
|
||||
st = data.get("streak") or {}
|
||||
for a in [a for g in st.get("sets", []) for a in g] + st.get("calm", []):
|
||||
tallest = max(sh[4] for fr in a["frames"] for sh in fr if sh[0] == "n")
|
||||
self.assertLess(ap.caption_h(a), tallest, a["name"])
|
||||
|
||||
def test_merge_keeps_streak_plays(self):
|
||||
a = model.new_day(SCHEDULE, TODAY)
|
||||
b = copy.deepcopy(a)
|
||||
a["states"]["am/teeth"] = {"s": "done", "t": 10}
|
||||
a["plays"] = [{"t": 10, "a": "x", "i": "am/teeth", "s": model.STREAK_SET, "n": 21}]
|
||||
b["states"]["am/tea"] = {"s": "done", "t": 11}
|
||||
b["plays"] = [{"t": 11, "a": "y", "i": "am/tea", "s": model.STREAK_CALM_SET, "n": 465},
|
||||
{"t": 12, "a": "z", "i": "am/run", "s": 0}]
|
||||
got = Java.run({"merge": [[a, b], [b, a]]})["merge"]
|
||||
self.assertEqual(got[0], model.merge(a, b))
|
||||
self.assertEqual(got[1], model.merge(b, a))
|
||||
|
||||
|
||||
def free_port():
|
||||
s = socket.socket()
|
||||
s.bind(("127.0.0.1", 0))
|
||||
port = s.getsockname()[1]
|
||||
s.close()
|
||||
return port
|
||||
|
||||
|
||||
class Server:
|
||||
"""A routine-server (server/routine_server.py, or another copy of it) on a spare local port."""
|
||||
|
||||
def __init__(self, source=None):
|
||||
self.dir = tempfile.mkdtemp(prefix="routine-server-")
|
||||
app = os.path.join(self.dir, "app")
|
||||
os.makedirs(app)
|
||||
if source is None:
|
||||
shutil.copy(os.path.join(ROOT, "server", "routine_server.py"), app)
|
||||
else:
|
||||
with open(os.path.join(app, "routine_server.py"), "w") as f:
|
||||
f.write(source)
|
||||
shutil.copy(os.path.join(ROOT, "routine", "model.py"), app)
|
||||
self.port = free_port()
|
||||
self.proc = subprocess.Popen([sys.executable, os.path.join(app, "routine_server.py"), "--port",
|
||||
str(self.port), "--data", os.path.join(self.dir, "data")],
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
for _ in range(100):
|
||||
try:
|
||||
urllib.request.urlopen(self.url + "/health", timeout=1)
|
||||
break
|
||||
except OSError:
|
||||
time.sleep(0.05)
|
||||
with open(os.path.join(self.dir, "data", "token")) as f:
|
||||
self.token = f.read().strip()
|
||||
|
||||
@property
|
||||
def url(self):
|
||||
return "http://127.0.0.1:%d" % self.port
|
||||
|
||||
def sync(self, body):
|
||||
req = urllib.request.Request(self.url + "/sync", json.dumps(body).encode(),
|
||||
{"Authorization": "Bearer " + self.token, "Content-Type": "application/json"})
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
return json.load(r)
|
||||
|
||||
def close(self):
|
||||
self.proc.terminate()
|
||||
self.proc.wait(5)
|
||||
shutil.rmtree(self.dir, ignore_errors=True)
|
||||
|
||||
|
||||
def old_server_source():
|
||||
"""server/routine_server.py as last committed before the streak base, if git has it."""
|
||||
for rev in ("HEAD:server/routine_server.py",):
|
||||
r = subprocess.run(["git", "-C", ROOT, "show", rev], capture_output=True, text=True)
|
||||
if r.returncode == 0 and "streaks" not in r.stdout:
|
||||
return r.stdout
|
||||
return None
|
||||
|
||||
|
||||
class Relay(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.srv = Server()
|
||||
|
||||
def tearDown(self):
|
||||
self.srv.close()
|
||||
|
||||
def doc(self, t, asof="2026-10-15"):
|
||||
return {"t": t, "asof": asof, "cheat_after": 7, "anims": True, "items": {"a/x": [12, 5, 0, 0]}}
|
||||
|
||||
def test_streak_base_relay(self):
|
||||
s = self.srv
|
||||
r = s.sync({"since": 0, "days": [], "schedule_rev": 0, "streaks": self.doc(100)}) # the desktop
|
||||
self.assertEqual(r["streaks_t"], 100)
|
||||
self.assertNotIn("streaks", r) # the desktop doesn't ask for it back
|
||||
r = s.sync({"since": 0, "days": [], "schedule_rev": 0, "streaks_t": 0}) # the R1
|
||||
self.assertEqual(r["streaks"], self.doc(100))
|
||||
r = s.sync({"since": 0, "days": [], "schedule_rev": 0, "streaks_t": 100}) # has it
|
||||
self.assertNotIn("streaks", r)
|
||||
r = s.sync({"since": 0, "days": [], "schedule_rev": 0}) # an old R1
|
||||
self.assertNotIn("streaks", r)
|
||||
s.sync({"since": 0, "days": [], "schedule_rev": 0, "streaks": self.doc(50, "2026-01-01")}) # older: kept out
|
||||
self.assertEqual(s.sync({"since": 0, "days": [], "streaks_t": 0})["streaks"]["t"], 100)
|
||||
for bad in ({"t": 200}, {"t": 200, "asof": "x", "items": {}}, {"t": "200", "asof": "2026-10-15", "items": {}},
|
||||
[1, 2], "x"):
|
||||
r = s.sync({"since": 0, "days": [], "streaks": bad, "streaks_t": 0})
|
||||
self.assertEqual(r["streaks"]["t"], 100)
|
||||
s.sync({"since": 0, "days": [], "streaks": self.doc(300)})
|
||||
self.assertEqual(s.sync({"since": 0, "days": [], "streaks_t": 100})["streaks"]["t"], 300)
|
||||
|
||||
def test_days_still_sync(self):
|
||||
day = model.new_day(SCHEDULE, dt.date.today())
|
||||
day["states"]["am/teeth"] = {"s": "done", "t": 5}
|
||||
r = self.srv.sync({"since": 0, "days": [day], "schedule_rev": 0, "streaks_t": 0})
|
||||
self.assertEqual(r["days"][0]["states"]["am/teeth"]["s"], "done")
|
||||
self.assertNotIn("streaks", r)
|
||||
self.assertNotIn("streaks_t", r)
|
||||
|
||||
|
||||
class EndToEnd(unittest.TestCase):
|
||||
"""The desktop's Syncer (Qt, no window) pushes a fake history and its streak base to a local
|
||||
server; the R1's side of it (the request MainActivity sends, then Streaks.ending) gets the
|
||||
desktop's number for every task ticked today."""
|
||||
|
||||
app = None # kept: processEvents does nothing once it's gone
|
||||
|
||||
def run_desktop(self, srv, store, cfg, sched, times=1):
|
||||
from routine.qt.QtCore import QCoreApplication
|
||||
from routine.sync import Syncer
|
||||
EndToEnd.app = QCoreApplication.instance() or QCoreApplication([])
|
||||
sy = Syncer(store, cfg, lambda: sched)
|
||||
sy.timer.stop()
|
||||
for _ in range(times):
|
||||
self.sync_once(sy)
|
||||
return sy
|
||||
|
||||
def sync_once(self, sy):
|
||||
sy.sync_now()
|
||||
t0 = time.time()
|
||||
while sy.busy and time.time() - t0 < 10:
|
||||
EndToEnd.app.processEvents()
|
||||
time.sleep(0.01)
|
||||
self.assertFalse(sy.busy)
|
||||
self.assertEqual(sy.last_error, "")
|
||||
|
||||
def setUp(self):
|
||||
try:
|
||||
import routine.qt.QtCore # noqa: F401
|
||||
except ImportError:
|
||||
self.skipTest("no Qt binding (PySide6 or PyQt6)")
|
||||
from routine.store import Store
|
||||
self.tmp = tempfile.mkdtemp(prefix="routine-e2e-")
|
||||
self.store = Store(os.path.join(self.tmp, "routine.db"))
|
||||
rng = random.Random(9)
|
||||
self.today = model.routine_date(SCHEDULE)
|
||||
n = 300
|
||||
self.days = []
|
||||
for k in range(n):
|
||||
d = self.today - dt.timedelta(days=n - 1 - k)
|
||||
day = model.new_day(SCHEDULE, d)
|
||||
for b in day["blocks"]:
|
||||
for it in b["items"]:
|
||||
if not it.get("hint") and (rng.random() < 0.97 or it["id"] == "am/teeth") and d != self.today:
|
||||
day["states"][it["id"]] = {"s": "done", "t": 1}
|
||||
self.days.append(day)
|
||||
for day in self.days: # what the server would hold: the last 60 days are pushed
|
||||
recent = day["date"] >= (dt.date.today() - dt.timedelta(days=59)).isoformat()
|
||||
self.store.put(day, dirty=recent)
|
||||
|
||||
def tearDown(self):
|
||||
if getattr(self, "store", None):
|
||||
self.store.db.close()
|
||||
shutil.rmtree(getattr(self, "tmp", ""), ignore_errors=True)
|
||||
|
||||
def r1_numbers(self, srv, cheat=7):
|
||||
r = srv.sync({"since": 0, "days": [], "schedule_rev": SCHEDULE["rev"], "streaks_t": 0})
|
||||
base = r.get("streaks")
|
||||
date = self.today.isoformat()
|
||||
cases, want = [], []
|
||||
for iid in ITEMS:
|
||||
if not on(self.days[-1], iid):
|
||||
continue
|
||||
held = ticked(r["days"], iid, date)
|
||||
cases.append({"days": held, "schedule": SCHEDULE, "item": iid, "date": date, "cheat": cheat, "base": base})
|
||||
want.append(model.streak_ending(ticked(self.days, iid, date), iid, date, cheat))
|
||||
return base, Java.run({"ending": cases})["ending"], want
|
||||
|
||||
@unittest.skipUnless(have_java(), "no JDK")
|
||||
def test_new_server(self):
|
||||
srv = Server()
|
||||
try:
|
||||
cfg = {"sync_url": srv.url, "sync_token": srv.token, "streak_anims": False, "cheat_day": True, "cheat_after": 7}
|
||||
sy = self.run_desktop(srv, self.store, cfg, SCHEDULE, times=2)
|
||||
self.assertEqual(sy._streaks_acked, sy._streaks[1]["t"]) # the server has it: not sent again
|
||||
base, got, want = self.r1_numbers(srv)
|
||||
self.assertIsNotNone(base)
|
||||
self.assertFalse(base["anims"])
|
||||
self.assertEqual(got, want)
|
||||
self.assertTrue(any(n > 60 for n in want))
|
||||
cfg["cheat_day"] = False # a setting changed: a new base
|
||||
t = sy._streaks[1]["t"]
|
||||
self.sync_once(sy)
|
||||
self.assertGreater(sy._streaks[1]["t"], t)
|
||||
base, got, want = self.r1_numbers(srv, cheat=0)
|
||||
self.assertEqual(base["cheat_after"], 0)
|
||||
self.assertEqual(got, want)
|
||||
finally:
|
||||
srv.close()
|
||||
|
||||
@unittest.skipUnless(have_java(), "no JDK")
|
||||
def test_old_server(self):
|
||||
src = old_server_source()
|
||||
if src is None:
|
||||
self.skipTest("no pre-streak server in git")
|
||||
srv = Server(src)
|
||||
try:
|
||||
cfg = {"sync_url": srv.url, "sync_token": srv.token}
|
||||
sy = self.run_desktop(srv, self.store, cfg, SCHEDULE, times=2)
|
||||
self.assertEqual(sy._streaks_acked, 0) # never acknowledged: still sent
|
||||
base, got, want = self.r1_numbers(srv)
|
||||
self.assertIsNone(base)
|
||||
for g, w in zip(got, want):
|
||||
self.assertIn(g, (0, w))
|
||||
finally:
|
||||
srv.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,319 @@
|
||||
"""Where the routine and history are kept (routine/storage.py, routine/paths.py), on fake data in
|
||||
temporary folders: moving a file safely, the first run, existing users, renamed config keys.
|
||||
Run: python3 -m unittest tests.test_storage"""
|
||||
import datetime as dt
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
from routine import model, paths, storage # noqa: E402
|
||||
from routine.store import Store # noqa: E402
|
||||
|
||||
FAKE = {"rev": 5, "dayStartsAt": 4, "blocks": [
|
||||
{"id": "am", "label": "Morning", "start": 7, "end": 9, "color": "#FFEEAA", "items": [
|
||||
{"id": "water", "label": "glass of water"},
|
||||
{"id": "plan", "label": "plan the day", "items": [
|
||||
{"id": "list", "label": "write a list", "items": [{"id": "short", "label": "keep it short"}]},
|
||||
{"id": "tip", "label": "five minutes is enough", "hint": True}]},
|
||||
{"id": "quiet", "label": "sit quietly", "calm": True}]},
|
||||
{"id": "pm", "label": "Evening", "start": 19, "end": 22, "color": "#CCBBFF", "items": [
|
||||
{"id": "tidy", "label": "tidy up"}]}]}
|
||||
|
||||
|
||||
class Base(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self._tmp = tempfile.TemporaryDirectory()
|
||||
self.tmp = self._tmp.name
|
||||
self.addCleanup(self._tmp.cleanup)
|
||||
p = mock.patch.object(paths, "DATA", os.path.join(self.tmp, "data"))
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
|
||||
def path(self, *parts):
|
||||
return os.path.join(self.tmp, *parts)
|
||||
|
||||
def write(self, path, text):
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w") as f:
|
||||
f.write(text)
|
||||
|
||||
def read(self, path):
|
||||
with open(path) as f:
|
||||
return f.read()
|
||||
|
||||
|
||||
class Move(Base):
|
||||
def test_moves_and_removes_the_original(self):
|
||||
src, dst = self.path("a", "schedule.json"), self.path("b", "deep", "schedule.json")
|
||||
self.write(src, json.dumps(FAKE))
|
||||
self.assertEqual(storage.move_file(src, dst, check=storage.check_schedule), "moved")
|
||||
self.assertFalse(os.path.exists(src))
|
||||
self.assertEqual(json.loads(self.read(dst)), FAKE)
|
||||
self.assertEqual(os.listdir(self.path("b", "deep")), ["schedule.json"]) # no .partial left behind
|
||||
|
||||
def test_same_place_does_nothing(self):
|
||||
src = self.path("a", "x.json")
|
||||
self.write(src, "{}")
|
||||
self.assertEqual(storage.move_file(src, src), "same")
|
||||
self.assertTrue(os.path.exists(src))
|
||||
|
||||
def test_no_original_only_changes_the_place(self):
|
||||
self.assertEqual(storage.move_file(self.path("a", "x.json"), self.path("b", "x.json")), "nothing")
|
||||
self.assertTrue(os.path.isdir(self.path("b")))
|
||||
|
||||
def test_existing_target_is_never_overwritten_without_asking(self):
|
||||
src, dst = self.path("a", "x.json"), self.path("b", "x.json")
|
||||
self.write(src, "mine")
|
||||
self.write(dst, "theirs")
|
||||
with self.assertRaises(storage.TargetTaken):
|
||||
storage.move_file(src, dst)
|
||||
self.assertEqual(self.read(src), "mine")
|
||||
self.assertEqual(self.read(dst), "theirs")
|
||||
|
||||
def test_use_that_one_leaves_both_alone(self):
|
||||
src, dst = self.path("a", "x.json"), self.path("b", "x.json")
|
||||
self.write(src, "mine")
|
||||
self.write(dst, "theirs")
|
||||
self.assertEqual(storage.move_file(src, dst, "use"), "used")
|
||||
self.assertEqual(self.read(src), "mine")
|
||||
self.assertEqual(self.read(dst), "theirs")
|
||||
|
||||
def test_use_that_one_refuses_a_broken_file(self):
|
||||
src, dst = self.path("a", "schedule.json"), self.path("b", "schedule.json")
|
||||
self.write(src, json.dumps(FAKE))
|
||||
self.write(dst, "not json")
|
||||
with self.assertRaises(storage.MoveError):
|
||||
storage.move_file(src, dst, "use", storage.check_schedule)
|
||||
self.assertEqual(json.loads(self.read(src)), FAKE)
|
||||
|
||||
def test_replace_keeps_theirs_beside(self):
|
||||
src, dst = self.path("a", "x.json"), self.path("b", "x.json")
|
||||
self.write(src, "mine")
|
||||
self.write(dst, "theirs")
|
||||
self.assertEqual(storage.move_file(src, dst, "replace"), "moved")
|
||||
self.assertFalse(os.path.exists(src))
|
||||
self.assertEqual(self.read(dst), "mine")
|
||||
kept = [f for f in os.listdir(self.path("b")) if f != "x.json"]
|
||||
self.assertEqual(len(kept), 1)
|
||||
self.assertTrue(kept[0].startswith("x.replaced-") and kept[0].endswith(".json"), kept)
|
||||
self.assertEqual(self.read(self.path("b", kept[0])), "theirs")
|
||||
|
||||
def test_failed_copy_leaves_the_original(self):
|
||||
src, dst = self.path("a", "x.json"), self.path("b", "x.json")
|
||||
self.write(src, "mine")
|
||||
|
||||
def broken(a, b):
|
||||
with open(b, "w") as f:
|
||||
f.write("mi") # a short write, then the disk fills up
|
||||
raise OSError(28, "No space left on device")
|
||||
with self.assertRaises(storage.MoveError):
|
||||
storage.move_file(src, dst, copy=broken)
|
||||
self.assertEqual(self.read(src), "mine")
|
||||
self.assertFalse(os.path.exists(dst))
|
||||
self.assertEqual(os.listdir(self.path("b")), [])
|
||||
|
||||
def test_copy_that_differs_is_caught(self):
|
||||
src, dst = self.path("a", "x.json"), self.path("b", "x.json")
|
||||
self.write(src, "mine")
|
||||
self.write(dst, "theirs")
|
||||
|
||||
def garbled(a, b):
|
||||
with open(b, "w") as f:
|
||||
f.write("mime")
|
||||
with self.assertRaises(storage.MoveError):
|
||||
storage.move_file(src, dst, "replace", copy=garbled)
|
||||
self.assertEqual(self.read(src), "mine")
|
||||
self.assertEqual(self.read(dst), "theirs") # theirs is back where it was
|
||||
self.assertEqual(os.listdir(self.path("b")), ["x.json"])
|
||||
|
||||
def test_failing_check_leaves_both(self):
|
||||
src, dst = self.path("a", "routine.db"), self.path("b", "routine.db")
|
||||
self.write(src, "not a database")
|
||||
with self.assertRaises(storage.MoveError):
|
||||
storage.move_file(src, dst, check=storage.check_db)
|
||||
self.assertEqual(self.read(src), "not a database")
|
||||
self.assertFalse(os.path.exists(dst))
|
||||
|
||||
def test_database_moves_closed_and_reopens(self):
|
||||
src, dst = self.path("a", "routine.db"), self.path("b", "routine.db")
|
||||
st = Store(src)
|
||||
day = model.new_day(FAKE, dt.date(2026, 3, 2))
|
||||
model.set_state(day, "am/water", model.DONE)
|
||||
st.put(day)
|
||||
st.set_meta("seq", 12)
|
||||
st.close()
|
||||
self.assertEqual(storage.move_file(src, dst, check=storage.check_db), "moved")
|
||||
self.assertFalse(os.path.exists(src))
|
||||
st.open(dst)
|
||||
self.assertEqual(st.path, dst)
|
||||
self.assertEqual(model.state(st.get("2026-03-02"), "am/water"), model.DONE)
|
||||
self.assertEqual(st.meta("seq"), "12")
|
||||
st.close()
|
||||
|
||||
def test_database_in_use_is_not_moved(self):
|
||||
src, dst = self.path("a", "routine.db"), self.path("b", "routine.db")
|
||||
st = Store(src)
|
||||
st.db.execute("PRAGMA journal_mode=WAL")
|
||||
st.put(model.new_day(FAKE, dt.date(2026, 3, 2)))
|
||||
with self.assertRaises(storage.MoveError): # still open, its -wal beside it
|
||||
storage.move_file(src, dst, check=storage.check_db)
|
||||
self.assertFalse(os.path.exists(dst))
|
||||
st.close() # close() folds the log in
|
||||
self.assertFalse(os.path.exists(src + "-wal"))
|
||||
self.assertEqual(storage.move_file(src, dst, check=storage.check_db), "moved")
|
||||
|
||||
|
||||
class FirstRun(Base):
|
||||
def cfg(self):
|
||||
return {"schedule_dir": self.path("sched"), "db_dir": self.path("hist")}
|
||||
|
||||
def template(self):
|
||||
p = self.path("repo", "schedule.json")
|
||||
self.write(p, json.dumps({"rev": 0, "dayStartsAt": 4, "blocks": [
|
||||
{"id": "t", "label": "Template", "start": 7, "end": 8, "color": "#FFFFFF", "items": [{"label": "x"}]}]}))
|
||||
return p
|
||||
|
||||
def test_fresh_start_copies_the_template(self):
|
||||
cfg = self.cfg()
|
||||
sch, how = storage.load_schedule(cfg, self.template())
|
||||
self.assertEqual(how, "template")
|
||||
self.assertEqual(sch["blocks"][0]["id"], "t")
|
||||
self.assertEqual(json.loads(self.read(paths.schedule_path(cfg))), sch)
|
||||
|
||||
def test_the_users_copy_wins_whatever_its_rev(self):
|
||||
cfg = self.cfg()
|
||||
mine = dict(FAKE, rev=0)
|
||||
self.write(paths.schedule_path(cfg), json.dumps(mine))
|
||||
tpl = self.template()
|
||||
with open(tpl) as f:
|
||||
t = json.load(f)
|
||||
t["rev"] = 99
|
||||
self.write(tpl, json.dumps(t))
|
||||
sch, how = storage.load_schedule(cfg, tpl)
|
||||
self.assertEqual((how, sch), ("yours", mine))
|
||||
self.assertEqual(model.load_schedule(paths.schedule_path(cfg), tpl), mine)
|
||||
|
||||
def history(self, cfg, days=3):
|
||||
st = Store(paths.db_path(cfg))
|
||||
for k in range(days):
|
||||
st.put(model.new_day(FAKE, dt.date(2026, 3, 1) + dt.timedelta(days=k)))
|
||||
st.close()
|
||||
|
||||
def test_existing_user_adopts_the_saved_copy_not_the_template(self):
|
||||
cfg = self.cfg()
|
||||
self.history(cfg)
|
||||
self.write(os.path.join(paths.DATA, "schedule.from-repo.json"), json.dumps(FAKE))
|
||||
sch, how = storage.load_schedule(cfg, self.template())
|
||||
self.assertEqual((how, sch), ("adopted", FAKE))
|
||||
self.assertEqual(json.loads(self.read(paths.schedule_path(cfg))), FAKE)
|
||||
self.assertTrue(os.path.exists(os.path.join(paths.DATA, "schedule.from-repo.json"))) # kept
|
||||
sch, how = storage.load_schedule(cfg, self.template()) # once only
|
||||
self.assertEqual(how, "yours")
|
||||
|
||||
def test_existing_user_without_a_saved_copy_gets_the_routine_back_from_the_history(self):
|
||||
cfg = self.cfg()
|
||||
self.history(cfg)
|
||||
sch, how = storage.load_schedule(cfg, self.template())
|
||||
self.assertEqual(how, "rebuilt")
|
||||
self.assertEqual(sch["rev"], FAKE["rev"])
|
||||
# the same tasks, ids, nesting, hints and calm marks: the history carries on
|
||||
day = dt.date(2026, 3, 9)
|
||||
self.assertEqual(model.snapshot(sch, day), model.snapshot(FAKE, day))
|
||||
plan = sch["blocks"][0]["items"][1]
|
||||
self.assertEqual([x["id"] for x in plan["items"]], ["list", "tip"])
|
||||
self.assertEqual(plan["items"][0]["items"][0]["id"], "short")
|
||||
self.assertTrue(plan["items"][1]["hint"])
|
||||
self.assertTrue(sch["blocks"][0]["items"][2]["calm"])
|
||||
|
||||
def test_rebuild_uses_the_most_recent_day(self):
|
||||
cfg = self.cfg()
|
||||
self.history(cfg)
|
||||
newer = json.loads(json.dumps(FAKE))
|
||||
newer["rev"] = 6
|
||||
newer["blocks"][1]["items"].append({"id": "read", "label": "read a little"})
|
||||
st = Store(paths.db_path(cfg))
|
||||
st.put(model.new_day(newer, dt.date(2026, 3, 10)))
|
||||
st.close()
|
||||
sch, how = storage.load_schedule(cfg, self.template())
|
||||
self.assertEqual(how, "rebuilt")
|
||||
self.assertEqual([x["id"] for x in sch["blocks"][1]["items"]], ["tidy", "read"])
|
||||
|
||||
def test_unreadable_copy_is_set_aside_not_lost(self):
|
||||
cfg = self.cfg()
|
||||
self.history(cfg)
|
||||
self.write(paths.schedule_path(cfg), "{ half a fi")
|
||||
sch, how = storage.load_schedule(cfg, self.template())
|
||||
self.assertEqual(how, "rebuilt") # not the template: there's a history
|
||||
aside = [f for f in os.listdir(self.path("sched")) if "unreadable" in f]
|
||||
self.assertEqual(len(aside), 1)
|
||||
self.assertEqual(self.read(self.path("sched", aside[0])), "{ half a fi")
|
||||
|
||||
def test_locations(self):
|
||||
self.assertEqual(paths.schedule_path({}), os.path.join(paths.DATA, "schedule.json"))
|
||||
self.assertEqual(paths.db_path({"db_dir": ""}), os.path.join(paths.DATA, "routine.db"))
|
||||
self.assertEqual(paths.db_path({"db_dir": self.path("x")}), self.path("x", "routine.db"))
|
||||
|
||||
|
||||
class Config(Base):
|
||||
def setUp(self):
|
||||
super().setUp()
|
||||
p = mock.patch.dict(paths.RENAMED, {"old_url": "sync_url", "old_token": "sync_token"})
|
||||
p.start()
|
||||
self.addCleanup(p.stop)
|
||||
|
||||
def test_renamed_keys_move_once(self):
|
||||
old, new = list(paths.RENAMED.items())[0]
|
||||
saved = {old: "value", "mode": "dark"}
|
||||
self.assertEqual(paths.migrate_config(saved), [old] + [])
|
||||
self.assertEqual(saved, {new: "value", "mode": "dark"})
|
||||
self.assertEqual(paths.migrate_config(saved), [])
|
||||
|
||||
def test_new_key_wins_over_an_old_one(self):
|
||||
old, new = list(paths.RENAMED.items())[0]
|
||||
saved = {old: "stale", new: "fresh"}
|
||||
paths.migrate_config(saved)
|
||||
self.assertEqual(saved, {new: "fresh"})
|
||||
|
||||
def test_load_config_writes_the_new_names_back(self):
|
||||
conf = self.path("conf", "config.json")
|
||||
old = list(paths.RENAMED)
|
||||
self.write(conf, json.dumps({old[0]: "http://example.invalid:1", old[1]: "fake-token"}))
|
||||
with mock.patch.object(paths, "CONFIG", conf), mock.patch.object(paths, "CONFIG_DIR", self.path("conf")), \
|
||||
mock.patch("sys.stderr"):
|
||||
cfg = paths.load_config()
|
||||
self.assertEqual(cfg["sync_url"], "http://example.invalid:1")
|
||||
self.assertEqual(cfg["sync_token"], "fake-token")
|
||||
on_disk = json.loads(self.read(conf))
|
||||
self.assertFalse(set(old) & set(on_disk))
|
||||
self.assertEqual(on_disk["sync_token"], "fake-token")
|
||||
|
||||
|
||||
class Template(unittest.TestCase):
|
||||
def test_the_shipped_template_shows_everything(self):
|
||||
with open(paths.SCHEDULE) as f:
|
||||
t = json.load(f)
|
||||
self.assertEqual(t["rev"], 0) # any routine of the user's own outranks it
|
||||
flat = []
|
||||
|
||||
def walk(items, depth):
|
||||
for x in items:
|
||||
flat.append((x, depth))
|
||||
walk(x.get("items", []), depth + 1)
|
||||
for b in t["blocks"]:
|
||||
walk(b["items"], 0)
|
||||
self.assertTrue(any(b.get("days") for b in t["blocks"]))
|
||||
self.assertTrue(any(x.get("days") for x, _ in flat))
|
||||
self.assertTrue(any(x.get("hint") for x, _ in flat))
|
||||
self.assertTrue(any(x.get("calm") for x, _ in flat))
|
||||
self.assertGreaterEqual(max(d for _, d in flat), 2)
|
||||
for k in range(7): # every day of the week makes a valid day
|
||||
model.new_day(t, dt.date(2026, 3, 1) + dt.timedelta(days=k))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,210 @@
|
||||
"""Streak logic in routine/model.py. Run: python3 -m unittest discover tests"""
|
||||
import datetime as dt
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from routine import model # noqa: E402
|
||||
|
||||
START = dt.date(2026, 1, 1)
|
||||
|
||||
|
||||
def mkdays(pattern, extra=None):
|
||||
"""One day per character, from START: D done, M missed (pending), S skipped, . item absent (off),
|
||||
H the item is a hint that day, P pending. A second item "b/y" is always done (and in block b)."""
|
||||
days = []
|
||||
for k, c in enumerate(pattern):
|
||||
d = (START + dt.timedelta(days=k)).isoformat()
|
||||
items = []
|
||||
states = {}
|
||||
if c != ".":
|
||||
items.append({"id": "a/x", "label": "x", "depth": 0, **({"hint": True} if c == "H" else {})})
|
||||
if c == "D":
|
||||
states["a/x"] = {"s": model.DONE, "t": 1}
|
||||
elif c == "S":
|
||||
states["a/x"] = {"s": model.SKIPPED, "t": 1}
|
||||
blocks = [{"id": "a", "label": "A", "start": 7, "end": 9, "color": "#fff", "items": items},
|
||||
{"id": "b", "label": "B", "start": 9, "end": 10, "color": "#fff",
|
||||
"items": [{"id": "b/y", "label": "y", "depth": 0}]}]
|
||||
states["b/y"] = {"s": model.DONE, "t": 1}
|
||||
days.append({"date": d, "rev": 1, "blocks": blocks, "states": states, "note": {"text": "", "t": 0}})
|
||||
return days
|
||||
|
||||
|
||||
def day(k):
|
||||
return (START + dt.timedelta(days=k)).isoformat()
|
||||
|
||||
|
||||
def run(pattern, cheat=model.CHEAT_AFTER, today=None):
|
||||
days = mkdays(pattern)
|
||||
today = today or day(len(pattern) - 1)
|
||||
return model.history(days, today, cheat).items["a/x"]
|
||||
|
||||
|
||||
def codes(st, n):
|
||||
m = {model.S_DONE: "D", model.S_MISS: "M", model.S_OFF: ".", model.S_CHEAT: "C", model.S_OPEN: "o"}
|
||||
return "".join(m[st.status_on(day(k))] for k in range(n))
|
||||
|
||||
|
||||
class Levels(unittest.TestCase):
|
||||
def test_levels(self):
|
||||
for k, n in enumerate(model.STREAK_LEVELS):
|
||||
self.assertEqual(model.streak_level(n), k)
|
||||
for n in (0, 1, 6, 8, 20, 101, 364, 366, 464, 466):
|
||||
self.assertIsNone(model.streak_level(n))
|
||||
top = len(model.STREAK_LEVELS) - 1
|
||||
for n in (465, 565, 1365):
|
||||
self.assertEqual(model.streak_level(n), top)
|
||||
|
||||
|
||||
class Streaks(unittest.TestCase):
|
||||
def test_plain_run(self):
|
||||
st = run("DDDMDD", cheat=0)
|
||||
self.assertEqual([r.length for r in st.runs], [3, 2])
|
||||
self.assertEqual(st.current, 2)
|
||||
self.assertEqual(st.longest, 3)
|
||||
self.assertEqual(codes(st, 6), "DDDMDD")
|
||||
|
||||
def test_off_days_neutral(self):
|
||||
st = run("DD..DH.D", cheat=0)
|
||||
self.assertEqual(len(st.runs), 1)
|
||||
self.assertEqual(st.current, 4)
|
||||
self.assertEqual(st.runs[0].start, day(0))
|
||||
self.assertEqual(st.runs[0].end, day(7))
|
||||
|
||||
def test_skip_is_miss(self):
|
||||
st = run("DDSDD", cheat=0)
|
||||
self.assertEqual([r.length for r in st.runs], [2, 2])
|
||||
|
||||
def test_today_pending_neutral(self):
|
||||
st = run("DDDP", cheat=0)
|
||||
self.assertEqual(st.current, 3)
|
||||
self.assertEqual(st.status_on(day(3)), model.S_OPEN)
|
||||
# the same day seen from tomorrow is a miss
|
||||
st = run("DDDPP", cheat=0)
|
||||
self.assertEqual(st.current, 0)
|
||||
self.assertEqual(st.status_on(day(3)), model.S_MISS)
|
||||
|
||||
def test_today_skipped_is_miss(self):
|
||||
st = run("DDDS", cheat=0)
|
||||
self.assertEqual(st.current, 0)
|
||||
|
||||
def test_cheat_needs_n_days(self):
|
||||
st = run("DDDDDDMD", cheat=7) # 6 done: none held
|
||||
self.assertEqual([r.length for r in st.runs], [6, 1])
|
||||
st = run("DDDDDDDMD", cheat=7) # 7 done: one held, used
|
||||
self.assertEqual(len(st.runs), 1)
|
||||
self.assertEqual(st.current, 8)
|
||||
self.assertEqual(st.runs[0].cheats, [day(7)])
|
||||
self.assertEqual(st.status_on(day(7)), model.S_CHEAT)
|
||||
self.assertEqual(st.run_of[day(7)], 0)
|
||||
|
||||
def test_cheat_counts_from_last_cheat(self):
|
||||
# 7 done, cheat, 6 done, miss: no second cheat held yet
|
||||
st = run("DDDDDDD" + "M" + "DDDDDD" + "M" + "D", cheat=7)
|
||||
self.assertEqual([r.length for r in st.runs], [13, 1])
|
||||
# 7 done, cheat, 7 done, miss: the second one is held
|
||||
st = run("DDDDDDD" + "M" + "DDDDDDD" + "M" + "D", cheat=7)
|
||||
self.assertEqual([r.length for r in st.runs], [15])
|
||||
self.assertEqual(len(st.runs[0].cheats), 2)
|
||||
|
||||
def test_at_most_one_held(self):
|
||||
st = run("D" * 20 + "MDMD", cheat=7) # 20 done hold one; the second miss ends it
|
||||
self.assertEqual([r.length for r in st.runs], [21, 1])
|
||||
|
||||
def test_two_misses_no_rescue(self):
|
||||
st = run("DDDDDDD" + "MM" + "DD", cheat=7)
|
||||
self.assertEqual([r.length for r in st.runs], [7, 2])
|
||||
self.assertEqual(st.runs[0].cheats, [])
|
||||
self.assertEqual(codes(st, 11), "DDDDDDDMMDD")
|
||||
self.assertNotIn(day(7), st.run_of)
|
||||
|
||||
def test_two_misses_across_off_days(self):
|
||||
st = run("DDDDDDD" + "M..M" + "D", cheat=7)
|
||||
self.assertEqual([r.length for r in st.runs], [7, 1])
|
||||
self.assertEqual(st.status_on(day(7)), model.S_MISS)
|
||||
|
||||
def test_trailing_cheat_alive(self):
|
||||
st = run("DDDDDDD" + "M" + "P", cheat=7) # yesterday missed, today pending
|
||||
self.assertEqual(st.current, 7)
|
||||
self.assertEqual(st.status_on(day(7)), model.S_CHEAT)
|
||||
self.assertEqual(st.runs[0].last(), day(7))
|
||||
self.assertEqual(st.runs[0].end, day(6))
|
||||
|
||||
def test_cheat_off(self):
|
||||
st = run("DDDDDDDMD", cheat=0)
|
||||
self.assertEqual([r.length for r in st.runs], [7, 1])
|
||||
st = run("DDDDDDDMD", cheat=None)
|
||||
self.assertEqual([r.length for r in st.runs], [7, 1])
|
||||
|
||||
def test_totals(self):
|
||||
st = run("DDDDDDDMDD.P", cheat=7)
|
||||
done, sched, pct = st.totals()
|
||||
self.assertEqual((done, sched), (9, 10)) # cheat day scheduled, not done; today open not counted
|
||||
self.assertAlmostEqual(pct, 90.0)
|
||||
self.assertEqual(st.totals(day(8), day(9))[:2], (2, 2))
|
||||
|
||||
def test_ranges(self):
|
||||
st = run("DDDMDDDDDMD", cheat=0)
|
||||
self.assertEqual(len(st.runs_in(day(4), day(6))), 1)
|
||||
self.assertEqual(st.longest_run(None, day(3)).length, 3)
|
||||
self.assertEqual(st.longest_run().length, 5)
|
||||
|
||||
def test_block(self):
|
||||
h = model.history(mkdays("DMD"), day(2), 0)
|
||||
b = h.blocks["a"]
|
||||
self.assertEqual([b.levels[day(k)] for k in range(3)], [model.LEVEL_ALL, model.LEVEL_NONE, model.LEVEL_ALL])
|
||||
self.assertEqual([r.length for r in b.runs], [1, 1])
|
||||
self.assertEqual(h.blocks["b"].current, 3)
|
||||
self.assertEqual(h.items["b/y"].current, 3)
|
||||
self.assertEqual(h.items["a/x"].label, "x")
|
||||
|
||||
|
||||
class Ending(unittest.TestCase):
|
||||
def test_streak_ending(self):
|
||||
days = mkdays("DDDDDDDP")
|
||||
self.assertEqual(model.streak_ending(days, "a/x", day(7)), 0) # not ticked yet
|
||||
days[7]["states"]["a/x"] = {"s": model.DONE, "t": 2}
|
||||
self.assertEqual(model.streak_ending(days, "a/x", day(7)), 8)
|
||||
self.assertEqual(model.streak_ending(days, "a/x", day(6)), 7) # later days don't count
|
||||
|
||||
def test_ending_past_gap(self):
|
||||
days = mkdays("DDDMDDD") # tick the gap on day 3
|
||||
days[3]["states"]["a/x"] = {"s": model.DONE, "t": 2}
|
||||
self.assertEqual(model.streak_ending(days, "a/x", day(3)), 4)
|
||||
|
||||
def test_ending_after_cheat(self):
|
||||
days = mkdays("DDDDDDDMP")
|
||||
days[8]["states"]["a/x"] = {"s": model.DONE, "t": 2}
|
||||
self.assertEqual(model.streak_ending(days, "a/x", day(8), 7), 8)
|
||||
self.assertEqual(model.streak_ending(days, "a/x", day(8), 0), 1)
|
||||
|
||||
|
||||
class Plays(unittest.TestCase):
|
||||
def test_streak_play_counts_as_tick(self):
|
||||
d = mkdays("P")[0]
|
||||
model.set_state(d, "a/x", model.DONE)
|
||||
model.add_play(d, "medal", "a/x", model.STREAK_SET, 7)
|
||||
self.assertEqual(model.ticks(d), 1)
|
||||
self.assertEqual(d["plays"][0]["n"], 7)
|
||||
|
||||
|
||||
class Speed(unittest.TestCase):
|
||||
def test_three_years_sixty_tasks(self):
|
||||
import time
|
||||
days = []
|
||||
for k in range(3 * 365):
|
||||
items = [{"id": "a/t%d" % n, "label": "t%d" % n, "depth": 0} for n in range(60)]
|
||||
states = {it["id"]: {"s": model.DONE, "t": 1} for it in items if (k + int(it["id"][3:])) % 9}
|
||||
days.append({"date": (START + dt.timedelta(days=k)).isoformat(), "rev": 1,
|
||||
"blocks": [{"id": "a", "label": "A", "start": 7, "end": 9, "color": "#fff", "items": items}],
|
||||
"states": states, "note": {"text": "", "t": 0}})
|
||||
t = time.time()
|
||||
h = model.history(days, days[-1]["date"])
|
||||
self.assertLess(time.time() - t, 2.0)
|
||||
self.assertEqual(len(h.items), 60)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,167 @@
|
||||
"""routine/system.py (what differs on Linux and macOS, asked of either from here) and routine/crash.py
|
||||
(unhandled errors logged without routine contents). Run: python3 -m unittest tests.test_system"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
from unittest import mock
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
sys.path.insert(0, ROOT)
|
||||
from routine import crash, system # noqa: E402
|
||||
|
||||
HOME = {"HOME": "/home/friend"}
|
||||
|
||||
|
||||
class Places(unittest.TestCase):
|
||||
def test_linux(self):
|
||||
self.assertEqual(system.data_dir("linux", HOME), "/home/friend/.local/share/routine")
|
||||
self.assertEqual(system.config_dir("linux", HOME), "/home/friend/.config/routine")
|
||||
self.assertEqual(system.log_dir("linux", HOME), "/home/friend/.local/state/routine")
|
||||
self.assertEqual(system.log_dir("linux", dict(HOME, XDG_STATE_HOME="/st")), "/st/routine")
|
||||
|
||||
def test_mac(self):
|
||||
sup = "/home/friend/Library/Application Support/Routine"
|
||||
self.assertEqual(system.data_dir("darwin", HOME), sup)
|
||||
self.assertEqual(system.config_dir("darwin", HOME), sup)
|
||||
self.assertEqual(system.log_dir("darwin", HOME), "/home/friend/Library/Logs/Routine")
|
||||
|
||||
def test_routine_home_wins_everywhere(self):
|
||||
env = dict(HOME, ROUTINE_HOME="/scratch/x")
|
||||
for plat in ("linux", "darwin"):
|
||||
self.assertEqual(system.data_dir(plat, env), "/scratch/x")
|
||||
self.assertEqual(system.config_dir(plat, env), "/scratch/x")
|
||||
self.assertEqual(system.log_dir(plat, env), "/scratch/x/logs")
|
||||
|
||||
def test_paths_uses_them(self):
|
||||
from routine import paths
|
||||
self.assertEqual(paths.DATA, system.data_dir())
|
||||
self.assertEqual(paths.CONFIG, os.path.join(system.config_dir(), "config.json"))
|
||||
|
||||
|
||||
class Features(unittest.TestCase):
|
||||
def test_mac_vs_linux(self):
|
||||
self.assertTrue(system.native_frame("darwin") and system.global_menubar("darwin"))
|
||||
self.assertFalse(system.native_frame("linux") or system.global_menubar("linux"))
|
||||
self.assertFalse(system.sync_supported("darwin"))
|
||||
self.assertTrue(system.sync_supported("linux"))
|
||||
|
||||
def test_sound_players(self):
|
||||
self.assertEqual(system.sound_players("darwin"), ["afplay"])
|
||||
self.assertEqual(system.sound_players("linux"), ["pw-play", "paplay"])
|
||||
|
||||
def test_audio_env_linux_only(self):
|
||||
env = {}
|
||||
system.audio_env("darwin", env)
|
||||
self.assertEqual(env, {})
|
||||
system.audio_env("linux", env)
|
||||
self.assertEqual(env, {"QT_AUDIO_BACKEND": "pulseaudio"})
|
||||
env = {"QT_AUDIO_BACKEND": "pipewire"}
|
||||
system.audio_env("linux", env)
|
||||
self.assertEqual(env["QT_AUDIO_BACKEND"], "pipewire") # the user's choice wins
|
||||
|
||||
def test_no_gsettings_off_linux(self):
|
||||
run = mock.Mock(side_effect=AssertionError("ran a command"))
|
||||
self.assertEqual(system.gnome_setting("a.b", "c", "darwin", run), "")
|
||||
env = {}
|
||||
system.cursor_env("darwin", env, run)
|
||||
self.assertEqual(env, {})
|
||||
run.assert_not_called()
|
||||
|
||||
def test_gsettings_on_linux(self):
|
||||
run = mock.Mock(return_value=subprocess.CompletedProcess([], 0, stdout="'Adwaita'\n"))
|
||||
env = {"XCURSOR_SIZE": "32"}
|
||||
system.cursor_env("linux", env, run)
|
||||
self.assertEqual(env, {"XCURSOR_SIZE": "32", "XCURSOR_THEME": "Adwaita"})
|
||||
self.assertEqual(run.call_count, 1) # the size was set already
|
||||
missing = mock.Mock(side_effect=FileNotFoundError)
|
||||
self.assertEqual(system.gnome_setting("a.b", "c", "linux", missing), "")
|
||||
|
||||
def test_shortcuts(self):
|
||||
self.assertEqual(system.shortcut("history", "linux"), "Ctrl+H")
|
||||
self.assertEqual(system.shortcut("history", "darwin"), "Ctrl+Y") # ⌘H hides the app
|
||||
|
||||
def test_instance_name(self):
|
||||
self.assertEqual(system.instance_name(None), system.APP_ID)
|
||||
a, b = system.instance_name("/tmp/a/very/long/path" * 10), system.instance_name("/tmp/b")
|
||||
self.assertNotEqual(a, b)
|
||||
self.assertNotIn("/", a)
|
||||
self.assertLess(len(a), 40)
|
||||
|
||||
def test_mac_app_name_is_quiet_off_a_mac(self):
|
||||
self.assertFalse(system.mac_app_name("Routine", "linux"))
|
||||
|
||||
def test_describe(self):
|
||||
self.assertIn("Python", system.describe())
|
||||
|
||||
|
||||
def raise_and_handle(exc):
|
||||
try:
|
||||
raise exc
|
||||
except BaseException:
|
||||
return crash.handle(*sys.exc_info())
|
||||
|
||||
|
||||
class Crash(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.mkdtemp(prefix="routine-crash-")
|
||||
self.notices = []
|
||||
crash.reset()
|
||||
crash._state.update(dir=self.tmp, notify=self.notices.append)
|
||||
self.err = mock.patch.object(sys, "stderr", open(os.devnull, "w"))
|
||||
self.err.start()
|
||||
|
||||
def tearDown(self):
|
||||
sys.stderr.close()
|
||||
self.err.stop()
|
||||
crash._state.update(dir=None, notify=None)
|
||||
|
||||
def log(self):
|
||||
with open(os.path.join(self.tmp, crash.LOG_NAME)) as f:
|
||||
return f.read()
|
||||
|
||||
def test_message_kept_for_code_errors_left_out_for_others(self):
|
||||
self.assertTrue(raise_and_handle(AttributeError("'QHelpEvent' object has no attribute 'position'")))
|
||||
self.assertTrue(raise_and_handle(KeyError("my secret task")))
|
||||
self.assertTrue(raise_and_handle(ValueError("dear diary")))
|
||||
text = self.log()
|
||||
self.assertIn("has no attribute 'position'", text)
|
||||
self.assertNotIn("my secret task", text)
|
||||
self.assertNotIn("dear diary", text)
|
||||
self.assertIn("KeyError: (message left out", text)
|
||||
self.assertIn("Traceback", text)
|
||||
self.assertIn("Routine ", text)
|
||||
|
||||
def test_once_per_distinct_error(self):
|
||||
for _ in range(3):
|
||||
raise_and_handle(TypeError("x")) # the same line each time: one error
|
||||
self.assertEqual(len(self.notices), 1)
|
||||
self.assertEqual(self.log().count("TypeError"), 1)
|
||||
raise_and_handle(NameError("y"))
|
||||
self.assertEqual(len(self.notices), 2)
|
||||
self.assertEqual(self.notices[0], os.path.join(self.tmp, crash.LOG_NAME))
|
||||
|
||||
def test_threads_log_without_a_notice(self):
|
||||
crash.handle(*_exc_info(RuntimeError("z")), gui=False)
|
||||
self.assertEqual(self.notices, [])
|
||||
self.assertIn("RuntimeError", self.log())
|
||||
|
||||
def test_log_rolls_over(self):
|
||||
path = os.path.join(self.tmp, crash.LOG_NAME)
|
||||
with open(path, "w") as f:
|
||||
f.write("x" * (crash.MAX_BYTES + 1))
|
||||
raise_and_handle(IndexError("i"))
|
||||
self.assertTrue(os.path.exists(path + ".1"))
|
||||
self.assertLess(os.path.getsize(path), 10_000)
|
||||
|
||||
|
||||
def _exc_info(exc):
|
||||
try:
|
||||
raise exc
|
||||
except BaseException:
|
||||
return sys.exc_info()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,71 @@
|
||||
"""The Statistics / Journal figures in routine/tally.py. Run: python3 -m unittest discover tests"""
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
||||
from routine import model, tally # noqa: E402
|
||||
|
||||
|
||||
def day(date, items, done=(), skipped=(), note=""):
|
||||
"""items: {block id: [(item id, depth)]}; ids given whole ("a/x")."""
|
||||
blocks = [{"id": b, "label": b.upper(), "start": 7, "end": 9, "color": "#fff",
|
||||
"items": [{"id": i, "label": i.split("/")[-1], "depth": d} for i, d in its]}
|
||||
for b, its in items.items()]
|
||||
states = {i: {"s": model.DONE, "t": 1} for i in done}
|
||||
states.update({i: {"s": model.SKIPPED, "t": 1} for i in skipped})
|
||||
return {"date": date, "blocks": blocks, "states": states, "note": {"text": note, "t": 1}}
|
||||
|
||||
|
||||
SCHEDULE = {"blocks": [{"id": "a", "label": "A", "start": 7, "end": 9, "color": "#fff",
|
||||
"items": [{"label": "x", "items": [{"label": "y"}]}, {"label": "z", "hint": True}]},
|
||||
{"id": "c", "label": "C", "start": 9, "end": 10, "color": "#000", "items": [{"label": "w"}]}]}
|
||||
|
||||
|
||||
class TreeTest(unittest.TestCase):
|
||||
def test_order_and_removed(self):
|
||||
days = [day("2026-01-01", {"a": [("a/x", 0), ("a/gone", 0), ("a/x/y", 1)], "b": [("b/old", 0)],
|
||||
"c": [("c/w", 0)]}),
|
||||
day("2026-01-02", {"a": [("a/x", 0), ("a/x/y", 1)], "c": [("c/w", 0)]})]
|
||||
h = model.history(days, "2026-01-03")
|
||||
tree = tally.task_tree(SCHEDULE, h, days, "2026-01-01", "2026-01-02")
|
||||
self.assertEqual([b["id"] for b in tree], ["a", "b", "c"]) # the removed block keeps its place
|
||||
self.assertTrue(tree[1]["removed"])
|
||||
self.assertEqual([it["id"] for it in tree[0]["items"]], ["a/x", "a/gone", "a/x/y"])
|
||||
self.assertEqual([it["removed"] for it in tree[0]["items"]], [False, True, False])
|
||||
# only tasks with a record in the range
|
||||
tree = tally.task_tree(SCHEDULE, h, days, "2026-01-02", "2026-01-02")
|
||||
self.assertEqual([[it["id"] for it in b["items"]] for b in tree], [["a/x", "a/x/y"], ["c/w"]])
|
||||
|
||||
|
||||
class FiguresTest(unittest.TestCase):
|
||||
def test_next_level(self):
|
||||
self.assertEqual(tally.next_level(0), (7, 7))
|
||||
self.assertEqual(tally.next_level(7), (21, 14))
|
||||
self.assertEqual(tally.next_level(365), (465, 100))
|
||||
self.assertEqual(tally.next_level(470), (565, 95))
|
||||
|
||||
def test_day_score_and_lists(self):
|
||||
d = day("2026-01-01", {"a": [("a/x", 0), ("a/x/y", 1)], "c": [("c/w", 0)]}, done=["a/x"], skipped=["c/w"])
|
||||
d["blocks"][0]["items"].append({"id": "a/h", "label": "h", "depth": 0, "hint": True})
|
||||
self.assertEqual(tally.day_score(d, "2026-01-05"), (1, 3, 100 / 3))
|
||||
got, rest = tally.day_lists(d, "2026-01-05")
|
||||
self.assertEqual([(b["id"], [i["id"] for i, _ in its]) for b, its in got], [("a", ["a/x"])])
|
||||
self.assertEqual([(b["id"], [(i["id"], s) for i, s in its]) for b, its in rest],
|
||||
[("a", [("a/x/y", model.PENDING)]), ("c", [("c/w", model.SKIPPED)])])
|
||||
self.assertEqual(tally.day_score(day("2026-01-01", {}), "2026-01-05"), (0, 0, None))
|
||||
|
||||
def test_summary(self):
|
||||
days = [day("2026-01-%02d" % n, {"a": [("a/x", 0)]}, done=["a/x"] if n != 4 else []) for n in range(1, 11)]
|
||||
h = model.history(days, "2026-01-10", cheat_after=2)
|
||||
s = tally.summary(h, days, "2026-01-01", "2026-01-10", "2026-01-10")
|
||||
self.assertEqual((s["days"], s["counted"], s["done"], s["scheduled"]), (10, 9, 9, 10))
|
||||
self.assertEqual((s["cheats"], s["cheat_tasks"], s["perfect"]), (1, 1, 8))
|
||||
self.assertEqual(s["best"][0][1].length, 9)
|
||||
self.assertEqual(s["going"][0][1], 9)
|
||||
s = tally.summary(h, days, "2026-01-01", "2026-01-03", "2026-01-10")
|
||||
self.assertEqual((s["done"], s["scheduled"], s["cheats"], s["best"]), (3, 3, 0, [])) # no run ends in it
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in New Issue
Block a user