readability_test.go 46 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332
  1. // SPDX-FileCopyrightText: Copyright The Miniflux Authors. All rights reserved.
  2. // SPDX-License-Identifier: Apache-2.0
  3. package readability // import "miniflux.app/v2/internal/reader/readability"
  4. import (
  5. "bytes"
  6. "fmt"
  7. "os"
  8. "strings"
  9. "testing"
  10. "github.com/PuerkitoBio/goquery"
  11. )
  12. func TestBaseURL(t *testing.T) {
  13. html := `
  14. <html>
  15. <head>
  16. <base href="https://example.org/ ">
  17. </head>
  18. <body>
  19. <article>
  20. Some content
  21. </article>
  22. </body>
  23. </html>`
  24. baseURL, _, err := ExtractContent(strings.NewReader(html))
  25. if err != nil {
  26. t.Fatal(err)
  27. }
  28. if baseURL != "https://example.org/" {
  29. t.Errorf(`Unexpected base URL, got %q instead of "https://example.org/"`, baseURL)
  30. }
  31. }
  32. func TestMultipleBaseURL(t *testing.T) {
  33. html := `
  34. <html>
  35. <head>
  36. <base href="https://example.org/ ">
  37. <base href="https://example.com/ ">
  38. </head>
  39. <body>
  40. <article>
  41. Some content
  42. </article>
  43. </body>
  44. </html>`
  45. baseURL, _, err := ExtractContent(strings.NewReader(html))
  46. if err != nil {
  47. t.Fatal(err)
  48. }
  49. if baseURL != "https://example.org/" {
  50. t.Errorf(`Unexpected base URL, got %q instead of "https://example.org/"`, baseURL)
  51. }
  52. }
  53. func TestRelativeBaseURL(t *testing.T) {
  54. html := `
  55. <html>
  56. <head>
  57. <base href="/test/ ">
  58. </head>
  59. <body>
  60. <article>
  61. Some content
  62. </article>
  63. </body>
  64. </html>`
  65. baseURL, _, err := ExtractContent(strings.NewReader(html))
  66. if err != nil {
  67. t.Fatal(err)
  68. }
  69. if baseURL != "" {
  70. t.Errorf(`Unexpected base URL, got %q`, baseURL)
  71. }
  72. }
  73. func TestWithoutBaseURL(t *testing.T) {
  74. html := `
  75. <html>
  76. <head>
  77. <title>Test</title>
  78. </head>
  79. <body>
  80. <article>
  81. Some content
  82. </article>
  83. </body>
  84. </html>`
  85. baseURL, _, err := ExtractContent(strings.NewReader(html))
  86. if err != nil {
  87. t.Fatal(err)
  88. }
  89. if baseURL != "" {
  90. t.Errorf(`Unexpected base URL, got %q instead of ""`, baseURL)
  91. }
  92. }
  93. func TestRemoveStyleScript(t *testing.T) {
  94. html := `
  95. <html>
  96. <head>
  97. <title>Test</title>
  98. <script src="tololo.js"></script>
  99. </head>
  100. <body>
  101. <script src="tololo.js"></script>
  102. <style>
  103. h1 {color:red;}
  104. p {color:blue;}
  105. </style>
  106. <article>Some content</article>
  107. </body>
  108. </html>`
  109. want := `<div><div><article>Somecontent</article></div></div>`
  110. _, content, err := ExtractContent(strings.NewReader(html))
  111. if err != nil {
  112. t.Fatal(err)
  113. }
  114. content = strings.ReplaceAll(content, "\n", "")
  115. content = strings.ReplaceAll(content, " ", "")
  116. content = strings.ReplaceAll(content, "\t", "")
  117. if content != want {
  118. t.Errorf(`Invalid content, got %s instead of %s`, content, want)
  119. }
  120. }
  121. func TestRemoveBlacklist(t *testing.T) {
  122. html := `
  123. <html>
  124. <head>
  125. <title>Test</title>
  126. </head>
  127. <body>
  128. <article class="super-ad">Some content</article>
  129. <article class="g-plus-crap">Some other thing</article>
  130. <article class="stuff popupbody">And more</article>
  131. <article class="legit">Valid!</article>
  132. </body>
  133. </html>`
  134. want := `<div><div><articleclass="legit">Valid!</article></div></div>`
  135. _, content, err := ExtractContent(strings.NewReader(html))
  136. if err != nil {
  137. t.Fatal(err)
  138. }
  139. content = strings.ReplaceAll(content, "\n", "")
  140. content = strings.ReplaceAll(content, " ", "")
  141. content = strings.ReplaceAll(content, "\t", "")
  142. if content != want {
  143. t.Errorf(`Invalid content, got %s instead of %s`, content, want)
  144. }
  145. }
  146. func TestNestedSpanInCodeBlock(t *testing.T) {
  147. html := `
  148. <html>
  149. <head>
  150. <title>Test</title>
  151. </head>
  152. <body>
  153. <article><p>Some content</p><pre><code class="hljs-built_in">Code block with <span class="hljs-built_in">nested span</span> <span class="hljs-comment"># exit 1</span></code></pre></article>
  154. </body>
  155. </html>`
  156. want := `<div><div><p>Some content</p><pre><code class="hljs-built_in">Code block with <span class="hljs-built_in">nested span</span> <span class="hljs-comment"># exit 1</span></code></pre></div></div>`
  157. _, result, err := ExtractContent(strings.NewReader(html))
  158. if err != nil {
  159. t.Fatal(err)
  160. }
  161. if result != want {
  162. t.Errorf(`Invalid content, got %s instead of %s`, result, want)
  163. }
  164. }
  165. func BenchmarkExtractContent(b *testing.B) {
  166. var testCases = map[string][]byte{
  167. "miniflux_github.html": {},
  168. "miniflux_wikipedia.html": {},
  169. }
  170. for filename := range testCases {
  171. data, err := os.ReadFile("testdata/" + filename)
  172. if err != nil {
  173. b.Fatalf(`Unable to read file %q: %v`, filename, err)
  174. }
  175. testCases[filename] = data
  176. }
  177. for range b.N {
  178. for _, v := range testCases {
  179. ExtractContent(bytes.NewReader(v))
  180. }
  181. }
  182. }
  183. func TestGetClassWeight(t *testing.T) {
  184. testCases := []struct {
  185. name string
  186. html string
  187. expected float32
  188. }{
  189. {
  190. name: "no class or id",
  191. html: `<div>content</div>`,
  192. expected: 0,
  193. },
  194. {
  195. name: "positive class only",
  196. html: `<div class="article">content</div>`,
  197. expected: 25,
  198. },
  199. {
  200. name: "negative class only",
  201. html: `<div class="comment">content</div>`,
  202. expected: -25,
  203. },
  204. {
  205. name: "positive id only",
  206. html: `<div id="main">content</div>`,
  207. expected: 25,
  208. },
  209. {
  210. name: "negative id only",
  211. html: `<div id="sidebar">content</div>`,
  212. expected: -25,
  213. },
  214. {
  215. name: "positive class and positive id",
  216. html: `<div class="content" id="main">content</div>`,
  217. expected: 50,
  218. },
  219. {
  220. name: "negative class and negative id",
  221. html: `<div class="comment" id="sidebar">content</div>`,
  222. expected: -50,
  223. },
  224. {
  225. name: "positive class and negative id",
  226. html: `<div class="article" id="comment">content</div>`,
  227. expected: 0,
  228. },
  229. {
  230. name: "negative class and positive id",
  231. html: `<div class="banner" id="content">content</div>`,
  232. expected: 0,
  233. },
  234. {
  235. name: "multiple positive classes",
  236. html: `<div class="article content">content</div>`,
  237. expected: 25,
  238. },
  239. {
  240. name: "multiple negative classes",
  241. html: `<div class="comment sidebar">content</div>`,
  242. expected: -25,
  243. },
  244. {
  245. name: "mixed positive and negative classes",
  246. html: `<div class="article comment">content</div>`,
  247. expected: -25, // negative takes precedence since it's checked first
  248. },
  249. {
  250. name: "case insensitive class",
  251. html: `<div class="ARTICLE">content</div>`,
  252. expected: 25,
  253. },
  254. {
  255. name: "case insensitive id",
  256. html: `<div id="MAIN">content</div>`,
  257. expected: 25,
  258. },
  259. {
  260. name: "non-matching class and id",
  261. html: `<div class="random" id="unknown">content</div>`,
  262. expected: 0,
  263. },
  264. {
  265. name: "empty class and id",
  266. html: `<div class="" id="">content</div>`,
  267. expected: 0,
  268. },
  269. {
  270. name: "class with special characters",
  271. html: `<div class="com-section">content</div>`,
  272. expected: -25, // matches com- in negative regex
  273. },
  274. {
  275. name: "id with special characters",
  276. html: `<div id="h-entry-123">content</div>`,
  277. expected: 25, // matches h-entry in positive regex
  278. },
  279. }
  280. for _, tc := range testCases {
  281. t.Run(tc.name, func(t *testing.T) {
  282. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  283. if err != nil {
  284. t.Fatalf("Failed to parse HTML: %v", err)
  285. }
  286. selection := doc.Find("div").First()
  287. if selection.Length() == 0 {
  288. t.Fatal("No div element found in HTML")
  289. }
  290. result := getClassWeight(selection)
  291. if result != tc.expected {
  292. t.Errorf("Expected weight %f, got %f", tc.expected, result)
  293. }
  294. })
  295. }
  296. }
  297. func TestGetClassWeightRegexPatterns(t *testing.T) {
  298. // Test specific regex patterns used in getClassWeight
  299. positiveWords := []string{"article", "body", "content", "entry", "hentry", "h-entry", "main", "page", "pagination", "post", "text", "blog", "story"}
  300. negativeWords := []string{"hid", "banner", "combx", "comment", "com-", "contact", "foot", "masthead", "media", "meta", "modal", "outbrain", "promo", "related", "scroll", "share", "shoutbox", "sidebar", "skyscraper", "sponsor", "shopping", "tags", "tool", "widget", "byline", "author", "dateline", "writtenby"}
  301. for _, word := range positiveWords {
  302. t.Run("positive_"+word, func(t *testing.T) {
  303. html := `<div class="` + word + `">content</div>`
  304. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  305. if err != nil {
  306. t.Fatalf("Failed to parse HTML: %v", err)
  307. }
  308. selection := doc.Find("div").First()
  309. result := getClassWeight(selection)
  310. if result != 25 {
  311. t.Errorf("Expected positive weight 25 for word '%s', got %f", word, result)
  312. }
  313. })
  314. }
  315. for _, word := range negativeWords {
  316. t.Run("negative_"+word, func(t *testing.T) {
  317. html := `<div class="` + word + `">content</div>`
  318. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  319. if err != nil {
  320. t.Fatalf("Failed to parse HTML: %v", err)
  321. }
  322. selection := doc.Find("div").First()
  323. result := getClassWeight(selection)
  324. if result != -25 {
  325. t.Errorf("Expected negative weight -25 for word '%s', got %f", word, result)
  326. }
  327. })
  328. }
  329. }
  330. func TestRemoveUnlikelyCandidates(t *testing.T) {
  331. testCases := []struct {
  332. name string
  333. html string
  334. expected string
  335. }{
  336. {
  337. name: "removes elements with popupbody class",
  338. html: `<html><body><div class="popupbody">popup content</div><div class="content">good content</div></body></html>`,
  339. expected: `<html><head></head><body><div class="content">good content</div></body></html>`,
  340. },
  341. {
  342. name: "removes elements with -ad in class",
  343. html: `<html><body><div class="super-ad">ad content</div><div class="content">good content</div></body></html>`,
  344. expected: `<html><head></head><body><div class="content">good content</div></body></html>`,
  345. },
  346. {
  347. name: "removes elements with g-plus in class",
  348. html: `<html><body><div class="g-plus-share">social content</div><div class="content">good content</div></body></html>`,
  349. expected: `<html><head></head><body><div class="content">good content</div></body></html>`,
  350. },
  351. {
  352. name: "removes elements with unlikely candidates in class",
  353. html: `<html><body><div class="banner">banner</div><div class="sidebar">sidebar</div><div class="content">good content</div></body></html>`,
  354. expected: `<html><head></head><body><div class="content">good content</div></body></html>`,
  355. },
  356. {
  357. name: "preserves elements with unlikely candidates but also good candidates in class",
  358. html: `<html><body><div class="banner article">mixed content</div><div class="content">good content</div></body></html>`,
  359. expected: `<html><head></head><body><div class="banner article">mixed content</div><div class="content">good content</div></body></html>`,
  360. },
  361. {
  362. name: "removes elements with unlikely candidates in id",
  363. html: `<html><body><div id="banner">banner</div><div id="main-content">good content</div></body></html>`,
  364. expected: `<html><head></head><body><div id="main-content">good content</div></body></html>`,
  365. },
  366. {
  367. name: "preserves elements with unlikely candidates but also good candidates in id",
  368. html: `<html><body><div id="comment-article">mixed content</div><div id="main">good content</div></body></html>`,
  369. expected: `<html><head></head><body><div id="comment-article">mixed content</div><div id="main">good content</div></body></html>`,
  370. },
  371. {
  372. name: "preserves html and body tags",
  373. html: `<html class="banner"><body class="sidebar"><div class="banner">content</div></body></html>`,
  374. expected: `<html class="banner"><head></head><body class="sidebar"></body></html>`,
  375. },
  376. {
  377. name: "preserves elements within code blocks",
  378. html: `<html><body><pre><code><span class="banner">code content</span></code></pre><div class="banner">remove this</div></body></html>`,
  379. expected: `<html><head></head><body><pre><code><span class="banner">code content</span></code></pre></body></html>`,
  380. },
  381. {
  382. name: "preserves elements within pre tags",
  383. html: `<html><body><pre><div class="sidebar">preformatted content</div></pre><div class="sidebar">remove this</div></body></html>`,
  384. expected: `<html><head></head><body><pre><div class="sidebar">preformatted content</div></pre></body></html>`,
  385. },
  386. {
  387. name: "case insensitive matching",
  388. html: `<html><body><div class="BANNER">uppercase banner</div><div class="Banner">mixed case banner</div><div class="content">good content</div></body></html>`,
  389. expected: `<html><head></head><body><div class="content">good content</div></body></html>`,
  390. },
  391. {
  392. name: "multiple unlikely patterns in single class",
  393. html: `<html><body><div class="banner sidebar footer">multiple bad</div><div class="content">good content</div></body></html>`,
  394. expected: `<html><head></head><body><div class="content">good content</div></body></html>`,
  395. },
  396. {
  397. name: "elements without class or id are preserved",
  398. html: `<html><body><div>no attributes</div><p>paragraph</p></body></html>`,
  399. expected: `<html><head></head><body><div>no attributes</div><p>paragraph</p></body></html>`,
  400. },
  401. {
  402. name: "removes nested unlikely elements",
  403. html: `<html><body><div class="main"><div class="banner">nested banner</div><p>good content</p></div></body></html>`,
  404. expected: `<html><head></head><body><div class="main"><p>good content</p></div></body></html>`,
  405. },
  406. {
  407. name: "comprehensive unlikely candidates test",
  408. html: `<html><body><div class="breadcrumbs">breadcrumbs</div><div class="combx">combx</div><div class="comment">comment</div><div class="community">community</div><div class="cover-wrap">cover-wrap</div><div class="disqus">disqus</div><div class="extra">extra</div><div class="foot">foot</div><div class="header">header</div><div class="legends">legends</div><div class="menu">menu</div><div class="modal">modal</div><div class="related">related</div><div class="remark">remark</div><div class="replies">replies</div><div class="rss">rss</div><div class="shoutbox">shoutbox</div><div class="skyscraper">skyscraper</div><div class="social">social</div><div class="sponsor">sponsor</div><div class="supplemental">supplemental</div><div class="ad-break">ad-break</div><div class="agegate">agegate</div><div class="pagination">pagination</div><div class="pager">pager</div><div class="popup">popup</div><div class="yom-remote">yom-remote</div><div class="article">good content</div></body></html>`,
  409. expected: `<html><head></head><body><div class="article">good content</div></body></html>`,
  410. },
  411. {
  412. name: "preserves good candidates that contain unlikely words",
  413. html: `<html><body><div class="banner article">should be preserved</div><div class="comment main">should be preserved</div><div class="sidebar body">should be preserved</div><div class="footer column">should be preserved</div><div class="header and">should be preserved</div><div class="menu shadow">should be preserved</div><div class="pure-banner">should be removed</div></body></html>`,
  414. expected: `<html><head></head><body><div class="banner article">should be preserved</div><div class="comment main">should be preserved</div><div class="sidebar body">should be preserved</div><div class="footer column">should be preserved</div><div class="header and">should be preserved</div><div class="menu shadow">should be preserved</div></body></html>`,
  415. },
  416. }
  417. for _, tc := range testCases {
  418. t.Run(tc.name, func(t *testing.T) {
  419. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  420. if err != nil {
  421. t.Fatalf("Failed to parse HTML: %v", err)
  422. }
  423. removeUnlikelyCandidates(doc)
  424. result, err := doc.Html()
  425. if err != nil {
  426. t.Fatalf("Failed to get HTML: %v", err)
  427. }
  428. // Normalize whitespace for comparison
  429. result = strings.TrimSpace(result)
  430. expected := strings.TrimSpace(tc.expected)
  431. if result != expected {
  432. t.Errorf("\nExpected:\n%s\n\nGot:\n%s", expected, result)
  433. }
  434. })
  435. }
  436. }
  437. func TestRemoveUnlikelyCandidatesShouldRemoveFunction(t *testing.T) {
  438. // Test the internal shouldRemove function behavior through the public interface
  439. testCases := []struct {
  440. name string
  441. attr string
  442. attrType string // "class" or "id"
  443. expected bool // true if should be removed
  444. }{
  445. // Special hardcoded cases
  446. {"popupbody in class", "popupbody", "class", true},
  447. {"contains popupbody in class", "main-popupbody-content", "class", true},
  448. {"ad suffix in class", "super-ad", "class", true},
  449. {"ad in middle of class", "pre-ad-post", "class", true},
  450. {"g-plus in class", "g-plus-share", "class", true},
  451. {"contains g-plus in class", "social-g-plus-button", "class", true},
  452. // Unlikely candidates regexp
  453. {"banner class", "banner", "class", true},
  454. {"breadcrumbs class", "breadcrumbs", "class", true},
  455. {"comment class", "comment", "class", true},
  456. {"sidebar class", "sidebar", "class", true},
  457. {"footer class", "footer", "class", true},
  458. // Unlikely candidates with good candidates (should not be removed)
  459. {"banner with article", "banner article", "class", false},
  460. {"comment with main", "comment main", "class", false},
  461. {"sidebar with body", "sidebar body", "class", false},
  462. {"footer with column", "footer column", "class", false},
  463. {"menu with shadow", "menu shadow", "class", false},
  464. // Case insensitive
  465. {"uppercase banner", "BANNER", "class", true},
  466. {"mixed case comment", "Comment", "class", true},
  467. {"uppercase with good", "BANNER ARTICLE", "class", false},
  468. // ID attributes
  469. {"banner id", "banner", "id", true},
  470. {"comment id", "comment", "id", true},
  471. {"banner with article id", "banner article", "id", false},
  472. // Good candidates only
  473. {"article class", "article", "class", false},
  474. {"main class", "main", "class", false},
  475. {"content class", "content", "class", false},
  476. {"body class", "body", "class", false},
  477. // No matches
  478. {"random class", "random-class", "class", false},
  479. {"normal content", "normal-content", "class", false},
  480. {"empty string", "", "class", false},
  481. }
  482. for _, tc := range testCases {
  483. t.Run(tc.name, func(t *testing.T) {
  484. var html string
  485. if tc.attrType == "class" {
  486. html = `<html><body><div class="` + tc.attr + `">content</div></body></html>`
  487. } else {
  488. html = `<html><body><div id="` + tc.attr + `">content</div></body></html>`
  489. }
  490. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  491. if err != nil {
  492. t.Fatalf("Failed to parse HTML: %v", err)
  493. }
  494. // Count elements before removal
  495. beforeCount := doc.Find("div").Length()
  496. removeUnlikelyCandidates(doc)
  497. // Count elements after removal
  498. afterCount := doc.Find("div").Length()
  499. wasRemoved := beforeCount > afterCount
  500. if wasRemoved != tc.expected {
  501. t.Errorf("Expected element to be removed: %v, but was removed: %v", tc.expected, wasRemoved)
  502. }
  503. })
  504. }
  505. }
  506. func TestRemoveUnlikelyCandidatesPreservation(t *testing.T) {
  507. testCases := []struct {
  508. name string
  509. html string
  510. description string
  511. }{
  512. {
  513. name: "preserves html tag",
  514. html: `<html class="banner sidebar footer"><body><div>content</div></body></html>`,
  515. description: "HTML tag should never be removed regardless of class",
  516. },
  517. {
  518. name: "preserves body tag",
  519. html: `<html><body class="banner sidebar footer"><div>content</div></body></html>`,
  520. description: "Body tag should never be removed regardless of class",
  521. },
  522. {
  523. name: "preserves elements in pre tags",
  524. html: `<html><body><pre><span class="banner">code</span></pre></body></html>`,
  525. description: "Elements within pre tags should be preserved",
  526. },
  527. {
  528. name: "preserves elements in code tags",
  529. html: `<html><body><code><span class="sidebar">code</span></code></body></html>`,
  530. description: "Elements within code tags should be preserved",
  531. },
  532. {
  533. name: "preserves nested elements in code blocks",
  534. html: `<html><body><pre><code><div class="comment"><span class="banner">nested</span></div></code></pre></body></html>`,
  535. description: "Deeply nested elements in code blocks should be preserved",
  536. },
  537. {
  538. name: "preserves elements in mixed code scenarios",
  539. html: `<html><body><div class="main"><pre><span class="sidebar">code</span></pre><code><div class="banner">more code</div></code></div></body></html>`,
  540. description: "Multiple code block scenarios should work correctly",
  541. },
  542. }
  543. for _, tc := range testCases {
  544. t.Run(tc.name, func(t *testing.T) {
  545. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  546. if err != nil {
  547. t.Fatalf("Failed to parse HTML: %v", err)
  548. }
  549. // Count specific elements before removal
  550. beforeHtml := doc.Find("html").Length()
  551. beforeBody := doc.Find("body").Length()
  552. beforePre := doc.Find("pre").Length()
  553. beforeCode := doc.Find("code").Length()
  554. removeUnlikelyCandidates(doc)
  555. // Count specific elements after removal
  556. afterHtml := doc.Find("html").Length()
  557. afterBody := doc.Find("body").Length()
  558. afterPre := doc.Find("pre").Length()
  559. afterCode := doc.Find("code").Length()
  560. // These elements should always be preserved
  561. if beforeHtml != afterHtml {
  562. t.Errorf("HTML elements were removed: before=%d, after=%d", beforeHtml, afterHtml)
  563. }
  564. if beforeBody != afterBody {
  565. t.Errorf("Body elements were removed: before=%d, after=%d", beforeBody, afterBody)
  566. }
  567. if beforePre != afterPre {
  568. t.Errorf("Pre elements were removed: before=%d, after=%d", beforePre, afterPre)
  569. }
  570. if beforeCode != afterCode {
  571. t.Errorf("Code elements were removed: before=%d, after=%d", beforeCode, afterCode)
  572. }
  573. // Verify that elements within code blocks are preserved
  574. if tc.name == "preserves elements in pre tags" || tc.name == "preserves elements in code tags" || tc.name == "preserves nested elements in code blocks" {
  575. spanInCode := doc.Find("pre span, code span, pre div, code div").Length()
  576. if spanInCode == 0 {
  577. t.Error("Elements within code blocks were incorrectly removed")
  578. }
  579. }
  580. })
  581. }
  582. }
  583. func TestGetArticle(t *testing.T) {
  584. testCases := []struct {
  585. name string
  586. html string
  587. expected string
  588. }{
  589. {
  590. name: "single top candidate",
  591. html: `<html><body><div id="main"><p>This is the main content.</p></div></body></html>`,
  592. expected: `<div><div><p>This is the main content.</p></div></div>`,
  593. },
  594. {
  595. name: "top candidate with high-scoring sibling",
  596. html: `<html><body><div id="content"><p>Main content here.</p></div><div id="related"><p>Related content with good score.</p></div></body></html>`,
  597. expected: `<div><div><div id="content"><p>Main content here.</p></div><div id="related"><p>Related content with good score.</p></div></div></div>`,
  598. },
  599. {
  600. name: "top candidate with low-scoring sibling",
  601. html: `<html><body><div id="content"><p>Main content here.</p></div><div id="sidebar"><p>Sidebar content.</p></div></body></html>`,
  602. expected: `<div><div><div id="content"><p>Main content here.</p></div><div id="sidebar"><p>Sidebar content.</p></div></div></div>`,
  603. },
  604. {
  605. name: "paragraph with high link density",
  606. html: `<html><body><div id="main"><p>This is content.</p></div><p>Some text with <a href="#">many</a> <a href="#">different</a> <a href="#">links</a> here.</p></body></html>`,
  607. expected: `<div><div><div id="main"><p>This is content.</p></div><p>Some text with <a href="#">many</a> <a href="#">different</a> <a href="#">links</a> here.</p></div></div>`,
  608. },
  609. {
  610. name: "paragraph with low link density and long content",
  611. html: `<html><body><div id="main"><p>This is content.</p></div><p>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.</p></body></html>`,
  612. expected: `<div><div><div id="main"><p>This is content.</p></div><p>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.</p></div></div>`,
  613. },
  614. {
  615. name: "short paragraph with no links and sentence",
  616. html: `<html><body><div id="main"><p>This is content.</p></div><p>Short sentence.</p></body></html>`,
  617. expected: `<div><div><div id="main"><p>This is content.</p></div><p>Short sentence.</p></div></div>`,
  618. },
  619. {
  620. name: "short paragraph with no links but no sentence",
  621. html: `<html><body><div id="main"><p>This is content.</p></div><p>Short fragment</p></body></html>`,
  622. expected: `<div><div><div id="main"><p>This is content.</p></div><p>Short fragment</p></div></div>`,
  623. },
  624. {
  625. name: "mixed content with various elements",
  626. html: `<html><body><div id="main"><p>Main content.</p></div><p>Good long content with enough text to be included based on length criteria and low link density.</p><p>Bad content with <a href="#">too</a> <a href="#">many</a> <a href="#">links</a> relative to text.</p><p>Good short.</p><div>Non-paragraph content.</div></body></html>`,
  627. expected: `<div><div><div id="main"><p>Main content.</p></div><p>Good long content with enough text to be included based on length criteria and low link density.</p><p>Bad content with <a href="#">too</a> <a href="#">many</a> <a href="#">links</a> relative to text.</p><p>Good short.</p><div>Non-paragraph content.</div></div></div>`,
  628. },
  629. {
  630. name: "nested content structure",
  631. html: `<html><body><div id="article"><div><p>Nested paragraph content.</p><span>Nested span.</span></div></div><p>Sibling paragraph.</p></body></html>`,
  632. expected: `<div><p>Sibling paragraph.</p><div><div><p>Nested paragraph content.</p><span>Nested span.</span></div></div></div>`,
  633. },
  634. {
  635. name: "empty top candidate",
  636. html: `<html><body><div id="empty"></div><p>Some content here.</p></body></html>`,
  637. expected: `<div><div><div id="empty"></div><p>Some content here.</p></div></div>`,
  638. },
  639. }
  640. for _, tc := range testCases {
  641. t.Run(tc.name, func(t *testing.T) {
  642. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  643. if err != nil {
  644. t.Fatalf("Failed to parse HTML: %v", err)
  645. }
  646. // Get candidates like the real extraction process
  647. candidates := getCandidates(doc)
  648. topCandidate := getTopCandidate(doc, candidates)
  649. result := getArticle(topCandidate, candidates)
  650. if result != tc.expected {
  651. t.Errorf("\nExpected:\n%s\n\nGot:\n%s", tc.expected, result)
  652. }
  653. })
  654. }
  655. }
  656. func TestGetArticleWithSpecificScoring(t *testing.T) {
  657. // Test specific scoring scenarios
  658. html := `<html><body>
  659. <div id="main-content" class="article">
  660. <p>This is the main article content with substantial text.</p>
  661. </div>
  662. <div id="high-score" class="content">
  663. <p>This sibling has high score due to good class name.</p>
  664. </div>
  665. <div id="low-score" class="sidebar">
  666. <p>This sibling has low score due to bad class name.</p>
  667. </div>
  668. <p>This is a standalone paragraph with enough content to be included based on length and should be appended.</p>
  669. <p>Short.</p>
  670. <p>This has <a href="#">too many</a> <a href="#">links</a> for its <a href="#">size</a>.</p>
  671. </body></html>`
  672. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  673. if err != nil {
  674. t.Fatalf("Failed to parse HTML: %v", err)
  675. }
  676. candidates := getCandidates(doc)
  677. topCandidate := getTopCandidate(doc, candidates)
  678. result := getArticle(topCandidate, candidates)
  679. // Verify the structure contains expected elements
  680. resultDoc, err := goquery.NewDocumentFromReader(strings.NewReader(result))
  681. if err != nil {
  682. t.Fatalf("Failed to parse result HTML: %v", err)
  683. }
  684. // Should contain the main content
  685. if resultDoc.Find("p:contains('main article content')").Length() == 0 {
  686. t.Error("Main content not found in result")
  687. }
  688. // Should contain high-scoring sibling
  689. if resultDoc.Find("p:contains('high score')").Length() == 0 {
  690. t.Error("High-scoring sibling not found in result")
  691. }
  692. // Should contain long standalone paragraph
  693. if resultDoc.Find("p:contains('standalone paragraph')").Length() == 0 {
  694. t.Error("Long standalone paragraph not found in result")
  695. }
  696. // Should contain short paragraph with sentence
  697. if resultDoc.Find("p:contains('Short.')").Length() == 0 {
  698. t.Error("Short paragraph with sentence not found in result")
  699. }
  700. // Should NOT contain low-scoring sibling
  701. if resultDoc.Find("p:contains('low score')").Length() > 0 {
  702. t.Error("Low-scoring sibling incorrectly included in result")
  703. }
  704. // Should NOT contain paragraph with too many links
  705. if resultDoc.Find("p:contains('too many')").Length() > 0 {
  706. t.Error("Paragraph with too many links incorrectly included in result")
  707. }
  708. }
  709. func TestGetArticleSiblingScoreThreshold(t *testing.T) {
  710. testCases := []struct {
  711. name string
  712. topScore float32
  713. expectedThreshold float32
  714. }{
  715. {
  716. name: "high score candidate",
  717. topScore: 100,
  718. expectedThreshold: 20, // 100 * 0.2 = 20
  719. },
  720. {
  721. name: "medium score candidate",
  722. topScore: 50,
  723. expectedThreshold: 10, // max(10, 50 * 0.2) = max(10, 10) = 10
  724. },
  725. {
  726. name: "low score candidate",
  727. topScore: 30,
  728. expectedThreshold: 10, // max(10, 30 * 0.2) = max(10, 6) = 10
  729. },
  730. {
  731. name: "very low score candidate",
  732. topScore: 5,
  733. expectedThreshold: 10, // max(10, 5 * 0.2) = max(10, 1) = 10
  734. },
  735. }
  736. for _, tc := range testCases {
  737. t.Run(tc.name, func(t *testing.T) {
  738. // Create a simple HTML structure
  739. html := `<html><body>
  740. <div id="main"><p>Main content</p></div>
  741. <div id="sibling"><p>Sibling content</p></div>
  742. </body></html>`
  743. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  744. if err != nil {
  745. t.Fatalf("Failed to parse HTML: %v", err)
  746. }
  747. // Create artificial candidates with specific scores
  748. mainDiv := doc.Find("#main").Get(0)
  749. siblingDiv := doc.Find("#sibling").Get(0)
  750. topCandidate := &candidate{
  751. selection: doc.Find("#main"),
  752. score: tc.topScore,
  753. }
  754. candidates := candidateList{
  755. mainDiv: topCandidate,
  756. siblingDiv: &candidate{
  757. selection: doc.Find("#sibling"),
  758. score: tc.expectedThreshold, // Set exactly at threshold
  759. },
  760. }
  761. result := getArticle(topCandidate, candidates)
  762. // Parse result to check if sibling was included
  763. resultDoc, err := goquery.NewDocumentFromReader(strings.NewReader(result))
  764. if err != nil {
  765. t.Fatalf("Failed to parse result HTML: %v", err)
  766. }
  767. // Sibling should be included since its score equals the threshold
  768. if resultDoc.Find("p:contains('Sibling content')").Length() == 0 {
  769. t.Errorf("Sibling with score %f should be included with threshold %f", tc.expectedThreshold, tc.expectedThreshold)
  770. }
  771. // Test with score just below threshold
  772. candidates[siblingDiv].score = tc.expectedThreshold - 0.1
  773. result2 := getArticle(topCandidate, candidates)
  774. resultDoc2, err := goquery.NewDocumentFromReader(strings.NewReader(result2))
  775. if err != nil {
  776. t.Fatalf("Failed to parse result HTML: %v", err)
  777. }
  778. // Sibling should NOT be included since its score is below threshold
  779. if resultDoc2.Find("p:contains('Sibling content')").Length() > 0 {
  780. t.Errorf("Sibling with score %f should not be included with threshold %f", tc.expectedThreshold-0.1, tc.expectedThreshold)
  781. }
  782. })
  783. }
  784. }
  785. func TestGetArticleParagraphSpecificLogic(t *testing.T) {
  786. // This test focuses specifically on the paragraph-specific logic in getArticle
  787. // where paragraphs are tested against link density and sentence criteria
  788. // even if they're not in the candidates list
  789. testCases := []struct {
  790. name string
  791. html string
  792. checkParagraph string // text to check for inclusion/exclusion
  793. shouldInclude bool
  794. reason string
  795. }{
  796. {
  797. name: "long paragraph with high link density should be excluded",
  798. html: `<html><body><div id="main"><p>Main content</p></div><p>This is a paragraph with lots of <a href="#">links</a> <a href="#">that</a> <a href="#">should</a> <a href="#">make</a> <a href="#">it</a> <a href="#">excluded</a> based on density.</p></body></html>`,
  799. checkParagraph: "This is a paragraph with lots of",
  800. shouldInclude: false,
  801. reason: "Long paragraph with >= 25% link density should be excluded",
  802. },
  803. {
  804. name: "long paragraph with low link density should be included",
  805. html: `<html><body><div id="main"><p>Main content</p></div><p>This is a very long paragraph with substantial content that has more than eighty characters and contains only <a href="#">one link</a> so the link density is very low.</p></body></html>`,
  806. checkParagraph: "This is a very long paragraph",
  807. shouldInclude: true,
  808. reason: "Long paragraph with < 25% link density should be included",
  809. },
  810. {
  811. name: "short paragraph with no links and sentence should be included",
  812. html: `<html><body><div id="main"><p>Main content</p></div><p>Short sentence.</p></body></html>`,
  813. checkParagraph: "Short sentence.",
  814. shouldInclude: true,
  815. reason: "Short paragraph with 0% link density and sentence should be included",
  816. },
  817. {
  818. name: "short paragraph with no links but no sentence should be excluded",
  819. html: `<html><body><div id="main"><p>Main content</p></div><p>fragment</p></body></html>`,
  820. checkParagraph: "fragment",
  821. shouldInclude: false,
  822. reason: "Short paragraph with 0% link density but no sentence should be excluded",
  823. },
  824. {
  825. name: "short paragraph with links should be excluded",
  826. html: `<html><body><div id="main"><p>Main content</p></div><p>Short with <a href="#">link</a>.</p></body></html>`,
  827. checkParagraph: "Short with",
  828. shouldInclude: false,
  829. reason: "Short paragraph with any links should be excluded",
  830. },
  831. }
  832. for _, tc := range testCases {
  833. t.Run(tc.name, func(t *testing.T) {
  834. // Create a custom scenario where the paragraphs are NOT in the candidates list
  835. // so we can test the paragraph-specific logic
  836. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  837. if err != nil {
  838. t.Fatalf("Failed to parse HTML: %v", err)
  839. }
  840. // Create artificial candidates that only include the main div, not the paragraphs
  841. mainDiv := doc.Find("#main").Get(0)
  842. topCandidate := &candidate{
  843. selection: doc.Find("#main"),
  844. score: 50,
  845. }
  846. candidates := candidateList{
  847. mainDiv: topCandidate,
  848. // Deliberately not including the test paragraphs as candidates
  849. }
  850. result := getArticle(topCandidate, candidates)
  851. included := strings.Contains(result, tc.checkParagraph)
  852. if included != tc.shouldInclude {
  853. t.Errorf("%s: Expected included=%v, got included=%v\nReason: %s\nResult: %s",
  854. tc.name, tc.shouldInclude, included, tc.reason, result)
  855. }
  856. })
  857. }
  858. }
  859. func TestGetArticleLinkDensityThresholds(t *testing.T) {
  860. testCases := []struct {
  861. name string
  862. content string
  863. expectIncluded bool
  864. description string
  865. }{
  866. {
  867. name: "long content with no links",
  868. 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.",
  869. expectIncluded: true,
  870. description: "Content >= 80 chars with 0% link density should be included",
  871. },
  872. {
  873. name: "long content with acceptable link density",
  874. content: "This is a very long paragraph with substantial content and <a href='#'>one small link</a> that should be included because the link density is well below 25%.",
  875. expectIncluded: true,
  876. description: "Content >= 80 chars with < 25% link density should be included",
  877. },
  878. {
  879. name: "long content with high link density",
  880. content: "Short text with <a href='#'>many</a> <a href='#'>different</a> <a href='#'>links</a> here and <a href='#'>more</a> <a href='#'>links</a>.",
  881. expectIncluded: true, // This appears to be included because it's processed as a sibling, not just through paragraph logic
  882. description: "Content with high link density - actual behavior includes siblings",
  883. },
  884. {
  885. name: "short content with no links and sentence",
  886. content: "This is a sentence.",
  887. expectIncluded: true,
  888. description: "Content < 80 chars with 0% link density and proper sentence should be included",
  889. },
  890. {
  891. name: "short content with no links but no sentence",
  892. content: "Just a fragment",
  893. expectIncluded: true, // The algorithm actually includes all siblings, paragraph rules are additional
  894. description: "Content < 80 chars with 0% link density but no sentence - still included as sibling",
  895. },
  896. {
  897. name: "short content with links",
  898. content: "Text with <a href='#'>link</a>.",
  899. expectIncluded: true, // Still included as sibling
  900. description: "Content < 80 chars with any links - still included as sibling",
  901. },
  902. {
  903. name: "edge case: exactly 80 characters no links",
  904. content: "This paragraph has exactly eighty characters and should be included ok.",
  905. expectIncluded: true,
  906. description: "Content with exactly 80 chars and no links should be included",
  907. },
  908. {
  909. name: "edge case: 79 characters no links with sentence",
  910. content: "This paragraph has seventy-nine characters and should be included.",
  911. expectIncluded: true,
  912. description: "Content with 79 chars, no links, and sentence should be included",
  913. },
  914. {
  915. name: "sentence with period at end",
  916. content: "Sentence ending with period.",
  917. expectIncluded: true,
  918. description: "Short content ending with period should be included",
  919. },
  920. {
  921. name: "sentence with period in middle",
  922. content: "Sentence with period. And more",
  923. expectIncluded: true,
  924. description: "Short content with period in middle should be included",
  925. },
  926. }
  927. for _, tc := range testCases {
  928. t.Run(tc.name, func(t *testing.T) {
  929. html := fmt.Sprintf(`<html><body>
  930. <div id="main"><p>Main content</p></div>
  931. <p>%s</p>
  932. </body></html>`, tc.content)
  933. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  934. if err != nil {
  935. t.Fatalf("Failed to parse HTML: %v", err)
  936. }
  937. candidates := getCandidates(doc)
  938. topCandidate := getTopCandidate(doc, candidates)
  939. result := getArticle(topCandidate, candidates)
  940. // Check if the test content was included
  941. included := strings.Contains(result, tc.content) || strings.Contains(result, strings.ReplaceAll(tc.content, `'`, `"`))
  942. if included != tc.expectIncluded {
  943. t.Errorf("%s: Expected included=%v, got included=%v\nContent: %s\nResult: %s",
  944. tc.description, tc.expectIncluded, included, tc.content, result)
  945. }
  946. })
  947. }
  948. }
  949. func TestGetArticleTagWrapping(t *testing.T) {
  950. // Test that paragraph elements keep their tag, others become div
  951. html := `<html><body>
  952. <div id="main"><p>Main content</p></div>
  953. <p>Paragraph content that should stay as p tag.</p>
  954. <div>Div content that should become div tag.</div>
  955. <span>Span content that should become div tag.</span>
  956. <section>Section content that should become div tag.</section>
  957. </body></html>`
  958. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  959. if err != nil {
  960. t.Fatalf("Failed to parse HTML: %v", err)
  961. }
  962. candidates := getCandidates(doc)
  963. topCandidate := getTopCandidate(doc, candidates)
  964. result := getArticle(topCandidate, candidates)
  965. // Parse result to verify tag wrapping
  966. resultDoc, err := goquery.NewDocumentFromReader(strings.NewReader(result))
  967. if err != nil {
  968. t.Fatalf("Failed to parse result HTML: %v", err)
  969. }
  970. // Check that paragraph content is wrapped in <p> tags
  971. paragraphElements := resultDoc.Find("p")
  972. foundParagraphContent := false
  973. paragraphElements.Each(func(i int, s *goquery.Selection) {
  974. if strings.Contains(s.Text(), "Paragraph content") {
  975. foundParagraphContent = true
  976. }
  977. })
  978. if !foundParagraphContent {
  979. t.Error("Paragraph content should be wrapped in <p> tags")
  980. }
  981. // Check that non-paragraph content is wrapped in <div> tags
  982. divElements := resultDoc.Find("div")
  983. foundDivContent := false
  984. foundSpanContent := false
  985. foundSectionContent := false
  986. divElements.Each(func(i int, s *goquery.Selection) {
  987. text := s.Text()
  988. if strings.Contains(text, "Div content") {
  989. foundDivContent = true
  990. }
  991. if strings.Contains(text, "Span content") {
  992. foundSpanContent = true
  993. }
  994. if strings.Contains(text, "Section content") {
  995. foundSectionContent = true
  996. }
  997. })
  998. if !foundDivContent {
  999. t.Error("Div content should be wrapped in <div> tags")
  1000. }
  1001. if !foundSpanContent {
  1002. t.Error("Span content should be wrapped in <div> tags")
  1003. }
  1004. if !foundSectionContent {
  1005. t.Error("Section content should be wrapped in <div> tags")
  1006. }
  1007. // Verify overall structure
  1008. if !strings.HasPrefix(result, "<div>") || !strings.HasSuffix(result, "</div>") {
  1009. t.Error("Result should be wrapped in outer <div> tags")
  1010. }
  1011. }
  1012. func TestGetArticleEmptyAndEdgeCases(t *testing.T) {
  1013. testCases := []struct {
  1014. name string
  1015. html string
  1016. expected string
  1017. }{
  1018. {
  1019. name: "empty body",
  1020. html: `<html><body></body></html>`,
  1021. expected: `<div><div></div></div>`, // getTopCandidate returns body, body has no inner HTML
  1022. },
  1023. {
  1024. name: "only whitespace content",
  1025. html: `<html><body><div id="main"> </div></body></html>`,
  1026. expected: `<div><div><div id="main"> </div></div></div>`, // body is top candidate, includes inner div
  1027. },
  1028. {
  1029. name: "self-closing elements",
  1030. html: `<html><body><div id="main"><p>Content</p><br><img src="test.jpg"></div></body></html>`,
  1031. expected: `<div><div><div id="main"><p>Content</p><br/><img src="test.jpg"/></div></div></div>`, // body includes inner div
  1032. },
  1033. {
  1034. name: "nested structure with no text",
  1035. html: `<html><body><div id="main"><div><div></div></div></div></body></html>`,
  1036. expected: `<div><div><div id="main"><div><div></div></div></div></div></div>`, // body includes inner div
  1037. },
  1038. {
  1039. name: "complex nesting with mixed content",
  1040. html: `<html><body><div id="main"><div class="inner"><span>Nested content</span><p>Paragraph in nested structure.</p></div></div></body></html>`,
  1041. expected: `<div><div><div class="inner"><span>Nested content</span><p>Paragraph in nested structure.</p></div></div></div>`, // The #main div gets selected as top candidate, not body
  1042. },
  1043. }
  1044. for _, tc := range testCases {
  1045. t.Run(tc.name, func(t *testing.T) {
  1046. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  1047. if err != nil {
  1048. t.Fatalf("Failed to parse HTML: %v", err)
  1049. }
  1050. candidates := getCandidates(doc)
  1051. topCandidate := getTopCandidate(doc, candidates)
  1052. result := getArticle(topCandidate, candidates)
  1053. if result != tc.expected {
  1054. t.Errorf("\nExpected:\n%s\n\nGot:\n%s", tc.expected, result)
  1055. }
  1056. })
  1057. }
  1058. }
  1059. // Test helper functions used by getArticle
  1060. func TestGetLinkDensity(t *testing.T) {
  1061. testCases := []struct {
  1062. name string
  1063. html string
  1064. expected float32
  1065. }{
  1066. {
  1067. name: "no links",
  1068. html: `<div>This is plain text content with no links at all.</div>`,
  1069. expected: 0.0,
  1070. },
  1071. {
  1072. name: "all links",
  1073. html: `<div><a href="#">Link one</a><a href="#">Link two</a></div>`,
  1074. expected: 1.0,
  1075. },
  1076. {
  1077. name: "half links",
  1078. html: `<div>Plain text <a href="#">Link text</a></div>`,
  1079. expected: 0.45, // "Link text" is 9 chars, "Plain text Link text" is 20 chars
  1080. },
  1081. {
  1082. name: "nested links",
  1083. html: `<div>Text <a href="#">Link <span>nested</span></a> more text</div>`,
  1084. expected: float32(11) / float32(26), // "Link nested" vs "Text Link nested more text"
  1085. },
  1086. {
  1087. name: "empty content",
  1088. html: `<div></div>`,
  1089. expected: 0.0,
  1090. },
  1091. {
  1092. name: "whitespace only",
  1093. html: `<div> </div>`,
  1094. expected: 0.0,
  1095. },
  1096. {
  1097. name: "links with no text",
  1098. html: `<div>Text content <a href="#"></a></div>`,
  1099. expected: 0.0, // Empty link contributes 0 to link length
  1100. },
  1101. {
  1102. name: "multiple links",
  1103. html: `<div>Start <a href="#">first</a> middle <a href="#">second</a> end</div>`,
  1104. expected: float32(11) / float32(29), // "firstsecond" vs "Start first middle second end"
  1105. },
  1106. }
  1107. for _, tc := range testCases {
  1108. t.Run(tc.name, func(t *testing.T) {
  1109. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  1110. if err != nil {
  1111. t.Fatalf("Failed to parse HTML: %v", err)
  1112. }
  1113. selection := doc.Find("div").First()
  1114. result := getLinkDensity(selection)
  1115. // Use a small epsilon for float comparison
  1116. epsilon := float32(0.001)
  1117. if result < tc.expected-epsilon || result > tc.expected+epsilon {
  1118. t.Errorf("Expected link density %f, got %f", tc.expected, result)
  1119. }
  1120. })
  1121. }
  1122. }
  1123. func TestContainsSentence(t *testing.T) {
  1124. testCases := []struct {
  1125. name string
  1126. content string
  1127. expected bool
  1128. }{
  1129. {
  1130. name: "ends with period",
  1131. content: "This is a sentence.",
  1132. expected: true,
  1133. },
  1134. {
  1135. name: "contains period with space",
  1136. content: "First sentence. Second sentence",
  1137. expected: true,
  1138. },
  1139. {
  1140. name: "no sentence markers",
  1141. content: "Just a fragment",
  1142. expected: false,
  1143. },
  1144. {
  1145. name: "period without space",
  1146. content: "Something.else",
  1147. expected: false,
  1148. },
  1149. {
  1150. name: "empty string",
  1151. content: "",
  1152. expected: false,
  1153. },
  1154. {
  1155. name: "only period",
  1156. content: ".",
  1157. expected: true,
  1158. },
  1159. {
  1160. name: "period and space at end",
  1161. content: "Sentence. ",
  1162. expected: true,
  1163. },
  1164. {
  1165. name: "multiple sentences",
  1166. content: "First. Second. Third",
  1167. expected: true,
  1168. },
  1169. {
  1170. name: "period in middle only",
  1171. content: "Text. More text",
  1172. expected: true,
  1173. },
  1174. {
  1175. name: "whitespace around period",
  1176. content: "Text . More",
  1177. expected: true,
  1178. },
  1179. }
  1180. for _, tc := range testCases {
  1181. t.Run(tc.name, func(t *testing.T) {
  1182. result := containsSentence(tc.content)
  1183. if result != tc.expected {
  1184. t.Errorf("Expected %v for content %q, got %v", tc.expected, tc.content, result)
  1185. }
  1186. })
  1187. }
  1188. }
  1189. func BenchmarkGetWeight(b *testing.B) {
  1190. testCases := []string{
  1191. "p-3 color-bg-accent-emphasis color-fg-on-emphasis show-on-focus js-skip-to-content",
  1192. "d-flex flex-column mb-3",
  1193. "AppHeader-search-control AppHeader-search-control-overflow",
  1194. "Button Button--iconOnly Button--invisible Button--medium mr-1 px-2 py-0 d-flex flex-items-center rounded-1 color-fg-muted",
  1195. "sr-only",
  1196. "validation-12753bbc-b4d1-4e10-bec6-92e585d1699d",
  1197. }
  1198. for range b.N {
  1199. for _, v := range testCases {
  1200. getWeight(v)
  1201. }
  1202. }
  1203. }