// SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved. // SPDX-License-Identifier: Apache-2.0 package readability // import "miniflux.app/v2/internal/reader/readability" import ( "bytes" "fmt" "os" "strings" "testing" "github.com/PuerkitoBio/goquery" "golang.org/x/net/html" ) func BenchmarkExtractContent(b *testing.B) { var testCases = map[string][]byte{ "miniflux_github.html": {}, "miniflux_wikipedia.html": {}, } for filename := range testCases { data, err := os.ReadFile("testdata/" + filename) if err != nil { b.Fatalf(`Unable to read file %q: %v`, filename, err) } testCases[filename] = data } for range b.N { for _, v := range testCases { ExtractContent(bytes.NewReader(v)) } } } func BenchmarkGetWeight(b *testing.B) { testCases := []string{ "p-3 color-bg-accent-emphasis color-fg-on-emphasis show-on-focus js-skip-to-content", "d-flex flex-column mb-3", "AppHeader-search-control AppHeader-search-control-overflow", "Button Button--iconOnly Button--invisible Button--medium mr-1 px-2 py-0 d-flex flex-items-center rounded-1 color-fg-muted", "sr-only", "validation-12753bbc-b4d1-4e10-bec6-92e585d1699d", } for range b.N { for _, v := range testCases { getWeight(v) } } } func BenchmarkTransformMisusedDivsIntoParagraphs(b *testing.B) { html := `
Paragraph content
Some content
Code block with nested span # exit 1
Some content
Code block with nested span # exit 1
`,
expected: `
`,
},
{
name: "preserves elements within pre tags",
html: ``, expected: `
`, }, { name: "case insensitive matching", html: `
paragraph
`, expected: `paragraph
`, }, { name: "removes nested unlikely elements", html: `good content
good content
`,
description: "Elements within pre tags should be preserved",
},
{
name: "preserves elements in code tags",
html: `
`,
description: "Elements within code tags should be preserved",
},
{
name: "preserves nested elements in code blocks",
html: `
`,
description: "Deeply nested elements in code blocks should be preserved",
},
{
name: "preserves elements in mixed code scenarios",
html: `
This is the main content.
This is the main content.
Main content here.
Main content here.
Main content here.
Main content here.
This is content.
Some text with many different links here.
`, expected: ``, }, { name: "paragraph with low link density and long content", html: `This is content.
This is a very long paragraph with substantial content that should be included because it has enough text and minimal links. This paragraph contains meaningful information that readers would want to see. The content is substantial and valuable.
`, expected: `This is content.
This is a very long paragraph with substantial content that should be included because it has enough text and minimal links. This paragraph contains meaningful information that readers would want to see. The content is substantial and valuable.
This is content.
Short sentence.
`, expected: `This is content.
Short sentence.
This is content.
Short fragment
`, expected: `This is content.
Short fragment
Main content.
Good long content with enough text to be included based on length criteria and low link density.
Bad content with too many links relative to text.
Good short.
Nested paragraph content.
Nested span.Sibling paragraph.
`, expected: `Sibling paragraph.
Nested paragraph content.
Nested span.Some content here.
`, expected: `Some content here.
This is the main article content with substantial text.
This sibling has high score due to good class name.
This is a standalone paragraph with enough content to be included based on length and should be appended.
Short.
This has too many links for its size.
` doc, err := goquery.NewDocumentFromReader(strings.NewReader(html)) if err != nil { t.Fatalf("Failed to parse HTML: %v", err) } candidates := getCandidates(doc) topCandidate := getTopCandidate(doc, candidates) result := getArticle(topCandidate, candidates) // Verify the structure contains expected elements resultDoc, err := goquery.NewDocumentFromReader(strings.NewReader(result)) if err != nil { t.Fatalf("Failed to parse result HTML: %v", err) } // Should contain the main content if resultDoc.Find("p:contains('main article content')").Length() == 0 { t.Error("Main content not found in result") } // Should contain high-scoring sibling if resultDoc.Find("p:contains('high score')").Length() == 0 { t.Error("High-scoring sibling not found in result") } // Should contain long standalone paragraph if resultDoc.Find("p:contains('standalone paragraph')").Length() == 0 { t.Error("Long standalone paragraph not found in result") } // Should contain short paragraph with sentence if resultDoc.Find("p:contains('Short.')").Length() == 0 { t.Error("Short paragraph with sentence not found in result") } // Should NOT contain low-scoring sibling if resultDoc.Find("p:contains('low score')").Length() > 0 { t.Error("Low-scoring sibling incorrectly included in result") } // Should NOT contain paragraph with too many links if resultDoc.Find("p:contains('too many')").Length() > 0 { t.Error("Paragraph with too many links incorrectly included in result") } } func TestGetArticleSiblingScoreThreshold(t *testing.T) { testCases := []struct { name string topScore float32 expectedThreshold float32 }{ { name: "high score candidate", topScore: 100, expectedThreshold: 20, // 100 * 0.2 = 20 }, { name: "medium score candidate", topScore: 50, expectedThreshold: 10, // max(10, 50 * 0.2) = max(10, 10) = 10 }, { name: "low score candidate", topScore: 30, expectedThreshold: 10, // max(10, 30 * 0.2) = max(10, 6) = 10 }, { name: "very low score candidate", topScore: 5, expectedThreshold: 10, // max(10, 5 * 0.2) = max(10, 1) = 10 }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { // Create a simple HTML structure html := `Main content
Sibling content
Main content
This is a paragraph with lots of links that should make it excluded based on density.
`, checkParagraph: "This is a paragraph with lots of", shouldInclude: false, reason: "Long paragraph with >= 25% link density should be excluded", }, { name: "long paragraph with low link density should be included", html: `Main content
This is a very long paragraph with substantial content that has more than eighty characters and contains only one link so the link density is very low.
`, checkParagraph: "This is a very long paragraph", shouldInclude: true, reason: "Long paragraph with < 25% link density should be included", }, { name: "short paragraph with no links and sentence should be included", html: `Main content
Short sentence.
`, checkParagraph: "Short sentence.", shouldInclude: true, reason: "Short paragraph with 0% link density and sentence should be included", }, { name: "short paragraph with no links but no sentence should be excluded", html: `Main content
fragment
`, checkParagraph: "fragment", shouldInclude: false, reason: "Short paragraph with 0% link density but no sentence should be excluded", }, { name: "short paragraph with links should be excluded", html: `Main content
Short with link.
`, checkParagraph: "Short with", shouldInclude: false, reason: "Short paragraph with any links should be excluded", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { // Create a custom scenario where the paragraphs are NOT in the candidates list // so we can test the paragraph-specific logic doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html)) if err != nil { t.Fatalf("Failed to parse HTML: %v", err) } // Create artificial candidates that only include the main div, not the paragraphs mainDiv := doc.Find("#main").Get(0) topCandidate := &candidate{ selection: doc.Find("#main"), score: 50, } candidates := candidateList{ mainDiv: topCandidate, // Deliberately not including the test paragraphs as candidates } result := getArticle(topCandidate, candidates) included := strings.Contains(result, tc.checkParagraph) if included != tc.shouldInclude { t.Errorf("%s: Expected included=%v, got included=%v\nReason: %s\nResult: %s", tc.name, tc.shouldInclude, included, tc.reason, result) } }) } } func TestGetArticleLinkDensityThresholds(t *testing.T) { testCases := []struct { name string content string expectIncluded bool description string }{ { name: "long content with no links", content: "This is a very long paragraph with substantial content that should definitely be included because it has more than 80 characters and no links at all.", expectIncluded: true, description: "Content >= 80 chars with 0% link density should be included", }, { name: "long content with acceptable link density", content: "This is a very long paragraph with substantial content and one small link that should be included because the link density is well below 25%.", expectIncluded: true, description: "Content >= 80 chars with < 25% link density should be included", }, { name: "long content with high link density", content: "Short text with many different links here and more links.", expectIncluded: true, // This appears to be included because it's processed as a sibling, not just through paragraph logic description: "Content with high link density - actual behavior includes siblings", }, { name: "short content with no links and sentence", content: "This is a sentence.", expectIncluded: true, description: "Content < 80 chars with 0% link density and proper sentence should be included", }, { name: "short content with no links but no sentence", content: "Just a fragment", expectIncluded: true, // The algorithm actually includes all siblings, paragraph rules are additional description: "Content < 80 chars with 0% link density but no sentence - still included as sibling", }, { name: "short content with links", content: "Text with link.", expectIncluded: true, // Still included as sibling description: "Content < 80 chars with any links - still included as sibling", }, { name: "edge case: exactly 80 characters no links", content: "This paragraph has exactly eighty characters and should be included ok.", expectIncluded: true, description: "Content with exactly 80 chars and no links should be included", }, { name: "edge case: 79 characters no links with sentence", content: "This paragraph has seventy-nine characters and should be included.", expectIncluded: true, description: "Content with 79 chars, no links, and sentence should be included", }, { name: "sentence with period at end", content: "Sentence ending with period.", expectIncluded: true, description: "Short content ending with period should be included", }, { name: "sentence with period in middle", content: "Sentence with period. And more", expectIncluded: true, description: "Short content with period in middle should be included", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { html := fmt.Sprintf(`Main content
%s
`, tc.content) doc, err := goquery.NewDocumentFromReader(strings.NewReader(html)) if err != nil { t.Fatalf("Failed to parse HTML: %v", err) } candidates := getCandidates(doc) topCandidate := getTopCandidate(doc, candidates) result := getArticle(topCandidate, candidates) // Check if the test content was included included := strings.Contains(result, tc.content) || strings.Contains(result, strings.ReplaceAll(tc.content, `'`, `"`)) if included != tc.expectIncluded { t.Errorf("%s: Expected included=%v, got included=%v\nContent: %s\nResult: %s", tc.description, tc.expectIncluded, included, tc.content, result) } }) } } func TestGetArticleTagWrapping(t *testing.T) { // Test that paragraph elements keep their tag, others become div html := `Main content
Paragraph content that should stay as p tag.
tags paragraphElements := resultDoc.Find("p") foundParagraphContent := false paragraphElements.Each(func(i int, s *goquery.Selection) { if strings.Contains(s.Text(), "Paragraph content") { foundParagraphContent = true } }) if !foundParagraphContent { t.Error("Paragraph content should be wrapped in
tags") } // Check that non-paragraph content is wrapped in
Content
Content
Paragraph in nested structure.
Paragraph in nested structure.
Some code`, expectedScore: 3, expectedTag: "pre", }, { name: "td element with no class or id", html: `
Table cell |
Quote`, expectedScore: 3, expectedTag: "blockquote", }, { name: "img element with no class or id", html: `
Header cell |
---|
Paragraph content
`, expectedScore: 0, expectedTag: "p", }, { name: "span element with no class or id (default case)", html: `Span content`, expectedScore: 0, expectedTag: "span", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html)) if err != nil { t.Fatal(err) } selection := doc.Find(tc.expectedTag) if selection.Length() == 0 { t.Fatalf("Could not find element with tag %s", tc.expectedTag) } candidate := scoreNode(selection) if candidate.score != tc.expectedScore { t.Errorf("Expected score %f, got %f", tc.expectedScore, candidate.score) } if candidate.selection != selection { t.Error("Expected selection to be preserved in candidate") } if candidate.Node() == nil { t.Errorf("Expected valid node, got nil") } else if candidate.Node().Data != tc.expectedTag { t.Errorf("Expected node tag %s, got %s", tc.expectedTag, candidate.Node().Data) } }) } } func TestScoreNodeWithClassWeights(t *testing.T) { testCases := []struct { name string html string expectedScore float32 description string }{ { name: "div with positive class", html: `Paragraph
`, expectedScore: 0, // 0 (p) + 0 (neutral class) + 0 (neutral id) description: "p base score with neutral class and id", }, } for _, tc := range testCases { t.Run(tc.name, func(t *testing.T) { doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html)) if err != nil { t.Fatal(err) } // Find the first non-html/body element selection := doc.Find("div, h1, h2, h3, h4, h5, h6, ul, ol, p, pre, blockquote, img, td, th, address, dl, dd, dt, li, form, span").First() if selection.Length() == 0 { t.Fatal("Could not find element") } candidate := scoreNode(selection) if candidate.score != tc.expectedScore { t.Errorf("%s: Expected score %f, got %f", tc.description, tc.expectedScore, candidate.score) } }) } } func TestScoreNodeEdgeCases(t *testing.T) { t.Run("empty selection", func(t *testing.T) { doc, err := goquery.NewDocumentFromReader(strings.NewReader(``)) if err != nil { t.Fatal(err) } // Create empty selection emptySelection := doc.Find("nonexistent") if emptySelection.Length() != 0 { t.Fatal("Expected empty selection") } // scoreNode should handle empty selection gracefully candidate := scoreNode(emptySelection) if candidate == nil { t.Error("Expected non-nil candidate even for empty selection") } // Should have score 0 and empty selection if candidate != nil && candidate.score != 0 { t.Errorf("Expected score 0 for empty selection, got %f", candidate.score) } if candidate.selection.Length() != 0 { t.Error("Expected candidate to preserve empty selection") } // Node() should return nil for empty selection if candidate.Node() != nil { t.Error("Expected Node() to return nil for empty selection") } // String() should handle empty selection gracefully str := candidate.String() expected := "empty => 0.000000" if str != expected { t.Errorf("Expected String() to return %q, got %q", expected, str) } }) t.Run("multiple elements in selection", func(t *testing.T) { html := `First paragraph
Text
Simple text content
`, description: "div containing only text should be converted to p", }, { name: "div with inline elements should become paragraph", input: `Text with inline and emphasis
`, description: "div with inline elements should be converted to p", }, { name: "div with strong and other inline elements", input: `Some bold and italic text
`, description: "div with inline formatting should be converted to p", }, { name: "div with anchor tag should NOT become paragraph", input: `Nested paragraph
Nested paragraph
Quote
Quote
Nested div
Code block
Code block
Cell |
Cell |
`, description: "div with only whitespace should be converted to p", }, { name: "div with self-closing anchor tag should NOT become paragraph", input: ``, expected: `
Has paragraph
Text only
Has paragraph
More text
`, description: "should transform multiple divs appropriately", }, { name: "nested divs where inner gets transformed", input: `Paragraph
Inner text only
Paragraph
quote`, shouldMatch: true, description: "should match blockquote tags", }, { name: "dl tag", html: `
paragraph
`, shouldMatch: true, description: "should match p tags", }, { name: "pre tag", html: `code`, shouldMatch: true, description: "should match pre tags", }, { name: "table tag", html: `
No divs here
Just other elements` doc, err := goquery.NewDocumentFromReader(strings.NewReader(html)) if err != nil { t.Fatal(err) } // Should not panic or cause issues transformMisusedDivsIntoParagraphs(doc) bodyHtml, _ := doc.Find("body").Html() expected := `No divs here
Just other elements` if strings.TrimSpace(bodyHtml) != expected { t.Errorf("Expected no changes to document without divs") } }) t.Run("empty document", func(t *testing.T) { html := `` doc, err := goquery.NewDocumentFromReader(strings.NewReader(html)) if err != nil { t.Fatal(err) } // Should not panic with empty document transformMisusedDivsIntoParagraphs(doc) bodyHtml, _ := doc.Find("body").Html() if strings.TrimSpace(bodyHtml) != "" { t.Errorf("Expected empty body to remain empty") } }) t.Run("deeply nested divs", func(t *testing.T) { html := `Deep text
Block element
Comment text
`, expected: "p.comment => -25.000000", setup: func(doc *goquery.Document) *candidate { selection := doc.Find("p") return scoreNode(selection) }, }, { name: "heading candidate with positive id", html: `Paragraph
Good content
`, setup: func(doc *goquery.Document) candidateList { candidates := make(candidateList) divSelection := doc.Find("div") divCandidate := scoreNode(divSelection) candidates[divSelection.Get(0)] = divCandidate pSelection := doc.Find("p") pCandidate := scoreNode(pSelection) candidates[pSelection.Get(0)] = pCandidate return candidates }, }, { name: "candidate with empty selection", html: `