Files
matrix/now-playing/test_lotus_now_playing.py
T
jared 3a0a4e15a8
Lint / Shell (shellcheck) (push) Successful in 10s
Lint / JS (eslint) (push) Successful in 7s
Lint / No Hookshot webhook IDs in README (push) Successful in 6s
Lint / No secrets in webhook configs (push) Successful in 6s
Lint / Landing page is rendered (matrix (push) Successful in 7s
Lint / Python (ruff) (push) Successful in 11s
Lint / Python deps (pip-audit) (push) Successful in 36s
Lint / Secret scan (gitleaks) (push) Successful in 5s
now-playing: Navidrome "Listening to" service for Lotus Chat (cinny #491) (#68)
2026-11-16 23:51:07 -05:00

174 lines
7.5 KiB
Python

"""Tests for lotus_now_playing.py. Run: python3 -m unittest now-playing/test_lotus_now_playing.py"""
import json
import os
import sys
import tempfile
import unittest
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
import lotus_now_playing as np # noqa: E402
def nd(entries, status="ok"):
return {"subsonic-response": {"status": status, "nowPlaying": {"entry": entries}}}
def entry(user, title="Song", minutes=0, state="playing", cover="al-1", **kw):
e = {"username": user, "title": title, "artist": "Band", "album": "LP", "duration": 200,
"minutesAgo": minutes, "state": state, "coverArt": cover, "playerName": "DN", "positionMs": 1000}
e.update(kw)
return e
class ParseTests(unittest.TestCase):
def test_basic_and_ignored_users(self):
out = np.parse_now_playing(nd([entry("jared"), entry("droppedneedle")]), ("droppedneedle",))
self.assertEqual(list(out), ["jared"])
self.assertEqual(out["jared"]["artist"], "Band")
self.assertEqual(out["jared"]["durationS"], 200)
def test_prefers_display_artist(self):
out = np.parse_now_playing(nd([entry("a", displayArtist="Band feat. X")]))
self.assertEqual(out["a"]["artist"], "Band feat. X")
def test_newest_session_wins(self):
out = np.parse_now_playing(nd([entry("a", "Old", minutes=5), entry("a", "New", minutes=0)]))
self.assertEqual(out["a"]["title"], "New")
def test_drops_stopped_untitled_and_stale(self):
out = np.parse_now_playing(nd([
entry("a", state="stopped"),
entry("b", title=""),
entry("c", minutes=90, positionMs=0),
entry("d", state="paused"),
]))
self.assertEqual(list(out), ["d"])
def test_single_entry_object_and_empty(self):
self.assertEqual(list(np.parse_now_playing(nd(entry("a")))), ["a"])
self.assertEqual(np.parse_now_playing({"subsonic-response": {"status": "ok"}}), {})
def test_error_raises(self):
with self.assertRaises(ValueError):
np.parse_now_playing({"subsonic-response": {"status": "failed", "error": {"message": "nope"}}})
class MappingTests(unittest.TestCase):
def test_email_on_domain(self):
user = {"threepids": [{"medium": "email", "address": "Tyler@LotusGuild.org"}]}
self.assertEqual(np.username_from_admin_user(user, "lotusguild.org"), "tyler")
def test_other_domain_ignored(self):
user = {"threepids": [{"medium": "email", "address": "x@gmail.com"}]}
self.assertIsNone(np.username_from_admin_user(user, "lotusguild.org"))
def test_legacy_external_id(self):
user = {"external_ids": [{"auth_provider": "https://auth.lotusguild.org", "external_id": "cole"}]}
self.assertEqual(np.username_from_admin_user(user, "lotusguild.org"), "cole")
def test_opaque_uuid_is_not_a_username(self):
user = {"external_ids": [
{"auth_provider": "oidc-authelia", "external_id": "b546660f-371c-45de-812c-bbae0e615148"},
{"auth_provider": "https://auth.lotusguild.org", "external_id": "b546660f-371c-45de-812c-bbae0e615148"},
]}
self.assertIsNone(np.username_from_admin_user(user, "lotusguild.org"))
def test_parse_ids(self):
ids = np.parse_ids("@a:hs, @b:other,@a:hs,junk,@c:hs", "hs")
self.assertEqual(ids, ["@a:hs", "@c:hs"])
self.assertEqual(len(np.parse_ids(",".join(f"@u{i}:hs" for i in range(80)), "hs")), np.MAX_IDS)
class FakeHttp:
def __init__(self):
self.calls = []
self.now_playing = nd([entry("jared", cover="al-9"), entry("jeff", cover="al-7")])
self.admin = {
"@jared:hs": {"threepids": [{"medium": "email", "address": "jared@lotusguild.org"}]},
"@nomail:hs": {"threepids": []},
}
self.openid = {"good": "@jared:hs", "foreign": "@x:elsewhere"}
def __call__(self, url, headers, timeout):
self.calls.append(url)
if "/rest/getNowPlaying" in url:
return 200, json.dumps(self.now_playing).encode(), "application/json"
if "/openid/userinfo" in url:
tok = url.split("access_token=")[1]
if tok in self.openid:
return 200, json.dumps({"sub": self.openid[tok]}).encode(), "application/json"
return 401, b"{}", "application/json"
if "/_synapse/admin/v2/users/" in url:
mxid = url.rsplit("/", 1)[1].replace("%40", "@").replace("%3A", ":")
if mxid in self.admin:
return 200, json.dumps(self.admin[mxid]).encode(), "application/json"
return 404, b"{}", "application/json"
raise AssertionError(url)
class ServiceTests(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
users = os.path.join(self.tmp.name, "users.json")
with open(users, "w") as f:
json.dump({"@bigmanjeff:hs": "jeff"}, f)
self.http = FakeHttp()
self.svc = np.Service({
"server_name": "hs", "email_domain": "lotusguild.org", "synapse": "http://syn",
"matrix_token": "admin", "nd_url": "http://nd", "nd_user": "svc", "nd_password": "pw",
"ignore_users": ("droppedneedle",), "state_dir": self.tmp.name, "users_file": users, "poll_s": 10,
}, http_get=self.http)
self.svc.poll_once()
def tearDown(self):
self.tmp.cleanup()
def test_token_check_and_cache(self):
self.assertEqual(self.svc.verify_token("good"), "@jared:hs")
self.assertEqual(self.svc.verify_token("good"), "@jared:hs")
self.assertEqual(sum("/openid/" in c for c in self.http.calls), 1)
self.assertIsNone(self.svc.verify_token("bad"))
self.assertIsNone(self.svc.verify_token("foreign"))
self.assertIsNone(self.svc.verify_token(""))
def test_opt_in_required(self):
self.assertEqual(self.svc.users_view(["@jared:hs", "@bigmanjeff:hs"]), {})
self.svc.optins.set("@jared:hs", True)
view = self.svc.users_view(["@jared:hs", "@bigmanjeff:hs"])
self.assertEqual(list(view), ["@jared:hs"])
self.assertEqual(view["@jared:hs"]["cover"], "/now-playing/v1/cover/al-9")
def test_override_mapping(self):
self.svc.optins.set("@bigmanjeff:hs", True)
self.assertIn("@bigmanjeff:hs", self.svc.users_view(["@bigmanjeff:hs"]))
def test_opt_in_persists_and_opt_out(self):
self.svc.optins.set("@jared:hs", True)
reloaded = np.OptIns(os.path.join(self.tmp.name, "state.json"))
self.assertTrue(reloaded.get("@jared:hs"))
self.svc.optins.set("@jared:hs", False)
self.assertEqual(self.svc.users_view(["@jared:hs"]), {})
def test_me_view(self):
me = self.svc.me_view("@jared:hs")
self.assertEqual((me["share"], me["linked"]), (False, True))
self.assertEqual(me["playing"]["title"], "Song")
self.assertEqual(self.svc.me_view("@nomail:hs"), {"share": False, "linked": False, "playing": None})
def test_cover_allow_list(self):
self.assertFalse(self.svc.cover_allowed("al-9")) # nobody opted in yet
self.svc.optins.set("@jared:hs", True)
self.assertTrue(self.svc.cover_allowed("al-9"))
self.assertFalse(self.svc.cover_allowed("al-7")) # jeff hasn't opted in
self.assertFalse(self.svc.cover_allowed("al-unknown"))
def test_subsonic_url_never_contains_password(self):
url = self.svc.subsonic_url("getNowPlaying")
self.assertNotIn("pw", url.split("?")[1].split("&t=")[0])
self.assertIn("u=svc", url)
self.assertNotIn("p=", url)
if __name__ == "__main__":
unittest.main()