Something went wrong. Try again.
A community based topic aggregation platform built on atproto
Something went wrong. Try again.
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398//go:build integration
package comments_test
import ( "context" "database/sql" "encoding/json" "fmt" "net/http" "net/http/httptest" "strings" "testing" "time"
commentsAPI "Coves/internal/api/handlers/comments" "Coves/internal/atproto/jetstream" "Coves/internal/core/comments" "Coves/internal/core/moderation" "Coves/internal/crypto/credentialcipher/credentialciphertest" "Coves/internal/db/postgres" "Coves/tests/fixtures" "Coves/tests/testkit"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/require")
// TestCommentQuery_BasicFetch tests fetching top-level comments with default paramsfunc TestCommentQuery_BasicFetch(t *testing.T) { t.Parallel() db := testkit.DB(t)
ctx := context.Background() testUser := fixtures.User(t, db, "basicfetch.test", "did:plc:basicfetch123") testCommunity, err := fixtures.Community(ctx, db, "basicfetchcomm", "ownerbasic.test") require.NoError(t, err, "Failed to create test community")
postURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Basic Fetch Test Post", 0, time.Now())
// Create 3 top-level comments with different scores and ages comment1 := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "First comment", 10, 2, time.Now().Add(-2*time.Hour)) comment2 := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Second comment", 5, 1, time.Now().Add(-30*time.Minute)) comment3 := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Third comment", 3, 0, time.Now().Add(-5*time.Minute))
// Fetch comments with default params (hot sort) service := setupCommentService(db) req := &comments.GetCommentsRequest{ PostURI: postURI, Sort: "hot", Depth: 10, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err, "GetComments should not return error") require.NotNil(t, resp, "Response should not be nil")
// Verify all 3 comments returned assert.Len(t, resp.Comments, 3, "Should return all 3 top-level comments")
// Verify stats are correct for _, threadView := range resp.Comments { commentView := threadView.Comment assert.NotNil(t, commentView.Stats, "Stats should not be nil")
// Verify upvotes, downvotes, score, reply count present assert.GreaterOrEqual(t, commentView.Stats.Upvotes, 0, "Upvotes should be non-negative") assert.GreaterOrEqual(t, commentView.Stats.Downvotes, 0, "Downvotes should be non-negative") assert.Equal(t, 0, commentView.Stats.ReplyCount, "Top-level comments should have 0 replies") }
// Verify URIs match commentURIs := []string{comment1, comment2, comment3} returnedURIs := make(map[string]bool) for _, tv := range resp.Comments { returnedURIs[tv.Comment.URI] = true }
for _, uri := range commentURIs { assert.True(t, returnedURIs[uri], "Comment URI %s should be in results", uri) }}
// TestCommentQuery_NestedReplies tests fetching comments with nested reply structurefunc TestCommentQuery_NestedReplies(t *testing.T) { t.Parallel() db := testkit.DB(t)
ctx := context.Background() testUser := fixtures.User(t, db, "nested.test", "did:plc:nested123") testCommunity, err := fixtures.Community(ctx, db, "nestedcomm", "ownernested.test") require.NoError(t, err)
postURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Nested Test Post", 0, time.Now())
// Create nested structure: // Post // |- Comment A (top-level) // |- Reply A1 // |- Reply A1a // |- Reply A1b // |- Reply A2 // |- Comment B (top-level)
commentA := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Comment A", 5, 0, time.Now().Add(-1*time.Hour)) replyA1 := createTestCommentWithScore(t, db, testUser.DID, postURI, commentA, "Reply A1", 3, 0, time.Now().Add(-50*time.Minute)) replyA1a := createTestCommentWithScore(t, db, testUser.DID, postURI, replyA1, "Reply A1a", 2, 0, time.Now().Add(-40*time.Minute)) replyA1b := createTestCommentWithScore(t, db, testUser.DID, postURI, replyA1, "Reply A1b", 1, 0, time.Now().Add(-30*time.Minute)) replyA2 := createTestCommentWithScore(t, db, testUser.DID, postURI, commentA, "Reply A2", 2, 0, time.Now().Add(-20*time.Minute)) commentB := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Comment B", 4, 0, time.Now().Add(-10*time.Minute))
// Fetch with depth=2 (should get 2 levels of nesting) service := setupCommentService(db) req := &comments.GetCommentsRequest{ PostURI: postURI, Sort: "new", Depth: 2, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err) require.Len(t, resp.Comments, 2, "Should return 2 top-level comments")
// Find Comment A in results var commentAThread *comments.ThreadViewComment for _, tv := range resp.Comments { if tv.Comment.URI == commentA { commentAThread = tv break } } require.NotNil(t, commentAThread, "Comment A should be in results")
// Verify Comment A has replies require.NotNil(t, commentAThread.Replies, "Comment A should have replies") assert.Len(t, commentAThread.Replies, 2, "Comment A should have 2 direct replies (A1 and A2)")
// Find Reply A1 var replyA1Thread *comments.ThreadViewComment for _, reply := range commentAThread.Replies { if reply.Comment.URI == replyA1 { replyA1Thread = reply break } } require.NotNil(t, replyA1Thread, "Reply A1 should be in results")
// Verify Reply A1 has nested replies (at depth 2) require.NotNil(t, replyA1Thread.Replies, "Reply A1 should have nested replies at depth 2") assert.Len(t, replyA1Thread.Replies, 2, "Reply A1 should have 2 nested replies (A1a and A1b)")
// Verify reply URIs replyURIs := make(map[string]bool) for _, r := range replyA1Thread.Replies { replyURIs[r.Comment.URI] = true } assert.True(t, replyURIs[replyA1a], "Reply A1a should be present") assert.True(t, replyURIs[replyA1b], "Reply A1b should be present")
// Verify no deeper nesting (depth limit enforced) for _, r := range replyA1Thread.Replies { assert.Nil(t, r.Replies, "Replies at depth 2 should not have further nesting") }
_ = commentB _ = replyA2}
// TestCommentQuery_DepthLimit tests depth limiting works correctlyfunc TestCommentQuery_DepthLimit(t *testing.T) { t.Parallel() db := testkit.DB(t)
ctx := context.Background() testUser := fixtures.User(t, db, "depth.test", "did:plc:depth123") testCommunity, err := fixtures.Community(ctx, db, "depthcomm", "ownerdepth.test") require.NoError(t, err)
postURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Depth Test Post", 0, time.Now())
// Create deeply nested thread (5 levels) // Post -> C1 -> C2 -> C3 -> C4 -> C5 c1 := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Level 1", 5, 0, time.Now().Add(-5*time.Minute)) c2 := createTestCommentWithScore(t, db, testUser.DID, postURI, c1, "Level 2", 4, 0, time.Now().Add(-4*time.Minute)) c3 := createTestCommentWithScore(t, db, testUser.DID, postURI, c2, "Level 3", 3, 0, time.Now().Add(-3*time.Minute)) c4 := createTestCommentWithScore(t, db, testUser.DID, postURI, c3, "Level 4", 2, 0, time.Now().Add(-2*time.Minute)) c5 := createTestCommentWithScore(t, db, testUser.DID, postURI, c4, "Level 5", 1, 0, time.Now().Add(-1*time.Minute))
t.Run("Depth 0 returns flat list", func(t *testing.T) { service := setupCommentService(db) req := &comments.GetCommentsRequest{ PostURI: postURI, Sort: "new", Depth: 0, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err) require.Len(t, resp.Comments, 1, "Should return 1 top-level comment")
// Verify no replies included assert.Nil(t, resp.Comments[0].Replies, "Depth 0 should not include replies")
// Verify HasMore flag is set (c1 has replies) assert.True(t, resp.Comments[0].HasMore, "HasMore should be true when replies exist but depth=0") })
t.Run("Depth 3 returns exactly 3 levels", func(t *testing.T) { service := setupCommentService(db) req := &comments.GetCommentsRequest{ PostURI: postURI, Sort: "new", Depth: 3, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err) require.Len(t, resp.Comments, 1, "Should return 1 top-level comment")
// Traverse and verify exactly 3 levels level1 := resp.Comments[0] require.NotNil(t, level1.Replies, "Level 1 should have replies") require.Len(t, level1.Replies, 1, "Level 1 should have 1 reply")
level2 := level1.Replies[0] require.NotNil(t, level2.Replies, "Level 2 should have replies") require.Len(t, level2.Replies, 1, "Level 2 should have 1 reply")
level3 := level2.Replies[0] require.NotNil(t, level3.Replies, "Level 3 should have replies") require.Len(t, level3.Replies, 1, "Level 3 should have 1 reply")
// Level 4 should NOT have replies (depth limit) level4 := level3.Replies[0] assert.Nil(t, level4.Replies, "Level 4 should not have replies (depth limit)")
// Verify HasMore is set correctly at depth boundary assert.True(t, level4.HasMore, "HasMore should be true at depth boundary when more replies exist") })
_ = c2 _ = c3 _ = c4 _ = c5}
// TestCommentQuery_HotSorting tests hot sorting with Lemmy algorithmfunc TestCommentQuery_HotSorting(t *testing.T) { t.Parallel() db := testkit.DB(t)
ctx := context.Background() testUser := fixtures.User(t, db, "hot.test", "did:plc:hot123") testCommunity, err := fixtures.Community(ctx, db, "hotcomm", "ownerhot.test") require.NoError(t, err)
postURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Hot Sorting Test", 0, time.Now())
// Create 3 comments with different scores and ages // Comment 1: score=10, created 1 hour ago c1 := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Old high score", 10, 0, time.Now().Add(-1*time.Hour))
// Comment 2: score=5, created 5 minutes ago (should rank higher due to recency) c2 := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Recent medium score", 5, 0, time.Now().Add(-5*time.Minute))
// Comment 3: score=-2, created now (negative score should rank lower) c3 := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Negative score", 0, 2, time.Now())
service := setupCommentService(db) req := &comments.GetCommentsRequest{ PostURI: postURI, Sort: "hot", Depth: 0, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err) require.Len(t, resp.Comments, 3, "Should return all 3 comments")
// Verify hot sorting order // Recent comment with medium score should rank higher than old comment with high score assert.Equal(t, c2, resp.Comments[0].Comment.URI, "Recent medium score should rank first") assert.Equal(t, c1, resp.Comments[1].Comment.URI, "Old high score should rank second") assert.Equal(t, c3, resp.Comments[2].Comment.URI, "Negative score should rank last")
// Verify negative scores are handled gracefully negativeComment := resp.Comments[2].Comment assert.Equal(t, -2, negativeComment.Stats.Score, "Negative score should be preserved") assert.Equal(t, 0, negativeComment.Stats.Upvotes, "Upvotes should be 0") assert.Equal(t, 2, negativeComment.Stats.Downvotes, "Downvotes should be 2")}
// TestCommentQuery_TopSorting tests top sorting with score-based orderingfunc TestCommentQuery_TopSorting(t *testing.T) { t.Parallel() db := testkit.DB(t)
ctx := context.Background() testUser := fixtures.User(t, db, "top.test", "did:plc:top123") testCommunity, err := fixtures.Community(ctx, db, "topcomm", "ownertop.test") require.NoError(t, err)
postURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Top Sorting Test", 0, time.Now())
// Create comments with different scores c1 := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Low score", 2, 0, time.Now().Add(-30*time.Minute)) c2 := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "High score", 10, 0, time.Now().Add(-1*time.Hour)) c3 := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Medium score", 5, 0, time.Now().Add(-15*time.Minute))
t.Run("Top sort without timeframe", func(t *testing.T) { service := setupCommentService(db) req := &comments.GetCommentsRequest{ PostURI: postURI, Sort: "top", Depth: 0, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err) require.Len(t, resp.Comments, 3)
// Verify highest score first assert.Equal(t, c2, resp.Comments[0].Comment.URI, "Highest score should be first") assert.Equal(t, c3, resp.Comments[1].Comment.URI, "Medium score should be second") assert.Equal(t, c1, resp.Comments[2].Comment.URI, "Low score should be third") })
t.Run("Top sort with hour timeframe", func(t *testing.T) { service := setupCommentService(db) req := &comments.GetCommentsRequest{ PostURI: postURI, Sort: "top", Timeframe: "hour", Depth: 0, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err)
// Only comments from last hour should be included (c1 and c3, not c2) assert.LessOrEqual(t, len(resp.Comments), 2, "Should exclude comments older than 1 hour")
// Verify c2 (created 1 hour ago) is excluded for _, tv := range resp.Comments { assert.NotEqual(t, c2, tv.Comment.URI, "Comment older than 1 hour should be excluded") } })}
// TestCommentQuery_NewSorting tests chronological sortingfunc TestCommentQuery_NewSorting(t *testing.T) { t.Parallel() db := testkit.DB(t)
ctx := context.Background() testUser := fixtures.User(t, db, "new.test", "did:plc:new123") testCommunity, err := fixtures.Community(ctx, db, "newcomm", "ownernew.test") require.NoError(t, err)
postURI := fixtures.Post(t, db, testCommunity, testUser.DID, "New Sorting Test", 0, time.Now())
// Create comments at different times (different scores to verify time is priority) c1 := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Oldest", 10, 0, time.Now().Add(-1*time.Hour)) c2 := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Middle", 5, 0, time.Now().Add(-30*time.Minute)) c3 := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Newest", 2, 0, time.Now().Add(-5*time.Minute))
service := setupCommentService(db) req := &comments.GetCommentsRequest{ PostURI: postURI, Sort: "new", Depth: 0, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err) require.Len(t, resp.Comments, 3)
// Verify chronological order (newest first) assert.Equal(t, c3, resp.Comments[0].Comment.URI, "Newest comment should be first") assert.Equal(t, c2, resp.Comments[1].Comment.URI, "Middle comment should be second") assert.Equal(t, c1, resp.Comments[2].Comment.URI, "Oldest comment should be third")}
// TestCommentQuery_Pagination tests cursor-based paginationfunc TestCommentQuery_Pagination(t *testing.T) { t.Parallel() db := testkit.DB(t)
ctx := context.Background() testUser := fixtures.User(t, db, "page.test", "did:plc:page123") testCommunity, err := fixtures.Community(ctx, db, "pagecomm", "ownerpage.test") require.NoError(t, err)
postURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Pagination Test", 0, time.Now())
// Create 60 comments allCommentURIs := make([]string, 60) for i := 0; i < 60; i++ { uri := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, fmt.Sprintf("Comment %d", i), i, 0, time.Now().Add(-time.Duration(60-i)*time.Minute)) allCommentURIs[i] = uri }
service := setupCommentService(db)
// Fetch first page (limit=50) req1 := &comments.GetCommentsRequest{ PostURI: postURI, Sort: "new", Depth: 0, Limit: 50, }
resp1, err := service.GetComments(ctx, req1) require.NoError(t, err) assert.Len(t, resp1.Comments, 50, "First page should have 50 comments") require.NotNil(t, resp1.Cursor, "Cursor should be present for next page")
// Fetch second page with cursor req2 := &comments.GetCommentsRequest{ PostURI: postURI, Sort: "new", Depth: 0, Limit: 50, Cursor: resp1.Cursor, }
resp2, err := service.GetComments(ctx, req2) require.NoError(t, err) assert.Len(t, resp2.Comments, 10, "Second page should have remaining 10 comments") assert.Nil(t, resp2.Cursor, "Cursor should be nil on last page")
// Verify no duplicates between pages page1URIs := make(map[string]bool) for _, tv := range resp1.Comments { page1URIs[tv.Comment.URI] = true }
for _, tv := range resp2.Comments { assert.False(t, page1URIs[tv.Comment.URI], "Comment %s should not appear in both pages", tv.Comment.URI) }
// Verify all comments eventually retrieved allRetrieved := make(map[string]bool) for _, tv := range resp1.Comments { allRetrieved[tv.Comment.URI] = true } for _, tv := range resp2.Comments { allRetrieved[tv.Comment.URI] = true } assert.Len(t, allRetrieved, 60, "All 60 comments should be retrieved across pages")}
// TestCommentQuery_EmptyThread tests fetching comments from a post with no commentsfunc TestCommentQuery_EmptyThread(t *testing.T) { t.Parallel() db := testkit.DB(t)
ctx := context.Background() testUser := fixtures.User(t, db, "empty.test", "did:plc:empty123") testCommunity, err := fixtures.Community(ctx, db, "emptycomm", "ownerempty.test") require.NoError(t, err)
postURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Empty Thread Test", 0, time.Now())
service := setupCommentService(db) req := &comments.GetCommentsRequest{ PostURI: postURI, Sort: "hot", Depth: 10, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err) require.NotNil(t, resp, "Response should not be nil")
// Verify empty array (not null) assert.NotNil(t, resp.Comments, "Comments array should not be nil") assert.Len(t, resp.Comments, 0, "Comments array should be empty")
// Verify no cursor returned assert.Nil(t, resp.Cursor, "Cursor should be nil for empty results")}
// TestCommentQuery_DeletedComments tests that soft-deleted comments are excludedfunc TestCommentQuery_DeletedComments(t *testing.T) { t.Parallel() db := testkit.DB(t)
ctx := context.Background() commentRepo := postgres.NewCommentRepository(db) consumer := jetstream.NewCommentEventConsumer(commentRepo, db)
testUser := fixtures.User(t, db, "deleted.test", "did:plc:deleted123") testCommunity, err := fixtures.Community(ctx, db, "deletedcomm", "ownerdeleted.test") require.NoError(t, err)
postURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Deleted Comments Test", 0, time.Now())
// Create 5 comments via Jetstream consumer commentURIs := make([]string, 5) for i := 0; i < 5; i++ { rkey := testkit.TID() uri := fmt.Sprintf("at://%s/social.coves.community.comment/%s", testUser.DID, rkey) commentURIs[i] = uri
event := &jetstream.JetstreamEvent{ Did: testUser.DID, Kind: "commit", Commit: &jetstream.CommitEvent{ Operation: "create", Collection: "social.coves.community.comment", RKey: rkey, CID: fmt.Sprintf("bafyc%d", i), Record: map[string]interface{}{ "$type": "social.coves.community.comment", "content": fmt.Sprintf("Comment %d", i), "reply": map[string]interface{}{ "root": map[string]interface{}{ "uri": postURI, "cid": "bafypost", }, "parent": map[string]interface{}{ "uri": postURI, "cid": "bafypost", }, }, "createdAt": time.Now().Add(time.Duration(i) * time.Minute).Format(time.RFC3339), }, }, }
require.NoError(t, consumer.HandleEvent(ctx, event)) }
// Soft-delete 2 comments (index 1 and 3) deleteEvent1 := &jetstream.JetstreamEvent{ Did: testUser.DID, Kind: "commit", Commit: &jetstream.CommitEvent{ Operation: "delete", Collection: "social.coves.community.comment", RKey: strings.Split(commentURIs[1], "/")[4], }, } require.NoError(t, consumer.HandleEvent(ctx, deleteEvent1))
deleteEvent2 := &jetstream.JetstreamEvent{ Did: testUser.DID, Kind: "commit", Commit: &jetstream.CommitEvent{ Operation: "delete", Collection: "social.coves.community.comment", RKey: strings.Split(commentURIs[3], "/")[4], }, } require.NoError(t, consumer.HandleEvent(ctx, deleteEvent2))
// Fetch comments service := setupCommentService(db) req := &comments.GetCommentsRequest{ PostURI: postURI, Sort: "new", Depth: 0, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err)
// All 5 comments should be returned (deleted comments shown as placeholders) assert.Len(t, resp.Comments, 5, "Should return all comments including deleted ones as placeholders")
// Build a map of URI -> CommentView for verification commentViews := make(map[string]*comments.CommentView) for _, tv := range resp.Comments { commentViews[tv.Comment.URI] = tv.Comment }
// Verify all comments are present assert.Contains(t, commentViews, commentURIs[0], "Comment 0 should be in results") assert.Contains(t, commentViews, commentURIs[1], "Comment 1 (deleted) should be in results as placeholder") assert.Contains(t, commentViews, commentURIs[2], "Comment 2 should be in results") assert.Contains(t, commentViews, commentURIs[3], "Comment 3 (deleted) should be in results as placeholder") assert.Contains(t, commentViews, commentURIs[4], "Comment 4 should be in results")
// Verify deleted comments are marked as deleted assert.True(t, commentViews[commentURIs[1]].IsDeleted, "Deleted comment 1 should have IsDeleted=true") assert.True(t, commentViews[commentURIs[3]].IsDeleted, "Deleted comment 3 should have IsDeleted=true")
// Verify non-deleted comments are NOT marked as deleted assert.False(t, commentViews[commentURIs[0]].IsDeleted, "Non-deleted comment 0 should have IsDeleted=false") assert.False(t, commentViews[commentURIs[2]].IsDeleted, "Non-deleted comment 2 should have IsDeleted=false") assert.False(t, commentViews[commentURIs[4]].IsDeleted, "Non-deleted comment 4 should have IsDeleted=false")
// Verify deleted comments have nil Record (content cleared) assert.Nil(t, commentViews[commentURIs[1]].Record, "Deleted comment 1 should have nil Record") assert.Nil(t, commentViews[commentURIs[3]].Record, "Deleted comment 3 should have nil Record")
// Verify non-deleted comments have content assert.NotNil(t, commentViews[commentURIs[0]].Record, "Non-deleted comment 0 should have Record") assert.NotNil(t, commentViews[commentURIs[2]].Record, "Non-deleted comment 2 should have Record") assert.NotNil(t, commentViews[commentURIs[4]].Record, "Non-deleted comment 4 should have Record")}
// TestCommentQuery_InvalidInputs tests error handling for invalid inputsfunc TestCommentQuery_InvalidInputs(t *testing.T) { t.Parallel() db := testkit.DB(t)
ctx := context.Background() service := setupCommentService(db)
// Create a real post for validation tests that should succeed after normalization testUser := fixtures.User(t, db, "validation.test", "did:plc:validation123") testCommunity, err := fixtures.Community(ctx, db, "validationcomm", "ownervalidation.test") require.NoError(t, err, "Failed to create test community") validPostURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Validation Test Post", 0, time.Now())
t.Run("Invalid post URI", func(t *testing.T) { req := &comments.GetCommentsRequest{ PostURI: "not-an-at-uri", Sort: "hot", Depth: 10, Limit: 50, }
_, err := service.GetComments(ctx, req) assert.Error(t, err, "Should return error for invalid AT-URI") assert.Contains(t, err.Error(), "invalid", "Error should mention invalid") })
t.Run("Negative depth", func(t *testing.T) { req := &comments.GetCommentsRequest{ PostURI: validPostURI, // Use real post so validation can succeed Sort: "hot", Depth: -5, Limit: 50, }
resp, err := service.GetComments(ctx, req) // Should not error, but should clamp to default (10) require.NoError(t, err) // Depth is normalized in validation _ = resp })
t.Run("Depth exceeds max", func(t *testing.T) { req := &comments.GetCommentsRequest{ PostURI: validPostURI, // Use real post so validation can succeed Sort: "hot", Depth: 150, // Exceeds max of 100 Limit: 50, }
resp, err := service.GetComments(ctx, req) // Should not error, but should clamp to 100 require.NoError(t, err) _ = resp })
t.Run("Limit exceeds max", func(t *testing.T) { req := &comments.GetCommentsRequest{ PostURI: validPostURI, // Use real post so validation can succeed Sort: "hot", Depth: 10, Limit: 150, // Exceeds max of 100 }
resp, err := service.GetComments(ctx, req) // Should not error, but should clamp to 100 require.NoError(t, err) _ = resp })
t.Run("Invalid sort", func(t *testing.T) { req := &comments.GetCommentsRequest{ PostURI: "at://did:plc:test/social.coves.feed.post/abc123", Sort: "invalid", Depth: 10, Limit: 50, }
_, err := service.GetComments(ctx, req) assert.Error(t, err, "Should return error for invalid sort") assert.Contains(t, err.Error(), "invalid sort", "Error should mention invalid sort") })
t.Run("Empty post URI", func(t *testing.T) { req := &comments.GetCommentsRequest{ PostURI: "", Sort: "hot", Depth: 10, Limit: 50, }
_, err := service.GetComments(ctx, req) assert.Error(t, err, "Should return error for empty post URI") })}
// TestCommentQuery_HTTPHandler tests the HTTP handler end-to-endfunc TestCommentQuery_HTTPHandler(t *testing.T) { t.Parallel() db := testkit.DB(t)
ctx := context.Background() testUser := fixtures.User(t, db, "http.test", "did:plc:http123") testCommunity, err := fixtures.Community(ctx, db, "httpcomm", "ownerhttp.test") require.NoError(t, err)
postURI := fixtures.Post(t, db, testCommunity, testUser.DID, "HTTP Handler Test", 0, time.Now())
// Create test comments createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Test comment 1", 5, 0, time.Now().Add(-30*time.Minute)) createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Test comment 2", 3, 0, time.Now().Add(-15*time.Minute))
// Setup service adapter for HTTP handler service := setupCommentServiceAdapter(db) handler := &testGetCommentsHandler{service: service}
t.Run("Valid GET request", func(t *testing.T) { req := httptest.NewRequest("GET", fmt.Sprintf("/xrpc/social.coves.feed.getComments?post=%s&sort=hot&depth=10&limit=50", postURI), nil) w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusOK, w.Code) assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
var resp comments.GetCommentsResponse err := json.NewDecoder(w.Body).Decode(&resp) require.NoError(t, err) assert.Len(t, resp.Comments, 2, "Should return 2 comments") })
t.Run("Missing post parameter", func(t *testing.T) { req := httptest.NewRequest("GET", "/xrpc/social.coves.feed.getComments?sort=hot", nil) w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code) })
t.Run("Invalid depth parameter", func(t *testing.T) { req := httptest.NewRequest("GET", fmt.Sprintf("/xrpc/social.coves.feed.getComments?post=%s&depth=invalid", postURI), nil) w := httptest.NewRecorder()
handler.ServeHTTP(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code) })}
// TestCommentQuery_ParentRkeySubtree tests fetching a comment subtree via parentRkey// Backs the comment-permalink page and "continue this thread" for deep threadsfunc TestCommentQuery_ParentRkeySubtree(t *testing.T) { t.Parallel() db := testkit.DB(t)
ctx := context.Background() testUser := fixtures.User(t, db, "subtree.test", "did:plc:subtree123") testCommunity, err := fixtures.Community(ctx, db, "subtreecomm", "ownersubtree.test") require.NoError(t, err)
postURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Subtree Test Post", 0, time.Now())
// Create nested structure: // Post // |- Comment A (top-level) // |- Reply A1 // |- Reply A1a // |- Reply A2 // |- Comment B (top-level, must NOT appear in subtree responses) commentA := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Comment A", 5, 0, time.Now().Add(-1*time.Hour)) replyA1 := createTestCommentWithScore(t, db, testUser.DID, postURI, commentA, "Reply A1", 3, 0, time.Now().Add(-50*time.Minute)) replyA1a := createTestCommentWithScore(t, db, testUser.DID, postURI, replyA1, "Reply A1a", 2, 0, time.Now().Add(-40*time.Minute)) replyA2 := createTestCommentWithScore(t, db, testUser.DID, postURI, commentA, "Reply A2", 2, 0, time.Now().Add(-20*time.Minute)) commentB := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Comment B", 4, 0, time.Now().Add(-10*time.Minute))
// rkey is the last segment of the AT-URI (at://did/collection/rkey) commentARkey := strings.Split(commentA, "/")[4] replyA1Rkey := strings.Split(replyA1, "/")[4]
service := setupCommentService(db)
t.Run("Subtree returned with parent as sole root", func(t *testing.T) { req := &comments.GetCommentsRequest{ PostURI: postURI, ParentRkey: commentARkey, Sort: "new", Depth: 10, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err) require.NotNil(t, resp) require.NotNil(t, resp.Post, "Post view should still be present")
// Exactly one top-level entry: Comment A itself require.Len(t, resp.Comments, 1, "Subtree should have exactly one top-level comment") parentView := resp.Comments[0] assert.Equal(t, commentA, parentView.Comment.URI, "Parent comment should be the root of the subtree") assert.False(t, parentView.HasMore, "All direct replies are loaded") assert.Nil(t, resp.Cursor, "No cursor when all direct replies fit in one page")
// Direct replies nested beneath require.Len(t, parentView.Replies, 2, "Comment A should have 2 direct replies") replyURIs := make(map[string]*comments.ThreadViewComment) for _, r := range parentView.Replies { replyURIs[r.Comment.URI] = r } require.Contains(t, replyURIs, replyA1) require.Contains(t, replyURIs, replyA2) assert.NotContains(t, replyURIs, commentB, "Sibling top-level comment must not appear in subtree")
// Deeper descendant nested beneath Reply A1 replyA1View := replyURIs[replyA1] require.Len(t, replyA1View.Replies, 1, "Reply A1 should have its nested reply") assert.Equal(t, replyA1a, replyA1View.Replies[0].Comment.URI) })
t.Run("Depth relative to parent", func(t *testing.T) { t.Run("depth 0 returns only the parent", func(t *testing.T) { req := &comments.GetCommentsRequest{ PostURI: postURI, ParentRkey: commentARkey, Sort: "new", Depth: 0, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err) require.Len(t, resp.Comments, 1) parentView := resp.Comments[0] assert.Equal(t, commentA, parentView.Comment.URI) assert.Nil(t, parentView.Replies, "Depth 0 should not load replies") assert.True(t, parentView.HasMore, "HasMore should signal unloaded replies") })
t.Run("depth 1 returns parent and direct children only", func(t *testing.T) { req := &comments.GetCommentsRequest{ PostURI: postURI, ParentRkey: commentARkey, Sort: "new", Depth: 1, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err) require.Len(t, resp.Comments, 1) parentView := resp.Comments[0] require.Len(t, parentView.Replies, 2, "Depth 1 should include direct children")
for _, r := range parentView.Replies { assert.Nil(t, r.Replies, "Depth 1 should not include grandchildren") if r.Comment.URI == replyA1 { assert.True(t, r.HasMore, "Reply A1 has a hidden nested reply at the depth boundary") } } })
t.Run("subtree of a nested comment", func(t *testing.T) { req := &comments.GetCommentsRequest{ PostURI: postURI, ParentRkey: replyA1Rkey, Sort: "new", Depth: 10, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err) require.Len(t, resp.Comments, 1) parentView := resp.Comments[0] assert.Equal(t, replyA1, parentView.Comment.URI) require.Len(t, parentView.Replies, 1) assert.Equal(t, replyA1a, parentView.Replies[0].Comment.URI) }) })
t.Run("ParentNotFound for unknown rkey", func(t *testing.T) { req := &comments.GetCommentsRequest{ PostURI: postURI, ParentRkey: "3zzzzzzzzzzzz", Sort: "new", Depth: 10, Limit: 50, }
resp, err := service.GetComments(ctx, req) assert.Nil(t, resp) require.Error(t, err) assert.ErrorIs(t, err, comments.ErrParentNotFound) })
t.Run("ParentNotFound for rkey of comment in another post", func(t *testing.T) { otherPostURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Other Post", 0, time.Now()) otherComment := createTestCommentWithScore(t, db, testUser.DID, otherPostURI, otherPostURI, "Other post comment", 1, 0, time.Now()) otherRkey := strings.Split(otherComment, "/")[4]
req := &comments.GetCommentsRequest{ PostURI: postURI, // querying the original post with a foreign rkey ParentRkey: otherRkey, Sort: "new", Depth: 10, Limit: 50, }
resp, err := service.GetComments(ctx, req) assert.Nil(t, resp) require.Error(t, err) assert.ErrorIs(t, err, comments.ErrParentNotFound) })
t.Run("Pagination of parent's direct children", func(t *testing.T) { pagPostURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Subtree Pagination Post", 0, time.Now()) parentURI := createTestCommentWithScore(t, db, testUser.DID, pagPostURI, pagPostURI, "Paginated parent", 1, 0, time.Now().Add(-2*time.Hour)) parentRkey := strings.Split(parentURI, "/")[4]
childURIs := make(map[string]bool) for i := 0; i < 5; i++ { uri := createTestCommentWithScore(t, db, testUser.DID, pagPostURI, parentURI, fmt.Sprintf("Child %d", i), i, 0, time.Now().Add(-time.Duration(60-i)*time.Minute)) childURIs[uri] = true }
// First page of 3 direct children req1 := &comments.GetCommentsRequest{ PostURI: pagPostURI, ParentRkey: parentRkey, Sort: "new", Depth: 1, Limit: 3, } resp1, err := service.GetComments(ctx, req1) require.NoError(t, err) require.Len(t, resp1.Comments, 1) assert.Len(t, resp1.Comments[0].Replies, 3, "First page should have 3 children") require.NotNil(t, resp1.Cursor, "Cursor should be present for the next page of children") assert.True(t, resp1.Comments[0].HasMore, "HasMore should reflect remaining children")
// Second page via cursor: parent repeats as root, remaining children nested req2 := &comments.GetCommentsRequest{ PostURI: pagPostURI, ParentRkey: parentRkey, Sort: "new", Depth: 1, Limit: 3, Cursor: resp1.Cursor, } resp2, err := service.GetComments(ctx, req2) require.NoError(t, err) require.Len(t, resp2.Comments, 1) assert.Equal(t, parentURI, resp2.Comments[0].Comment.URI, "Parent should remain the root on subsequent pages") assert.Len(t, resp2.Comments[0].Replies, 2, "Second page should have remaining 2 children") assert.Nil(t, resp2.Cursor, "Cursor should be nil on last page") assert.False(t, resp2.Comments[0].HasMore)
// No duplicates and full coverage across pages seen := make(map[string]bool) for _, page := range []*comments.GetCommentsResponse{resp1, resp2} { for _, r := range page.Comments[0].Replies { assert.False(t, seen[r.Comment.URI], "Child %s should not appear in both pages", r.Comment.URI) assert.True(t, childURIs[r.Comment.URI], "Child %s should be a known child", r.Comment.URI) seen[r.Comment.URI] = true } } assert.Len(t, seen, 5, "All 5 children should be retrieved across pages") })
t.Run("Rkey collision resolves to earliest indexed", func(t *testing.T) { collisionPostURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Collision Post", 0, time.Now()) otherUser := fixtures.User(t, db, "subtree2.test", "did:plc:subtree456")
// Two commenters use the same rkey within the same post (astronomically unlikely with TIDs) sharedRkey := testkit.TID() firstURI := fmt.Sprintf("at://%s/social.coves.community.comment/%s", testUser.DID, sharedRkey) secondURI := fmt.Sprintf("at://%s/social.coves.community.comment/%s", otherUser.DID, sharedRkey)
insertCollisionComment := func(uri, did, content string, indexedAgo time.Duration) { _, err := db.ExecContext(ctx, ` INSERT INTO comments ( uri, cid, rkey, commenter_did, root_uri, root_cid, parent_uri, parent_cid, content, created_at, indexed_at ) VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9, NOW(), NOW() - $10::interval) `, uri, "bafyc"+did, sharedRkey, did, collisionPostURI, "bafyroot", collisionPostURI, "bafyparent", content, fmt.Sprintf("%d seconds", int(indexedAgo.Seconds()))) require.NoError(t, err, "Failed to insert collision comment") }
insertCollisionComment(firstURI, testUser.DID, "Indexed first", 60*time.Second) insertCollisionComment(secondURI, otherUser.DID, "Indexed second", 10*time.Second)
req := &comments.GetCommentsRequest{ PostURI: collisionPostURI, ParentRkey: sharedRkey, Sort: "new", Depth: 0, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err) require.Len(t, resp.Comments, 1) assert.Equal(t, firstURI, resp.Comments[0].Comment.URI, "Earliest indexed comment should win on rkey collision") })
t.Run("Deleted parent renders as placeholder with children intact", func(t *testing.T) { // GetByRootAndRkey deliberately includes soft-deleted rows so a permalink to a // deleted comment still shows its surviving replies. Someone adding // "deleted_at IS NULL" to that query would break this subtest. delPostURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Deleted Parent Post", 0, time.Now()) delParentURI := createTestCommentWithScore(t, db, testUser.DID, delPostURI, delPostURI, "Soon deleted parent", 3, 0, time.Now().Add(-30*time.Minute)) delChildURI := createTestCommentWithScore(t, db, testUser.DID, delPostURI, delParentURI, "Surviving child", 2, 0, time.Now().Add(-20*time.Minute)) delGrandchildURI := createTestCommentWithScore(t, db, testUser.DID, delPostURI, delChildURI, "Surviving grandchild", 1, 0, time.Now().Add(-10*time.Minute)) delParentRkey := strings.Split(delParentURI, "/")[4]
// Soft-delete the parent the same way the consumer does (see user_test.go) _, err := db.ExecContext(ctx, `UPDATE comments SET deleted_at = NOW() WHERE uri = $1`, delParentURI) require.NoError(t, err, "Failed to soft-delete parent comment")
req := &comments.GetCommentsRequest{ PostURI: delPostURI, ParentRkey: delParentRkey, Sort: "new", Depth: 10, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err, "Deleted parent should still resolve, not 404") require.Len(t, resp.Comments, 1, "Deleted parent should be the sole top-level comment")
parentView := resp.Comments[0] assert.Equal(t, delParentURI, parentView.Comment.URI) assert.True(t, parentView.Comment.IsDeleted, "Deleted parent should render as a [deleted] placeholder") assert.Nil(t, parentView.Comment.Record, "Deleted placeholder must not expose the original record content") assert.NotNil(t, parentView.Comment.DeletedAt, "Placeholder should carry the deletion timestamp")
// Children remain intact and nested beneath the placeholder require.Len(t, parentView.Replies, 1, "Deleted parent should preserve its child") childView := parentView.Replies[0] assert.Equal(t, delChildURI, childView.Comment.URI) assert.False(t, childView.Comment.IsDeleted, "Child should not inherit deletion") require.Len(t, childView.Replies, 1, "Grandchild should remain nested beneath the child") assert.Equal(t, delGrandchildURI, childView.Replies[0].Comment.URI) })
t.Run("ParentNotFound when viewer has blocked the parent's author", func(t *testing.T) { // A viewer who blocked the parent comment's author must get ParentNotFound, // as if the comment doesn't exist — consistent with feed/thread block filtering. // No FK to users, so the block row alone drives the filter (see user_journey_e2e_test.go). blockerDID := "did:plc:subtreeblocker1" _, err := db.ExecContext(ctx, ` INSERT INTO user_blocks (blocker_did, blocked_did, record_uri, record_cid) VALUES ($1, $2, $3, $4) `, blockerDID, testUser.DID, fmt.Sprintf("at://%s/social.coves.actor.block/subtreeblock", blockerDID), "bafysubtreeblockcid") require.NoError(t, err, "Failed to record viewer block")
blockedReq := &comments.GetCommentsRequest{ PostURI: postURI, ParentRkey: commentARkey, // Comment A is authored by testUser, whom the viewer blocked ViewerDID: &blockerDID, Sort: "new", Depth: 10, Limit: 50, }
resp, err := service.GetComments(ctx, blockedReq) assert.Nil(t, resp) require.Error(t, err) assert.ErrorIs(t, err, comments.ErrParentNotFound, "Blocked author's comment should behave as nonexistent for the blocker")
// The filter is viewer-scoped: the same request without a viewer succeeds anonReq := &comments.GetCommentsRequest{ PostURI: postURI, ParentRkey: commentARkey, Sort: "new", Depth: 10, Limit: 50, } anonResp, err := service.GetComments(ctx, anonReq) require.NoError(t, err, "Anonymous viewer should still see the subtree") require.Len(t, anonResp.Comments, 1) assert.Equal(t, commentA, anonResp.Comments[0].Comment.URI)
// ...and so does a viewer who hasn't blocked anyone nonBlockerDID := "did:plc:subtreeviewer1" nonBlockerReq := &comments.GetCommentsRequest{ PostURI: postURI, ParentRkey: commentARkey, ViewerDID: &nonBlockerDID, Sort: "new", Depth: 10, Limit: 50, } nonBlockerResp, err := service.GetComments(ctx, nonBlockerReq) require.NoError(t, err, "Non-blocking viewer should still see the subtree") require.Len(t, nonBlockerResp.Comments, 1) assert.Equal(t, commentA, nonBlockerResp.Comments[0].Comment.URI) })
t.Run("RootNotFound takes precedence for nonexistent post", func(t *testing.T) { // A bogus post URI with a real comment's rkey must fail on the post lookup // (RootNotFound), not fall through to the parent lookup (ParentNotFound) req := &comments.GetCommentsRequest{ PostURI: fmt.Sprintf("at://%s/social.coves.community.post/3nonexistent", testUser.DID), ParentRkey: commentARkey, // real rkey, wrong post Sort: "new", Depth: 10, Limit: 50, }
resp, err := service.GetComments(ctx, req) assert.Nil(t, resp) require.Error(t, err) assert.ErrorIs(t, err, comments.ErrRootNotFound, "Missing post should surface as RootNotFound") assert.NotErrorIs(t, err, comments.ErrParentNotFound, "Post lookup failure must not masquerade as ParentNotFound") })
t.Run("Behavior unchanged without parentRkey", func(t *testing.T) { req := &comments.GetCommentsRequest{ PostURI: postURI, Sort: "new", Depth: 10, Limit: 50, }
resp, err := service.GetComments(ctx, req) require.NoError(t, err) // GreaterOrEqual (not exact Len) so this subtest doesn't break if the shared // fixture ever gains another top-level comment; the known URIs are asserted below assert.GreaterOrEqual(t, len(resp.Comments), 2, "Full thread should still return the known top-level comments")
topLevelURIs := make(map[string]bool) for _, tv := range resp.Comments { topLevelURIs[tv.Comment.URI] = true } assert.True(t, topLevelURIs[commentA], "Comment A should be top-level") assert.True(t, topLevelURIs[commentB], "Comment B should be top-level") })}
// TestCommentQuery_ParentRkeyHTTPHandler tests the real XRPC handler with parentRkeyfunc TestCommentQuery_ParentRkeyHTTPHandler(t *testing.T) { t.Parallel() db := testkit.DB(t)
ctx := context.Background() testUser := fixtures.User(t, db, "subtreehttp.test", "did:plc:subtreehttp123") testCommunity, err := fixtures.Community(ctx, db, "subtreehttpcomm", "ownersubtreehttp.test") require.NoError(t, err)
postURI := fixtures.Post(t, db, testCommunity, testUser.DID, "Subtree HTTP Test", 0, time.Now()) commentURI := createTestCommentWithScore(t, db, testUser.DID, postURI, postURI, "Parent comment", 5, 0, time.Now().Add(-30*time.Minute)) replyURI := createTestCommentWithScore(t, db, testUser.DID, postURI, commentURI, "Child comment", 2, 0, time.Now().Add(-10*time.Minute)) commentRkey := strings.Split(commentURI, "/")[4]
// Use the real XRPC handler + service adapter (same wiring as cmd/server/main.go) handler := commentsAPI.NewGetCommentsHandler(commentsAPI.NewServiceAdapter(setupCommentService(db)), nil, moderation.NewAllowlistAuthority(nil), "did:plc:testinstance")
t.Run("Subtree via parentRkey", func(t *testing.T) { req := httptest.NewRequest("GET", fmt.Sprintf("/xrpc/social.coves.community.comment.getComments?post=%s&parentRkey=%s&sort=new&depth=10&limit=50", postURI, commentRkey), nil) w := httptest.NewRecorder()
handler.HandleGetComments(w, req)
require.Equal(t, http.StatusOK, w.Code) var resp comments.GetCommentsResponse require.NoError(t, json.NewDecoder(w.Body).Decode(&resp)) require.Len(t, resp.Comments, 1, "Parent should be the sole top-level comment") assert.Equal(t, commentURI, resp.Comments[0].Comment.URI) require.Len(t, resp.Comments[0].Replies, 1) assert.Equal(t, replyURI, resp.Comments[0].Replies[0].Comment.URI) })
t.Run("ParentNotFound error shape", func(t *testing.T) { req := httptest.NewRequest("GET", fmt.Sprintf("/xrpc/social.coves.community.comment.getComments?post=%s&parentRkey=3zzzzzzzzzzzz", postURI), nil) w := httptest.NewRecorder()
handler.HandleGetComments(w, req)
assert.Equal(t, http.StatusNotFound, w.Code) var errResp struct { Error string `json:"error"` Message string `json:"message"` } require.NoError(t, json.NewDecoder(w.Body).Decode(&errResp)) assert.Equal(t, "ParentNotFound", errResp.Error) })
t.Run("Invalid parentRkey syntax rejected", func(t *testing.T) { req := httptest.NewRequest("GET", fmt.Sprintf("/xrpc/social.coves.community.comment.getComments?post=%s&parentRkey=%s", postURI, "not%20a%20valid%20rkey!"), nil) w := httptest.NewRecorder()
handler.HandleGetComments(w, req)
assert.Equal(t, http.StatusBadRequest, w.Code) var errResp struct { Error string `json:"error"` Message string `json:"message"` } require.NoError(t, json.NewDecoder(w.Body).Decode(&errResp)) assert.Equal(t, "InvalidRequest", errResp.Error) })
t.Run("Without parentRkey returns full thread", func(t *testing.T) { req := httptest.NewRequest("GET", fmt.Sprintf("/xrpc/social.coves.community.comment.getComments?post=%s&sort=new&depth=10&limit=50", postURI), nil) w := httptest.NewRecorder()
handler.HandleGetComments(w, req)
require.Equal(t, http.StatusOK, w.Code) var resp comments.GetCommentsResponse require.NoError(t, json.NewDecoder(w.Body).Decode(&resp)) require.Len(t, resp.Comments, 1, "Post has one top-level comment") assert.Equal(t, commentURI, resp.Comments[0].Comment.URI) })}
// Helper: setupCommentService creates a comment service for testingfunc setupCommentService(db *sql.DB) comments.Service { commentRepo := postgres.NewCommentRepository(db) postRepo := postgres.NewPostRepository(db) userRepo := postgres.NewUserRepository(db) communityRepo := postgres.NewCommunityRepository(db, credentialciphertest.Fixed()) // Use factory constructor with nil factory - these tests only use the read path (GetComments) return comments.NewCommentServiceWithPDSFactory(commentRepo, userRepo, postRepo, communityRepo, nil, nil)}
// Helper: createTestCommentWithScore creates a comment with specific vote countsfunc createTestCommentWithScore(t *testing.T, db *sql.DB, commenterDID, rootURI, parentURI, content string, upvotes, downvotes int, createdAt time.Time) string { t.Helper()
ctx := context.Background() rkey := testkit.TID() uri := fmt.Sprintf("at://%s/social.coves.community.comment/%s", commenterDID, rkey)
// Insert comment directly for speed _, err := db.ExecContext(ctx, ` INSERT INTO comments ( uri, cid, rkey, commenter_did, root_uri, root_cid, parent_uri, parent_cid, content, created_at, indexed_at, upvote_count, downvote_count, score ) VALUES ( $1, $2, $3, $4, $5, $6, $7, $8, $9, $10, NOW(), $11, $12, $13 ) `, uri, fmt.Sprintf("bafyc%s", rkey), rkey, commenterDID, rootURI, "bafyroot", parentURI, "bafyparent", content, createdAt, upvotes, downvotes, upvotes-downvotes)
require.NoError(t, err, "Failed to create test comment")
// Update reply count on parent if it's a nested comment if parentURI != rootURI { _, _ = db.ExecContext(ctx, ` UPDATE comments SET reply_count = reply_count + 1 WHERE uri = $1 `, parentURI) } else { // Update comment count on post if top-level _, _ = db.ExecContext(ctx, ` UPDATE posts SET comment_count = comment_count + 1 WHERE uri = $1 `, parentURI) }
return uri}
// Helper: Service adapter for HTTP handler testingtype testCommentServiceAdapter struct { service comments.Service}
func (s *testCommentServiceAdapter) GetComments(r *http.Request, req *testGetCommentsRequest) (*comments.GetCommentsResponse, error) { ctx := r.Context()
serviceReq := &comments.GetCommentsRequest{ PostURI: req.PostURI, Sort: req.Sort, Timeframe: req.Timeframe, Depth: req.Depth, Limit: req.Limit, Cursor: req.Cursor, ViewerDID: req.ViewerDID, }
return s.service.GetComments(ctx, serviceReq)}
type testGetCommentsRequest struct { Cursor *string ViewerDID *string PostURI string Sort string Timeframe string Depth int Limit int}
func setupCommentServiceAdapter(db *sql.DB) *testCommentServiceAdapter { commentRepo := postgres.NewCommentRepository(db) postRepo := postgres.NewPostRepository(db) userRepo := postgres.NewUserRepository(db) communityRepo := postgres.NewCommunityRepository(db, credentialciphertest.Fixed()) // Use factory constructor with nil factory - these tests only use the read path (GetComments) service := comments.NewCommentServiceWithPDSFactory(commentRepo, userRepo, postRepo, communityRepo, nil, nil) return &testCommentServiceAdapter{service: service}}
// Helper: Simple HTTP handler wrapper for testingtype testGetCommentsHandler struct { service *testCommentServiceAdapter}
func (h *testGetCommentsHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) { if r.Method != http.MethodGet { http.Error(w, "Method not allowed", http.StatusMethodNotAllowed) return }
query := r.URL.Query() post := query.Get("post")
if post == "" { http.Error(w, "post parameter is required", http.StatusBadRequest) return }
sort := query.Get("sort") if sort == "" { sort = "hot" }
depth := 10 if d := query.Get("depth"); d != "" { if _, err := fmt.Sscanf(d, "%d", &depth); err != nil { http.Error(w, "invalid depth", http.StatusBadRequest) return } }
limit := 50 if l := query.Get("limit"); l != "" { if _, err := fmt.Sscanf(l, "%d", &limit); err != nil { http.Error(w, "invalid limit", http.StatusBadRequest) return } }
req := &testGetCommentsRequest{ PostURI: post, Sort: sort, Depth: depth, Limit: limit, }
resp, err := h.service.GetComments(r, req) if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return }
w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusOK) _ = json.NewEncoder(w).Encode(resp)}