Files
go-fa-api/comment_parser_test.go
2026-05-25 22:27:18 +02:00

84 lines
2.6 KiB
Go

package fa
import (
"bytes"
"strings"
"testing"
"github.com/PuerkitoBio/goquery"
)
const syntheticCommentsHTML = `<html><body>
<div id="cid:111" class="comment-container c-0" data-depth="0">
<a class="iconusername" href="/user/alice/"><img src="//d.example/a.png"/>Alice</a>
<span class="popup_date" title="Apr 5, 2026 01:00 PM">today</span>
<div class="comment-user-text"><p>First!</p></div>
</div>
<div id="cid:112" class="comment-container c-1 replyto-111" data-depth="1" data-parent="111">
<a class="iconusername" href="/user/bob/"><img src="//d.example/b.png"/>Bob</a>
<span class="popup_date" title="Apr 5, 2026 01:05 PM">today</span>
<div class="comment-user-text"><p>Reply to first</p></div>
</div>
<div id="cid:113" class="comment-container comment-deleted c-0">
<span class="popup_date" title="Apr 5, 2026 01:10 PM">today</span>
<div class="comment-user-text">[deleted]</div>
</div>
</body></html>`
func TestParseComments_Synthetic(t *testing.T) {
doc, err := goquery.NewDocumentFromReader(strings.NewReader(syntheticCommentsHTML))
if err != nil {
t.Fatalf("setup: %v", err)
}
cs := parseComments(doc)
if len(cs) != 3 {
t.Fatalf("comments = %d; want 3", len(cs))
}
if cs[0].ID != 111 || cs[0].Author.Name != "alice" || cs[0].Depth != 0 || cs[0].Parent != 0 {
t.Errorf("comment[0] = %+v", cs[0])
}
if cs[1].ID != 112 || cs[1].Author.Name != "bob" || cs[1].Depth != 1 || cs[1].Parent != 111 {
t.Errorf("comment[1] = %+v", cs[1])
}
if !cs[2].Deleted {
t.Errorf("comment[2].Deleted = false; want true")
}
if !strings.Contains(cs[0].BodyText, "First!") {
t.Errorf("comment[0].BodyText = %q", cs[0].BodyText)
}
}
func TestDepthFromWidthStyle(t *testing.T) {
cases := map[string]int{
"width: 99%; padding: 0": 0,
"width:96%": 1,
"width: 93%": 2,
"width: 90%": 3,
"width: 50%": 16,
"width: 100%": 0,
"no width here": 0,
"width: abc%": 0,
}
for in, want := range cases {
if got := depthFromWidthStyle(in); got != want {
t.Errorf("depthFromWidthStyle(%q) = %d; want %d", in, got, want)
}
}
}
func TestParseComments_RealFixture(t *testing.T) {
raw := loadFixture(t, "comments_submission.html")
doc, err := goquery.NewDocumentFromReader(bytes.NewReader(raw))
if err != nil {
t.Fatalf("read doc: %v", err)
}
cs := parseComments(doc)
// Comments may be empty on a submission with no comments; just ensure
// the parser doesn't crash and yields sane values when populated.
for i, c := range cs {
if c.Depth < 0 {
t.Errorf("comment %d: negative depth %d", i, c.Depth)
}
}
}