Files
StarPunk/tests/test_reply_crossposts.py
T
PhilandClaude Opus 5.5 67c0411fd8 feat: crossposted replies look like replies (v2.20.0)
- Native replies on the same network: GoToSocial in_reply_to_id (resolved
  by our instance) with the author's @mention; Bluesky reply root/parent
- Replies to our own notes (permalink or any crosspost URL) thread under
  that note's crosspost on every network, Threads included
- Otherwise "↩ Replying to <author>" and the link; on Bluesky the name is
  the link. compose_text keeps the line whole when shortening

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-13 15:32:14 -07:00

217 lines
9.0 KiB
Python

"""
Crossposted replies look like replies (v2.20.0)
A reply to a post on the same network threads under it natively (with an
@mention on the fediverse); a reply to one of our own notes threads under
that note's crosspost on every network; anything else starts with
"↩ Replying to <author>" and the link.
"""
import json
from types import SimpleNamespace
import httpx
import pytest
from starpunk import create_app, syndication
from starpunk.notes import create_note, get_note
from starpunk.syndication import (BlueskyClient, MastodonClient, Post, ThreadsClient,
compose_text, get_note_syndications, process_due,
select_targets)
SITE = "https://blog.example.com"
GTS = "https://social.example.com"
FEDI_POST = "https://mastodon.example/@alice/111"
OWN_FEDI_POST = "https://social.example.com/@phil/statuses/01OWN"
BSKY_POST = "https://bsky.app/profile/alice.example/post/3abc"
WEB_PAGE = "https://someblog.example/2026/a-post"
def note(content="Agreed, this cannot be good"):
return SimpleNamespace(content=content, title=None, bookmark_of=None, label=content[:30],
summary=None, excerpt=content)
def post(reply_to=None, **kwargs):
return Post(note=note(), permalink=f"{SITE}/note/1", tags=[], max_chars=500,
reply_to=reply_to, **kwargs)
class FakeGTS:
def __init__(self):
self.created = []
def __call__(self, request):
path = request.url.path
if path == "/api/v1/accounts/verify_credentials":
return httpx.Response(200, json={"id": "me"})
if path == "/api/v2/search":
q = request.url.params["q"]
accounts = {FEDI_POST: {"id": "a2", "acct": "alice@mastodon.example"},
OWN_FEDI_POST: {"id": "me", "acct": "phil"}}
if q in accounts:
return httpx.Response(200, json={"statuses": [{"id": "s1", "account": accounts[q]}]})
return httpx.Response(200, json={"statuses": []})
if path == "/api/v1/statuses" and request.method == "POST":
self.created.append(json.loads(request.content))
sid = f"p{len(self.created)}"
return httpx.Response(200, json={"id": sid, "url": f"{GTS}/@phil/statuses/{sid}"})
return httpx.Response(500)
class FakePDS:
def __init__(self):
self.records = []
def __call__(self, request):
nsid = request.url.path.removeprefix("/xrpc/")
if nsid == "com.atproto.server.createSession":
return httpx.Response(200, json={"did": "did:plc:me", "handle": "me.example",
"accessJwt": "a", "refreshJwt": "r"})
if nsid == "com.atproto.identity.resolveHandle":
return httpx.Response(200, json={"did": "did:plc:alice"})
if nsid == "app.bsky.feed.getPosts":
uri = request.url.params["uris"]
record = {"text": "parent"}
if uri.endswith("/3abc"): # itself a reply in a thread
record["reply"] = {"root": {"uri": "at://did:plc:alice/app.bsky.feed.post/root",
"cid": "rootcid"}, "parent": {}}
return httpx.Response(200, json={"posts": [{"uri": uri, "cid": "cid1", "record": record}]})
if nsid == "com.atproto.repo.createRecord":
body = json.loads(request.content)
self.records.append(body["record"])
uri = f"at://did:plc:me/{body['collection']}/r{len(self.records)}"
return httpx.Response(200, json={"uri": uri, "cid": "c"})
return httpx.Response(500, json={"error": nsid})
@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",
"GOTOSOCIAL_URL": GTS, "GOTOSOCIAL_ACCESS_TOKEN": "t",
"BLUESKY_HANDLE": "me.example", "BLUESKY_APP_PASSWORD": "p", "BLUESKY_SERVICE": "https://pds.example",
})
yield app
syndication._client_cache.clear()
@pytest.fixture
def gts():
fake = FakeGTS()
return fake, MastodonClient(GTS, "t", http=httpx.Client(transport=httpx.MockTransport(fake)))
@pytest.fixture
def pds():
fake = FakePDS()
return fake, BlueskyClient("https://pds.example", "me.example", "p",
http=httpx.Client(transport=httpx.MockTransport(fake)))
# --- GoToSocial ---------------------------------------------------------------
def test_fediverse_reply_threads_and_mentions(app, gts):
fake, client = gts
with app.app_context():
client.create(post(FEDI_POST, reply_name="Alice"), key="k")
(body,) = fake.created
assert body["in_reply_to_id"] == "s1"
assert body["status"].startswith("@alice@mastodon.example Agreed")
assert "Replying to" not in body["status"]
def test_reply_to_own_fediverse_post_has_no_mention(app, gts):
fake, client = gts
with app.app_context():
client.create(post(OWN_FEDI_POST), key="k")
assert fake.created[0]["in_reply_to_id"] == "s1"
assert fake.created[0]["status"].startswith("Agreed")
def test_reply_to_a_web_page_says_so_on_the_fediverse(app, gts):
fake, client = gts
with app.app_context():
client.create(post(WEB_PAGE, reply_name="Ada"), key="k1")
client.create(post(WEB_PAGE), key="k2")
named, unnamed = fake.created
assert "in_reply_to_id" not in named
assert named["status"].startswith(f"↩ Replying to Ada\n{WEB_PAGE}\n\nAgreed")
assert unnamed["status"].startswith(f"↩ Replying to someblog.example\n{WEB_PAGE}")
# --- Bluesky ------------------------------------------------------------------
def test_bluesky_reply_threads_under_the_post_and_its_root(app, pds):
fake, client = pds
with app.app_context():
client.create(post(BSKY_POST, reply_name="Alice"), key="k")
(record,) = fake.records
assert record["reply"]["parent"] == {"uri": "at://did:plc:alice/app.bsky.feed.post/3abc", "cid": "cid1"}
assert record["reply"]["root"] == {"uri": "at://did:plc:alice/app.bsky.feed.post/root", "cid": "rootcid"}
assert record["text"].startswith("Agreed")
def test_reply_to_a_fediverse_post_says_so_on_bluesky(app, pds):
fake, client = pds
with app.app_context():
client.create(post(FEDI_POST, reply_name="Alice"), key="k")
(record,) = fake.records
assert "reply" not in record
assert record["text"].startswith("↩ Replying to Alice\n\nAgreed")
links = [f for f in record["facets"] if f["features"][0]["uri"] == FEDI_POST]
(link,) = links
start = record["text"].encode().index(b"Alice")
assert link["index"] == {"byteStart": start, "byteEnd": start + len(b"Alice")}
# --- Threads ------------------------------------------------------------------
def test_threads_replies_natively_only_to_our_own_posts(app):
client = ThreadsClient("tok")
calls = []
client._call = lambda method, path, **params: calls.append(params) or {"id": "c1"}
with app.app_context():
client._container("me", post(f"{SITE}/note/0", reply_remote_id="1789"))
client._container("me", post(FEDI_POST, reply_name="Alice"))
own, other = calls
assert own["reply_to_id"] == "1789" and not own["text"].startswith("↩")
assert "reply_to_id" not in other
assert other["text"].startswith(f"↩ Replying to Alice\n{FEDI_POST}\n\nAgreed")
# --- Composing ----------------------------------------------------------------
def test_reply_line_survives_shortening():
text = compose_text(note("word " * 200), f"{SITE}/note/1", [], 300,
lead=f"↩ Replying to Alice\n{FEDI_POST}")
assert text.startswith(f"↩ Replying to Alice\n{FEDI_POST}\n\nword")
assert len(text) <= 300 and text.endswith(f"{SITE}/note/1")
# --- Replies to our own notes thread under their crossposts ----------------------
@pytest.mark.parametrize("via", ["permalink", "crosspost"])
def test_reply_to_own_note_threads_on_every_network(app, gts, pds, monkeypatch, via):
monkeypatch.setattr("starpunk.reply_context.fetch_reply_context", lambda *a, **k: None)
(gts_fake, gts_client), (pds_fake, pds_client) = gts, pds
syndication._client_cache[GTS] = gts_client
syndication._client_cache["bluesky:https://pds.example:me.example"] = pds_client
def crosspost(**kwargs):
with app.test_request_context():
n = create_note("Plain words without links", published=True, **kwargs)
select_targets(n.id, ["gotosocial", "bluesky"])
process_due(limit=10)
return get_note(id=n.id).url, {r["target"]: r for r in get_note_syndications(n.id)}
first, rows = crosspost()
target = first if via == "permalink" else rows["gotosocial"]["remote_url"]
second, _ = crosspost(in_reply_to=target)
assert gts_fake.created[-1]["in_reply_to_id"] == rows["gotosocial"]["remote_id"]
assert not gts_fake.created[-1]["status"].startswith(("@", "↩"))
assert pds_fake.records[-1]["reply"]["parent"]["uri"] == rows["bluesky"]["remote_id"]