252 lines
11 KiB
Python
252 lines
11 KiB
Python
"""
|
|
Tests for notifications through Apprise (v2.14.0, ADR-074)
|
|
|
|
Most tests replace the Apprise send with a recorder. One sends for real
|
|
through Apprise to a local HTTP server (json://), to check the wiring.
|
|
"""
|
|
|
|
import json
|
|
import sqlite3
|
|
import threading
|
|
from http.server import BaseHTTPRequestHandler, HTTPServer
|
|
|
|
import pytest
|
|
|
|
from starpunk import backfeed, create_app, notifications, syndication
|
|
from starpunk.backfeed import Harvest, Response
|
|
from starpunk.database import get_db
|
|
from starpunk.notes import create_note
|
|
|
|
SITE = "https://blog.example.com"
|
|
|
|
|
|
@pytest.fixture
|
|
def sent(monkeypatch):
|
|
messages = []
|
|
|
|
def deliver(targets, title, body):
|
|
messages.append({"targets": targets, "title": title, "body": body})
|
|
return True, ""
|
|
|
|
monkeypatch.setattr(notifications, "_deliver", deliver)
|
|
return messages
|
|
|
|
|
|
@pytest.fixture
|
|
def app(tmp_path):
|
|
data = tmp_path / "data"
|
|
app = create_app({
|
|
"TESTING": True, "SITE_URL": SITE, "ADMIN_ME": "https://example.com",
|
|
"SESSION_SECRET": "x", "DATA_PATH": data, "NOTES_PATH": data / "notes",
|
|
"DATABASE_PATH": data / "starpunk.db",
|
|
"NOTIFY_URLS": "gotifys://gotify.example.com/TOKEN, ntfys://topic?priority=max",
|
|
"NOTIFY_EVENTS": "reply,mention,like,problems",
|
|
"NOTIFY_PRIORITY": "high",
|
|
"CSRF_ENABLED": False,
|
|
})
|
|
yield app
|
|
syndication._client_cache.clear()
|
|
backfeed.denied.clear()
|
|
|
|
|
|
def note(app, content="Hello world", age_days=0):
|
|
with app.app_context():
|
|
n = create_note(content=content, published=True)
|
|
if age_days:
|
|
get_db(app).execute("UPDATE notes SET created_at = datetime('now', ?) WHERE id = ?",
|
|
(f"-{age_days} days", n.id))
|
|
get_db(app).commit()
|
|
return n
|
|
|
|
|
|
def response(app, n, kind, name, source, moderation="approved", origin="webmention",
|
|
snippet=None, hours_ago=0):
|
|
with app.app_context():
|
|
get_db(app).execute(
|
|
"INSERT INTO webmentions (source_url, target_url, target_note_id, mention_type, author_name, "
|
|
"validation_status, moderation_status, origin, content_snippet, received_at) "
|
|
"VALUES (?, ?, ?, ?, ?, 'valid', ?, ?, ?, datetime('now', ?))",
|
|
(source, f"{SITE}/note/{n.slug}", n.id, kind, name, moderation, origin, snippet,
|
|
f"-{hours_ago} hours"))
|
|
get_db(app).commit()
|
|
|
|
|
|
def sweep(app, sweeper=None):
|
|
sweeper = sweeper or notifications.Sweeper()
|
|
with app.app_context():
|
|
return sweeper.run(app.config, app.config["DATABASE_PATH"], SITE), sweeper
|
|
|
|
|
|
def unsent(app):
|
|
with app.app_context():
|
|
return [r[0] for r in get_db(app).execute(
|
|
"SELECT source_url FROM webmentions WHERE notified_at IS NULL ORDER BY id")]
|
|
|
|
|
|
# --- Settings --------------------------------------------------------------------------
|
|
|
|
def test_settings():
|
|
config = {"NOTIFY_URLS": " a://x,b://y c://z ", "NOTIFY_EVENTS": "Reply, likes, problems"}
|
|
assert notifications.urls(config) == ["a://x", "b://y", "c://z"]
|
|
assert notifications.events(config) == {"reply", "problems"}, "unknown names are ignored"
|
|
assert notifications.events({}) == {"reply", "mention", "quote", "problems"}
|
|
assert notifications.with_priority("gotifys://h/T", "high") == "gotifys://h/T?priority=high"
|
|
assert notifications.with_priority("ntfys://t?tags=x", "5") == "ntfys://t?tags=x&priority=5"
|
|
assert notifications.with_priority("ntfys://t?priority=max", "low") == "ntfys://t?priority=max"
|
|
|
|
|
|
# --- Sweep -------------------------------------------------------------------------------------
|
|
|
|
def test_new_responses_are_sent_once_and_likes_grouped(app, sent):
|
|
n = note(app, "Starpunk now supports backfeeds")
|
|
response(app, n, "reply", "Ana", "https://a.example/r", origin="bluesky",
|
|
snippet="<p>Great & useful!</p>")
|
|
response(app, n, "like", "Bob", "https://b.example/l")
|
|
response(app, n, "like", "Cy", "https://c.example/l")
|
|
response(app, n, "repost", "Dee", "https://d.example/rp") # not selected
|
|
response(app, n, "mention", "Eve", "https://e.example/m", moderation="pending")
|
|
count, _ = sweep(app)
|
|
assert count == 4
|
|
titles = [m["title"] for m in sent]
|
|
assert "↩ Reply from Ana via Bluesky" in titles
|
|
assert "💬 Mention from Eve (awaiting moderation)" in titles
|
|
assert "♥ 2 new likes on “Starpunk now supports backfeeds”" in titles
|
|
reply = next(m for m in sent if m["title"].startswith("↩"))
|
|
assert reply["body"].startswith("Great & useful!")
|
|
assert f"({SITE}/note/{n.slug}#responses)" in reply["body"]
|
|
mention = next(m for m in sent if m["title"].startswith("💬"))
|
|
assert f"{SITE}/admin/webmentions/" in mention["body"], "pending ones link to moderation"
|
|
assert all(t.endswith("priority=high") or t.endswith("priority=max") for t in sent[0]["targets"])
|
|
assert unsent(app) == []
|
|
sent.clear()
|
|
assert sweep(app)[0] == 0 and sent == [], "nothing is sent twice"
|
|
|
|
|
|
def test_failed_send_is_retried_with_backoff(app, monkeypatch):
|
|
calls = []
|
|
monkeypatch.setattr(notifications, "_deliver", lambda t, ti, b: (calls.append(ti), (False, "boom"))[1])
|
|
n = note(app)
|
|
response(app, n, "reply", "Ana", "https://a.example/r")
|
|
count, sweeper = sweep(app)
|
|
assert count == 0 and unsent(app) == ["https://a.example/r"]
|
|
assert sweep(app, sweeper)[0] == 0 and len(calls) == 1, "waits before retrying"
|
|
with app.app_context():
|
|
assert "boom" in notifications.last_error(get_db(app))
|
|
sweeper._next_try = 0
|
|
monkeypatch.setattr(notifications, "_deliver", lambda t, ti, b: (True, ""))
|
|
assert sweep(app, sweeper)[0] == 1
|
|
with app.app_context():
|
|
assert notifications.last_error(get_db(app)) == ""
|
|
|
|
|
|
def test_old_unsent_responses_are_dropped(app, sent):
|
|
n = note(app)
|
|
response(app, n, "reply", "Ana", "https://a.example/r", hours_ago=30)
|
|
assert sweep(app)[0] == 0 and sent == [] and unsent(app) == []
|
|
|
|
|
|
def test_off_without_urls(app, sent):
|
|
app.config["NOTIFY_URLS"] = ""
|
|
n = note(app)
|
|
response(app, n, "reply", "Ana", "https://a.example/r")
|
|
assert sweep(app)[0] == 0 and unsent(app) == ["https://a.example/r"]
|
|
|
|
|
|
def test_backfill_and_late_first_checks_are_quiet(app, sent):
|
|
class Client:
|
|
config_token = "t"
|
|
def responses(self, remote_id, remote_url, cap=1000):
|
|
return Harvest([Response(kind="reply", source_url=f"{remote_url}/reply", remote_id="r",
|
|
author_name="Ana", content_html="<p>hi</p>")])
|
|
def maintain(self):
|
|
pass
|
|
|
|
app.config.update(GOTOSOCIAL_URL="https://social.example", GOTOSOCIAL_ACCESS_TOKEN="t",
|
|
BACKFEED_ENABLED=True)
|
|
syndication._client_cache["https://social.example"] = Client()
|
|
fresh, old = note(app, "New"), note(app, "Old", age_days=10)
|
|
with app.app_context():
|
|
for n, url in ((fresh, "https://social.example/1"), (old, "https://social.example/2")):
|
|
get_db(app).execute("INSERT INTO syndications (note_id, target, enabled, remote_id, remote_url, "
|
|
"state) VALUES (?, 'gotosocial', 1, 'x', ?, 'synced')", (n.id, url))
|
|
get_db(app).commit()
|
|
backfeed.process_due()
|
|
assert unsent(app) == ["https://social.example/1/reply"], "only the new note's reply is news"
|
|
|
|
|
|
# --- Problems and admin ----------------------------------------------------------------------------
|
|
|
|
def test_problems(app, sent):
|
|
with app.app_context():
|
|
notifications.problem(app.config, app.config["DATABASE_PATH"], "Crosspost to Bluesky failed",
|
|
"HTTP 400", f"{SITE}/admin/edit/1")
|
|
assert sent[0]["title"] == "⚠ Crosspost to Bluesky failed"
|
|
assert "HTTP 400" in sent[0]["body"] and "/admin/edit/1" in sent[0]["body"]
|
|
app.config["NOTIFY_EVENTS"] = "reply"
|
|
with app.app_context():
|
|
notifications.problem(app.config, app.config["DATABASE_PATH"], "x", "y", "z")
|
|
assert len(sent) == 1, "not selected: not sent"
|
|
|
|
|
|
def test_final_crosspost_failure_notifies(app, sent):
|
|
n = note(app)
|
|
app.config.update(GOTOSOCIAL_URL="https://social.example", GOTOSOCIAL_ACCESS_TOKEN="t")
|
|
with app.app_context():
|
|
cur = get_db(app).execute("INSERT INTO syndications (note_id, target, enabled, state, attempts) "
|
|
"VALUES (?, 'gotosocial', 1, 'pending', 0)", (n.id,))
|
|
get_db(app).commit()
|
|
row = get_db(app).execute("SELECT * FROM syndications WHERE id = ?", (cur.lastrowid,)).fetchone()
|
|
syndication._fail(get_db(app), row, syndication.SyndicationError("temporary", permanent=False))
|
|
assert sent == [], "a retry is coming: no message"
|
|
syndication._fail(get_db(app), row, syndication.SyndicationError("HTTP 422 bad", permanent=True))
|
|
assert sent and sent[0]["title"] == "⚠ Crosspost to GoToSocial failed"
|
|
|
|
|
|
def test_admin_status_and_test_button(app, sent):
|
|
from starpunk.auth import create_session
|
|
|
|
with app.test_request_context():
|
|
token = create_session("https://example.com")
|
|
browser = app.test_client()
|
|
browser.set_cookie("starpunk_session", token)
|
|
page = browser.get("/admin/webmentions").get_data(as_text=True)
|
|
assert "Sending like, mention, problems, reply to gotifys, ntfys at high priority" in page
|
|
page = browser.post("/admin/notifications/test", follow_redirects=True).get_data(as_text=True)
|
|
assert "Test notification sent" in page and sent[-1]["title"] == "StarPunk test notification"
|
|
|
|
|
|
# --- Real Apprise -------------------------------------------------------------------------------------
|
|
|
|
def test_apprise_delivers_markdown_to_a_service(app):
|
|
received = []
|
|
|
|
class Handler(BaseHTTPRequestHandler):
|
|
def do_POST(self):
|
|
received.append(json.loads(self.rfile.read(int(self.headers["Content-Length"]))))
|
|
self.send_response(200)
|
|
self.end_headers()
|
|
|
|
def log_message(self, *args):
|
|
pass
|
|
|
|
server = HTTPServer(("127.0.0.1", 0), Handler)
|
|
threading.Thread(target=server.handle_request, daemon=True).start()
|
|
app.config["NOTIFY_URLS"] = f"json://127.0.0.1:{server.server_port}/"
|
|
ok, error = notifications.send(app.config, "Title", "Body with [a link](https://x.example)")
|
|
server.server_close()
|
|
assert ok, error
|
|
assert received[0]["title"] == "Title" and "a link" in received[0]["message"]
|
|
app.config["NOTIFY_URLS"] = "notaservice://nope"
|
|
ok, error = notifications.send(app.config, "t", "b")
|
|
assert not ok and "Not a usable Apprise URL" in error
|
|
|
|
|
|
def test_migration_021_marks_history(tmp_path):
|
|
from pathlib import Path
|
|
|
|
conn = sqlite3.connect(tmp_path / "db")
|
|
conn.execute("CREATE TABLE webmentions (id INTEGER PRIMARY KEY, source_url TEXT)")
|
|
conn.execute("INSERT INTO webmentions (source_url) VALUES ('https://old.example')")
|
|
conn.executescript((Path(__file__).parent.parent / "migrations" / "021_notifications.sql").read_text())
|
|
assert conn.execute("SELECT notified_at IS NOT NULL FROM webmentions").fetchone()[0] == 1
|