readability_test.go 75 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688168916901691169216931694169516961697169816991700170117021703170417051706170717081709171017111712171317141715171617171718171917201721172217231724172517261727172817291730173117321733173417351736173717381739174017411742174317441745174617471748174917501751175217531754175517561757175817591760176117621763176417651766176717681769177017711772177317741775177617771778177917801781178217831784178517861787178817891790179117921793179417951796179717981799180018011802180318041805180618071808180918101811181218131814181518161817181818191820182118221823182418251826182718281829183018311832183318341835183618371838183918401841184218431844184518461847184818491850185118521853185418551856185718581859186018611862186318641865186618671868186918701871187218731874187518761877187818791880188118821883188418851886188718881889189018911892189318941895189618971898189919001901190219031904190519061907190819091910191119121913191419151916191719181919192019211922192319241925192619271928192919301931193219331934193519361937193819391940194119421943194419451946194719481949195019511952195319541955195619571958195919601961196219631964196519661967196819691970197119721973197419751976197719781979198019811982198319841985198619871988198919901991199219931994199519961997199819992000200120022003200420052006200720082009201020112012201320142015201620172018201920202021202220232024202520262027202820292030203120322033203420352036203720382039204020412042204320442045204620472048204920502051205220532054205520562057205820592060206120622063206420652066206720682069207020712072207320742075207620772078207920802081208220832084208520862087208820892090209120922093209420952096209720982099210021012102210321042105210621072108210921102111211221132114211521162117211821192120212121222123212421252126212721282129213021312132213321342135213621372138213921402141214221432144214521462147214821492150215121522153215421552156215721582159216021612162216321642165216621672168216921702171217221732174217521762177217821792180218121822183218421852186218721882189219021912192219321942195219621972198219922002201220222032204220522062207220822092210221122122213221422152216221722182219222022212222222322242225222622272228222922302231223222332234223522362237223822392240224122422243224422452246224722482249225022512252225322542255225622572258225922602261226222632264226522662267226822692270227122722273227422752276227722782279228022812282228322842285228622872288228922902291229222932294229522962297229822992300230123022303230423052306
  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. "errors"
  7. "fmt"
  8. "os"
  9. "strings"
  10. "testing"
  11. "github.com/PuerkitoBio/goquery"
  12. "golang.org/x/net/html"
  13. )
  14. func BenchmarkExtractContent(b *testing.B) {
  15. var testCases = map[string][]byte{
  16. "miniflux_github.html": {},
  17. "miniflux_wikipedia.html": {},
  18. }
  19. for filename := range testCases {
  20. data, err := os.ReadFile("testdata/" + filename)
  21. if err != nil {
  22. b.Fatalf(`Unable to read file %q: %v`, filename, err)
  23. }
  24. testCases[filename] = data
  25. }
  26. for range b.N {
  27. for _, v := range testCases {
  28. ExtractContent(bytes.NewReader(v))
  29. }
  30. }
  31. }
  32. func BenchmarkGetWeight(b *testing.B) {
  33. testCases := []string{
  34. "p-3 color-bg-accent-emphasis color-fg-on-emphasis show-on-focus js-skip-to-content",
  35. "d-flex flex-column mb-3",
  36. "AppHeader-search-control AppHeader-search-control-overflow",
  37. "Button Button--iconOnly Button--invisible Button--medium mr-1 px-2 py-0 d-flex flex-items-center rounded-1 color-fg-muted",
  38. "sr-only",
  39. "validation-12753bbc-b4d1-4e10-bec6-92e585d1699d",
  40. }
  41. for range b.N {
  42. for _, v := range testCases {
  43. getWeight(v)
  44. }
  45. }
  46. }
  47. func BenchmarkTransformMisusedDivsIntoParagraphs(b *testing.B) {
  48. html := `<html><body>
  49. <div>Simple text content</div>
  50. <div>More <span>inline</span> content</div>
  51. <div><a href="#">Link content</a></div>
  52. <div><p>Paragraph content</p></div>
  53. <div>Another simple text</div>
  54. </body></html>`
  55. b.ResetTimer()
  56. for i := 0; i < b.N; i++ {
  57. doc, _ := goquery.NewDocumentFromReader(strings.NewReader(html))
  58. transformMisusedDivsIntoParagraphs(doc)
  59. }
  60. }
  61. func TestBaseURL(t *testing.T) {
  62. html := `
  63. <html>
  64. <head>
  65. <base href="https://example.org/ ">
  66. </head>
  67. <body>
  68. <article>
  69. Some content
  70. </article>
  71. </body>
  72. </html>`
  73. baseURL, _, err := ExtractContent(strings.NewReader(html))
  74. if err != nil {
  75. t.Fatal(err)
  76. }
  77. if baseURL != "https://example.org/" {
  78. t.Errorf(`Unexpected base URL, got %q instead of "https://example.org/"`, baseURL)
  79. }
  80. }
  81. func TestMultipleBaseURL(t *testing.T) {
  82. html := `
  83. <html>
  84. <head>
  85. <base href="https://example.org/ ">
  86. <base href="https://example.com/ ">
  87. </head>
  88. <body>
  89. <article>
  90. Some content
  91. </article>
  92. </body>
  93. </html>`
  94. baseURL, _, err := ExtractContent(strings.NewReader(html))
  95. if err != nil {
  96. t.Fatal(err)
  97. }
  98. if baseURL != "https://example.org/" {
  99. t.Errorf(`Unexpected base URL, got %q instead of "https://example.org/"`, baseURL)
  100. }
  101. }
  102. func TestRelativeBaseURL(t *testing.T) {
  103. html := `
  104. <html>
  105. <head>
  106. <base href="/test/ ">
  107. </head>
  108. <body>
  109. <article>
  110. Some content
  111. </article>
  112. </body>
  113. </html>`
  114. baseURL, _, err := ExtractContent(strings.NewReader(html))
  115. if err != nil {
  116. t.Fatal(err)
  117. }
  118. if baseURL != "" {
  119. t.Errorf(`Unexpected base URL, got %q`, baseURL)
  120. }
  121. }
  122. func TestWithoutBaseURL(t *testing.T) {
  123. html := `
  124. <html>
  125. <head>
  126. <title>Test</title>
  127. </head>
  128. <body>
  129. <article>
  130. Some content
  131. </article>
  132. </body>
  133. </html>`
  134. baseURL, _, err := ExtractContent(strings.NewReader(html))
  135. if err != nil {
  136. t.Fatal(err)
  137. }
  138. if baseURL != "" {
  139. t.Errorf(`Unexpected base URL, got %q instead of ""`, baseURL)
  140. }
  141. }
  142. func TestRemoveStyleScript(t *testing.T) {
  143. html := `
  144. <html>
  145. <head>
  146. <title>Test</title>
  147. <script src="tololo.js"></script>
  148. </head>
  149. <body>
  150. <script src="tololo.js"></script>
  151. <style>
  152. h1 {color:red;}
  153. p {color:blue;}
  154. </style>
  155. <article>Some content</article>
  156. </body>
  157. </html>`
  158. want := `<div><div><article>Somecontent</article></div></div>`
  159. _, content, err := ExtractContent(strings.NewReader(html))
  160. if err != nil {
  161. t.Fatal(err)
  162. }
  163. content = strings.ReplaceAll(content, "\n", "")
  164. content = strings.ReplaceAll(content, " ", "")
  165. content = strings.ReplaceAll(content, "\t", "")
  166. if content != want {
  167. t.Errorf(`Invalid content, got %s instead of %s`, content, want)
  168. }
  169. }
  170. func TestRemoveBlacklist(t *testing.T) {
  171. html := `
  172. <html>
  173. <head>
  174. <title>Test</title>
  175. </head>
  176. <body>
  177. <article class="super-ad">Some content</article>
  178. <article class="g-plus-crap">Some other thing</article>
  179. <article class="stuff popupbody">And more</article>
  180. <article class="legit">Valid!</article>
  181. </body>
  182. </html>`
  183. want := `<div><div><articleclass="legit">Valid!</article></div></div>`
  184. _, content, err := ExtractContent(strings.NewReader(html))
  185. if err != nil {
  186. t.Fatal(err)
  187. }
  188. content = strings.ReplaceAll(content, "\n", "")
  189. content = strings.ReplaceAll(content, " ", "")
  190. content = strings.ReplaceAll(content, "\t", "")
  191. if content != want {
  192. t.Errorf(`Invalid content, got %s instead of %s`, content, want)
  193. }
  194. }
  195. func TestNestedSpanInCodeBlock(t *testing.T) {
  196. html := `
  197. <html>
  198. <head>
  199. <title>Test</title>
  200. </head>
  201. <body>
  202. <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>
  203. </body>
  204. </html>`
  205. 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>`
  206. _, result, err := ExtractContent(strings.NewReader(html))
  207. if err != nil {
  208. t.Fatal(err)
  209. }
  210. if result != want {
  211. t.Errorf(`Invalid content, got %s instead of %s`, result, want)
  212. }
  213. }
  214. func TestGetClassWeight(t *testing.T) {
  215. testCases := []struct {
  216. name string
  217. html string
  218. expected float32
  219. }{
  220. {
  221. name: "no class or id",
  222. html: `<div>content</div>`,
  223. expected: 0,
  224. },
  225. {
  226. name: "positive class only",
  227. html: `<div class="article">content</div>`,
  228. expected: 25,
  229. },
  230. {
  231. name: "negative class only",
  232. html: `<div class="comment">content</div>`,
  233. expected: -25,
  234. },
  235. {
  236. name: "positive id only",
  237. html: `<div id="main">content</div>`,
  238. expected: 25,
  239. },
  240. {
  241. name: "negative id only",
  242. html: `<div id="sidebar">content</div>`,
  243. expected: -25,
  244. },
  245. {
  246. name: "positive class and positive id",
  247. html: `<div class="content" id="main">content</div>`,
  248. expected: 50,
  249. },
  250. {
  251. name: "negative class and negative id",
  252. html: `<div class="comment" id="sidebar">content</div>`,
  253. expected: -50,
  254. },
  255. {
  256. name: "positive class and negative id",
  257. html: `<div class="article" id="comment">content</div>`,
  258. expected: 0,
  259. },
  260. {
  261. name: "negative class and positive id",
  262. html: `<div class="banner" id="content">content</div>`,
  263. expected: 0,
  264. },
  265. {
  266. name: "multiple positive classes",
  267. html: `<div class="article content">content</div>`,
  268. expected: 25,
  269. },
  270. {
  271. name: "multiple negative classes",
  272. html: `<div class="comment sidebar">content</div>`,
  273. expected: -25,
  274. },
  275. {
  276. name: "mixed positive and negative classes",
  277. html: `<div class="article comment">content</div>`,
  278. expected: -25, // negative takes precedence since it's checked first
  279. },
  280. {
  281. name: "case insensitive class",
  282. html: `<div class="ARTICLE">content</div>`,
  283. expected: 25,
  284. },
  285. {
  286. name: "case insensitive id",
  287. html: `<div id="MAIN">content</div>`,
  288. expected: 25,
  289. },
  290. {
  291. name: "non-matching class and id",
  292. html: `<div class="random" id="unknown">content</div>`,
  293. expected: 0,
  294. },
  295. {
  296. name: "empty class and id",
  297. html: `<div class="" id="">content</div>`,
  298. expected: 0,
  299. },
  300. {
  301. name: "class with special characters",
  302. html: `<div class="com-section">content</div>`,
  303. expected: -25, // matches com- in negative regex
  304. },
  305. {
  306. name: "id with special characters",
  307. html: `<div id="h-entry-123">content</div>`,
  308. expected: 25, // matches h-entry in positive regex
  309. },
  310. }
  311. for _, tc := range testCases {
  312. t.Run(tc.name, func(t *testing.T) {
  313. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  314. if err != nil {
  315. t.Fatalf("Failed to parse HTML: %v", err)
  316. }
  317. selection := doc.Find("div").First()
  318. if selection.Length() == 0 {
  319. t.Fatal("No div element found in HTML")
  320. }
  321. })
  322. }
  323. }
  324. func TestRemoveUnlikelyCandidates(t *testing.T) {
  325. testCases := []struct {
  326. name string
  327. html string
  328. expected string
  329. }{
  330. {
  331. name: "removes elements with popupbody class",
  332. html: `<html><body><div class="popupbody">popup content</div><div class="content">good content</div></body></html>`,
  333. expected: `<html><head></head><body><div class="content">good content</div></body></html>`,
  334. },
  335. {
  336. name: "removes elements with -ad in class",
  337. html: `<html><body><div class="super-ad">ad content</div><div class="content">good content</div></body></html>`,
  338. expected: `<html><head></head><body><div class="content">good content</div></body></html>`,
  339. },
  340. {
  341. name: "removes elements with g-plus in class",
  342. html: `<html><body><div class="g-plus-share">social content</div><div class="content">good content</div></body></html>`,
  343. expected: `<html><head></head><body><div class="content">good content</div></body></html>`,
  344. },
  345. {
  346. name: "removes elements with unlikely candidates in class",
  347. html: `<html><body><div class="banner">banner</div><div class="sidebar">sidebar</div><div class="content">good content</div></body></html>`,
  348. expected: `<html><head></head><body><div class="content">good content</div></body></html>`,
  349. },
  350. {
  351. name: "preserves elements with unlikely candidates but also good candidates in class",
  352. html: `<html><body><div class="banner article">mixed content</div><div class="content">good content</div></body></html>`,
  353. expected: `<html><head></head><body><div class="banner article">mixed content</div><div class="content">good content</div></body></html>`,
  354. },
  355. {
  356. name: "removes elements with unlikely candidates in id",
  357. html: `<html><body><div id="banner">banner</div><div id="main-content">good content</div></body></html>`,
  358. expected: `<html><head></head><body><div id="main-content">good content</div></body></html>`,
  359. },
  360. {
  361. name: "preserves elements with unlikely candidates but also good candidates in id",
  362. html: `<html><body><div id="comment-article">mixed content</div><div id="main">good content</div></body></html>`,
  363. expected: `<html><head></head><body><div id="comment-article">mixed content</div><div id="main">good content</div></body></html>`,
  364. },
  365. {
  366. name: "preserves html and body tags",
  367. html: `<html class="banner"><body class="sidebar"><div class="banner">content</div></body></html>`,
  368. expected: `<html class="banner"><head></head><body class="sidebar"></body></html>`,
  369. },
  370. {
  371. name: "preserves elements within code blocks",
  372. html: `<html><body><pre><code><span class="banner">code content</span></code></pre><div class="banner">remove this</div></body></html>`,
  373. expected: `<html><head></head><body><pre><code><span class="banner">code content</span></code></pre></body></html>`,
  374. },
  375. {
  376. name: "preserves elements within pre tags",
  377. html: `<html><body><pre><div class="sidebar">preformatted content</div></pre><div class="sidebar">remove this</div></body></html>`,
  378. expected: `<html><head></head><body><pre><div class="sidebar">preformatted content</div></pre></body></html>`,
  379. },
  380. {
  381. name: "case insensitive matching",
  382. html: `<html><body><div class="BANNER">uppercase banner</div><div class="Banner">mixed case banner</div><div class="content">good content</div></body></html>`,
  383. expected: `<html><head></head><body><div class="content">good content</div></body></html>`,
  384. },
  385. {
  386. name: "multiple unlikely patterns in single class",
  387. html: `<html><body><div class="banner sidebar footer">multiple bad</div><div class="content">good content</div></body></html>`,
  388. expected: `<html><head></head><body><div class="content">good content</div></body></html>`,
  389. },
  390. {
  391. name: "elements without class or id are preserved",
  392. html: `<html><body><div>no attributes</div><p>paragraph</p></body></html>`,
  393. expected: `<html><head></head><body><div>no attributes</div><p>paragraph</p></body></html>`,
  394. },
  395. {
  396. name: "removes nested unlikely elements",
  397. html: `<html><body><div class="main"><div class="banner">nested banner</div><p>good content</p></div></body></html>`,
  398. expected: `<html><head></head><body><div class="main"><p>good content</p></div></body></html>`,
  399. },
  400. {
  401. name: "comprehensive unlikely candidates test",
  402. 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>`,
  403. expected: `<html><head></head><body><div class="article">good content</div></body></html>`,
  404. },
  405. {
  406. name: "preserves good candidates that contain unlikely words",
  407. 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>`,
  408. 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>`,
  409. },
  410. }
  411. for _, tc := range testCases {
  412. t.Run(tc.name, func(t *testing.T) {
  413. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  414. if err != nil {
  415. t.Fatalf("Failed to parse HTML: %v", err)
  416. }
  417. removeUnlikelyCandidates(doc)
  418. result, err := doc.Html()
  419. if err != nil {
  420. t.Fatalf("Failed to get HTML: %v", err)
  421. }
  422. // Normalize whitespace for comparison
  423. result = strings.TrimSpace(result)
  424. expected := strings.TrimSpace(tc.expected)
  425. if result != expected {
  426. t.Errorf("\nExpected:\n%s\n\nGot:\n%s", expected, result)
  427. }
  428. })
  429. }
  430. }
  431. func TestRemoveUnlikelyCandidatesShouldRemoveFunction(t *testing.T) {
  432. // Test the internal shouldRemove function behavior through the public interface
  433. testCases := []struct {
  434. name string
  435. attr string
  436. attrType string // "class" or "id"
  437. expected bool // true if should be removed
  438. }{
  439. // Special hardcoded cases
  440. {"popupbody in class", "popupbody", "class", true},
  441. {"contains popupbody in class", "main-popupbody-content", "class", true},
  442. {"ad suffix in class", "super-ad", "class", true},
  443. {"ad in middle of class", "pre-ad-post", "class", true},
  444. {"g-plus in class", "g-plus-share", "class", true},
  445. {"contains g-plus in class", "social-g-plus-button", "class", true},
  446. // Unlikely candidates regexp
  447. {"banner class", "banner", "class", true},
  448. {"breadcrumbs class", "breadcrumbs", "class", true},
  449. {"comment class", "comment", "class", true},
  450. {"sidebar class", "sidebar", "class", true},
  451. {"footer class", "footer", "class", true},
  452. // Unlikely candidates with good candidates (should not be removed)
  453. {"banner with article", "banner article", "class", false},
  454. {"comment with main", "comment main", "class", false},
  455. {"sidebar with body", "sidebar body", "class", false},
  456. {"footer with column", "footer column", "class", false},
  457. {"menu with shadow", "menu shadow", "class", false},
  458. // Case insensitive
  459. {"uppercase banner", "BANNER", "class", true},
  460. {"mixed case comment", "Comment", "class", true},
  461. {"uppercase with good", "BANNER ARTICLE", "class", false},
  462. // ID attributes
  463. {"banner id", "banner", "id", true},
  464. {"comment id", "comment", "id", true},
  465. {"banner with article id", "banner article", "id", false},
  466. // Good candidates only
  467. {"article class", "article", "class", false},
  468. {"main class", "main", "class", false},
  469. {"content class", "content", "class", false},
  470. {"body class", "body", "class", false},
  471. // No matches
  472. {"random class", "random-class", "class", false},
  473. {"normal content", "normal-content", "class", false},
  474. {"empty string", "", "class", false},
  475. }
  476. for _, tc := range testCases {
  477. t.Run(tc.name, func(t *testing.T) {
  478. var html string
  479. if tc.attrType == "class" {
  480. html = `<html><body><div class="` + tc.attr + `">content</div></body></html>`
  481. } else {
  482. html = `<html><body><div id="` + tc.attr + `">content</div></body></html>`
  483. }
  484. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  485. if err != nil {
  486. t.Fatalf("Failed to parse HTML: %v", err)
  487. }
  488. // Count elements before removal
  489. beforeCount := doc.Find("div").Length()
  490. removeUnlikelyCandidates(doc)
  491. // Count elements after removal
  492. afterCount := doc.Find("div").Length()
  493. wasRemoved := beforeCount > afterCount
  494. if wasRemoved != tc.expected {
  495. t.Errorf("Expected element to be removed: %v, but was removed: %v", tc.expected, wasRemoved)
  496. }
  497. })
  498. }
  499. }
  500. func TestRemoveUnlikelyCandidatesPreservation(t *testing.T) {
  501. testCases := []struct {
  502. name string
  503. html string
  504. description string
  505. }{
  506. {
  507. name: "preserves html tag",
  508. html: `<html class="banner sidebar footer"><body><div>content</div></body></html>`,
  509. description: "HTML tag should never be removed regardless of class",
  510. },
  511. {
  512. name: "preserves body tag",
  513. html: `<html><body class="banner sidebar footer"><div>content</div></body></html>`,
  514. description: "Body tag should never be removed regardless of class",
  515. },
  516. {
  517. name: "preserves elements in pre tags",
  518. html: `<html><body><pre><span class="banner">code</span></pre></body></html>`,
  519. description: "Elements within pre tags should be preserved",
  520. },
  521. {
  522. name: "preserves elements in code tags",
  523. html: `<html><body><code><span class="sidebar">code</span></code></body></html>`,
  524. description: "Elements within code tags should be preserved",
  525. },
  526. {
  527. name: "preserves nested elements in code blocks",
  528. html: `<html><body><pre><code><div class="comment"><span class="banner">nested</span></div></code></pre></body></html>`,
  529. description: "Deeply nested elements in code blocks should be preserved",
  530. },
  531. {
  532. name: "preserves elements in mixed code scenarios",
  533. html: `<html><body><div class="main"><pre><span class="sidebar">code</span></pre><code><div class="banner">more code</div></code></div></body></html>`,
  534. description: "Multiple code block scenarios should work correctly",
  535. },
  536. }
  537. for _, tc := range testCases {
  538. t.Run(tc.name, func(t *testing.T) {
  539. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  540. if err != nil {
  541. t.Fatalf("Failed to parse HTML: %v", err)
  542. }
  543. // Count specific elements before removal
  544. beforeHtml := doc.Find("html").Length()
  545. beforeBody := doc.Find("body").Length()
  546. beforePre := doc.Find("pre").Length()
  547. beforeCode := doc.Find("code").Length()
  548. removeUnlikelyCandidates(doc)
  549. // Count specific elements after removal
  550. afterHtml := doc.Find("html").Length()
  551. afterBody := doc.Find("body").Length()
  552. afterPre := doc.Find("pre").Length()
  553. afterCode := doc.Find("code").Length()
  554. // These elements should always be preserved
  555. if beforeHtml != afterHtml {
  556. t.Errorf("HTML elements were removed: before=%d, after=%d", beforeHtml, afterHtml)
  557. }
  558. if beforeBody != afterBody {
  559. t.Errorf("Body elements were removed: before=%d, after=%d", beforeBody, afterBody)
  560. }
  561. if beforePre != afterPre {
  562. t.Errorf("Pre elements were removed: before=%d, after=%d", beforePre, afterPre)
  563. }
  564. if beforeCode != afterCode {
  565. t.Errorf("Code elements were removed: before=%d, after=%d", beforeCode, afterCode)
  566. }
  567. // Verify that elements within code blocks are preserved
  568. if tc.name == "preserves elements in pre tags" || tc.name == "preserves elements in code tags" || tc.name == "preserves nested elements in code blocks" {
  569. spanInCode := doc.Find("pre span, code span, pre div, code div").Length()
  570. if spanInCode == 0 {
  571. t.Error("Elements within code blocks were incorrectly removed")
  572. }
  573. }
  574. })
  575. }
  576. }
  577. func TestGetArticle(t *testing.T) {
  578. testCases := []struct {
  579. name string
  580. html string
  581. expected string
  582. }{
  583. {
  584. name: "single top candidate",
  585. html: `<html><body><div id="main"><p>This is the main content.</p></div></body></html>`,
  586. expected: `<div><div><p>This is the main content.</p></div></div>`,
  587. },
  588. {
  589. name: "top candidate with high-scoring sibling",
  590. 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>`,
  591. 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>`,
  592. },
  593. {
  594. name: "top candidate with low-scoring sibling",
  595. html: `<html><body><div id="content"><p>Main content here.</p></div><div id="sidebar"><p>Sidebar content.</p></div></body></html>`,
  596. expected: `<div><div><div id="content"><p>Main content here.</p></div><div id="sidebar"><p>Sidebar content.</p></div></div></div>`,
  597. },
  598. {
  599. name: "paragraph with high link density",
  600. 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>`,
  601. 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>`,
  602. },
  603. {
  604. name: "paragraph with low link density and long content",
  605. 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>`,
  606. 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>`,
  607. },
  608. {
  609. name: "short paragraph with no links and sentence",
  610. html: `<html><body><div id="main"><p>This is content.</p></div><p>Short sentence.</p></body></html>`,
  611. expected: `<div><div><div id="main"><p>This is content.</p></div><p>Short sentence.</p></div></div>`,
  612. },
  613. {
  614. name: "short paragraph with no links but no sentence",
  615. html: `<html><body><div id="main"><p>This is content.</p></div><p>Short fragment</p></body></html>`,
  616. expected: `<div><div><div id="main"><p>This is content.</p></div><p>Short fragment</p></div></div>`,
  617. },
  618. {
  619. name: "mixed content with various elements",
  620. 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>`,
  621. 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>`,
  622. },
  623. {
  624. name: "nested content structure",
  625. html: `<html><body><div id="article"><div><p>Nested paragraph content.</p><span>Nested span.</span></div></div><p>Sibling paragraph.</p></body></html>`,
  626. expected: `<div><p>Sibling paragraph.</p><div><div><p>Nested paragraph content.</p><span>Nested span.</span></div></div></div>`,
  627. },
  628. {
  629. name: "empty top candidate",
  630. html: `<html><body><div id="empty"></div><p>Some content here.</p></body></html>`,
  631. expected: `<div><div><div id="empty"></div><p>Some content here.</p></div></div>`,
  632. },
  633. }
  634. for _, tc := range testCases {
  635. t.Run(tc.name, func(t *testing.T) {
  636. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  637. if err != nil {
  638. t.Fatalf("Failed to parse HTML: %v", err)
  639. }
  640. // Get candidates like the real extraction process
  641. candidates := getCandidates(doc)
  642. topCandidate := getTopCandidate(doc, candidates)
  643. result := getArticle(topCandidate, candidates)
  644. if result != tc.expected {
  645. t.Errorf("\nExpected:\n%s\n\nGot:\n%s", tc.expected, result)
  646. }
  647. })
  648. }
  649. }
  650. func TestGetArticleWithSpecificScoring(t *testing.T) {
  651. // Test specific scoring scenarios
  652. html := `<html><body>
  653. <div id="main-content" class="article">
  654. <p>This is the main article content with substantial text.</p>
  655. </div>
  656. <div id="high-score" class="content">
  657. <p>This sibling has high score due to good class name.</p>
  658. </div>
  659. <div id="low-score" class="sidebar">
  660. <p>This sibling has low score due to bad class name.</p>
  661. </div>
  662. <p>This is a standalone paragraph with enough content to be included based on length and should be appended.</p>
  663. <p>Short.</p>
  664. <p>This has <a href="#">too many</a> <a href="#">links</a> for its <a href="#">size</a>.</p>
  665. </body></html>`
  666. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  667. if err != nil {
  668. t.Fatalf("Failed to parse HTML: %v", err)
  669. }
  670. candidates := getCandidates(doc)
  671. topCandidate := getTopCandidate(doc, candidates)
  672. result := getArticle(topCandidate, candidates)
  673. // Verify the structure contains expected elements
  674. resultDoc, err := goquery.NewDocumentFromReader(strings.NewReader(result))
  675. if err != nil {
  676. t.Fatalf("Failed to parse result HTML: %v", err)
  677. }
  678. // Should contain the main content
  679. if resultDoc.Find("p:contains('main article content')").Length() == 0 {
  680. t.Error("Main content not found in result")
  681. }
  682. // Should contain high-scoring sibling
  683. if resultDoc.Find("p:contains('high score')").Length() == 0 {
  684. t.Error("High-scoring sibling not found in result")
  685. }
  686. // Should contain long standalone paragraph
  687. if resultDoc.Find("p:contains('standalone paragraph')").Length() == 0 {
  688. t.Error("Long standalone paragraph not found in result")
  689. }
  690. // Should contain short paragraph with sentence
  691. if resultDoc.Find("p:contains('Short.')").Length() == 0 {
  692. t.Error("Short paragraph with sentence not found in result")
  693. }
  694. // Should NOT contain low-scoring sibling
  695. if resultDoc.Find("p:contains('low score')").Length() > 0 {
  696. t.Error("Low-scoring sibling incorrectly included in result")
  697. }
  698. // Should NOT contain paragraph with too many links
  699. if resultDoc.Find("p:contains('too many')").Length() > 0 {
  700. t.Error("Paragraph with too many links incorrectly included in result")
  701. }
  702. }
  703. func TestGetArticleSiblingScoreThreshold(t *testing.T) {
  704. testCases := []struct {
  705. name string
  706. topScore float32
  707. expectedThreshold float32
  708. }{
  709. {
  710. name: "high score candidate",
  711. topScore: 100,
  712. expectedThreshold: 20, // 100 * 0.2 = 20
  713. },
  714. {
  715. name: "medium score candidate",
  716. topScore: 50,
  717. expectedThreshold: 10, // max(10, 50 * 0.2) = max(10, 10) = 10
  718. },
  719. {
  720. name: "low score candidate",
  721. topScore: 30,
  722. expectedThreshold: 10, // max(10, 30 * 0.2) = max(10, 6) = 10
  723. },
  724. {
  725. name: "very low score candidate",
  726. topScore: 5,
  727. expectedThreshold: 10, // max(10, 5 * 0.2) = max(10, 1) = 10
  728. },
  729. }
  730. for _, tc := range testCases {
  731. t.Run(tc.name, func(t *testing.T) {
  732. // Create a simple HTML structure
  733. html := `<html><body>
  734. <div id="main"><p>Main content</p></div>
  735. <div id="sibling"><p>Sibling content</p></div>
  736. </body></html>`
  737. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  738. if err != nil {
  739. t.Fatalf("Failed to parse HTML: %v", err)
  740. }
  741. // Create artificial candidates with specific scores
  742. mainDiv := doc.Find("#main").Get(0)
  743. siblingDiv := doc.Find("#sibling").Get(0)
  744. topCandidate := &candidate{
  745. selection: doc.Find("#main"),
  746. score: tc.topScore,
  747. }
  748. candidates := candidateList{
  749. mainDiv: topCandidate,
  750. siblingDiv: &candidate{
  751. selection: doc.Find("#sibling"),
  752. score: tc.expectedThreshold, // Set exactly at threshold
  753. },
  754. }
  755. result := getArticle(topCandidate, candidates)
  756. // Parse result to check if sibling was included
  757. resultDoc, err := goquery.NewDocumentFromReader(strings.NewReader(result))
  758. if err != nil {
  759. t.Fatalf("Failed to parse result HTML: %v", err)
  760. }
  761. // Sibling should be included since its score equals the threshold
  762. if resultDoc.Find("p:contains('Sibling content')").Length() == 0 {
  763. t.Errorf("Sibling with score %f should be included with threshold %f", tc.expectedThreshold, tc.expectedThreshold)
  764. }
  765. // Test with score just below threshold
  766. candidates[siblingDiv].score = tc.expectedThreshold - 0.1
  767. result2 := getArticle(topCandidate, candidates)
  768. resultDoc2, err := goquery.NewDocumentFromReader(strings.NewReader(result2))
  769. if err != nil {
  770. t.Fatalf("Failed to parse result HTML: %v", err)
  771. }
  772. // Sibling should NOT be included since its score is below threshold
  773. if resultDoc2.Find("p:contains('Sibling content')").Length() > 0 {
  774. t.Errorf("Sibling with score %f should not be included with threshold %f", tc.expectedThreshold-0.1, tc.expectedThreshold)
  775. }
  776. })
  777. }
  778. }
  779. func TestGetArticleParagraphSpecificLogic(t *testing.T) {
  780. // This test focuses specifically on the paragraph-specific logic in getArticle
  781. // where paragraphs are tested against link density and sentence criteria
  782. // even if they're not in the candidates list
  783. testCases := []struct {
  784. name string
  785. html string
  786. checkParagraph string // text to check for inclusion/exclusion
  787. shouldInclude bool
  788. reason string
  789. }{
  790. {
  791. name: "long paragraph with high link density should be excluded",
  792. 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>`,
  793. checkParagraph: "This is a paragraph with lots of",
  794. shouldInclude: false,
  795. reason: "Long paragraph with >= 25% link density should be excluded",
  796. },
  797. {
  798. name: "long paragraph with low link density should be included",
  799. 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>`,
  800. checkParagraph: "This is a very long paragraph",
  801. shouldInclude: true,
  802. reason: "Long paragraph with < 25% link density should be included",
  803. },
  804. {
  805. name: "short paragraph with no links and sentence should be included",
  806. html: `<html><body><div id="main"><p>Main content</p></div><p>Short sentence.</p></body></html>`,
  807. checkParagraph: "Short sentence.",
  808. shouldInclude: true,
  809. reason: "Short paragraph with 0% link density and sentence should be included",
  810. },
  811. {
  812. name: "short paragraph with no links but no sentence should be excluded",
  813. html: `<html><body><div id="main"><p>Main content</p></div><p>fragment</p></body></html>`,
  814. checkParagraph: "fragment",
  815. shouldInclude: false,
  816. reason: "Short paragraph with 0% link density but no sentence should be excluded",
  817. },
  818. {
  819. name: "short paragraph with links should be excluded",
  820. html: `<html><body><div id="main"><p>Main content</p></div><p>Short with <a href="#">link</a>.</p></body></html>`,
  821. checkParagraph: "Short with",
  822. shouldInclude: false,
  823. reason: "Short paragraph with any links should be excluded",
  824. },
  825. }
  826. for _, tc := range testCases {
  827. t.Run(tc.name, func(t *testing.T) {
  828. // Create a custom scenario where the paragraphs are NOT in the candidates list
  829. // so we can test the paragraph-specific logic
  830. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  831. if err != nil {
  832. t.Fatalf("Failed to parse HTML: %v", err)
  833. }
  834. // Create artificial candidates that only include the main div, not the paragraphs
  835. mainDiv := doc.Find("#main").Get(0)
  836. topCandidate := &candidate{
  837. selection: doc.Find("#main"),
  838. score: 50,
  839. }
  840. candidates := candidateList{
  841. mainDiv: topCandidate,
  842. // Deliberately not including the test paragraphs as candidates
  843. }
  844. result := getArticle(topCandidate, candidates)
  845. included := strings.Contains(result, tc.checkParagraph)
  846. if included != tc.shouldInclude {
  847. t.Errorf("%s: Expected included=%v, got included=%v\nReason: %s\nResult: %s",
  848. tc.name, tc.shouldInclude, included, tc.reason, result)
  849. }
  850. })
  851. }
  852. }
  853. func TestGetArticleLinkDensityThresholds(t *testing.T) {
  854. testCases := []struct {
  855. name string
  856. content string
  857. expectIncluded bool
  858. description string
  859. }{
  860. {
  861. name: "long content with no links",
  862. 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.",
  863. expectIncluded: true,
  864. description: "Content >= 80 chars with 0% link density should be included",
  865. },
  866. {
  867. name: "long content with acceptable link density",
  868. 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%.",
  869. expectIncluded: true,
  870. description: "Content >= 80 chars with < 25% link density should be included",
  871. },
  872. {
  873. name: "long content with high link density",
  874. 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>.",
  875. expectIncluded: true, // This appears to be included because it's processed as a sibling, not just through paragraph logic
  876. description: "Content with high link density - actual behavior includes siblings",
  877. },
  878. {
  879. name: "short content with no links and sentence",
  880. content: "This is a sentence.",
  881. expectIncluded: true,
  882. description: "Content < 80 chars with 0% link density and proper sentence should be included",
  883. },
  884. {
  885. name: "short content with no links but no sentence",
  886. content: "Just a fragment",
  887. expectIncluded: true, // The algorithm actually includes all siblings, paragraph rules are additional
  888. description: "Content < 80 chars with 0% link density but no sentence - still included as sibling",
  889. },
  890. {
  891. name: "short content with links",
  892. content: "Text with <a href='#'>link</a>.",
  893. expectIncluded: true, // Still included as sibling
  894. description: "Content < 80 chars with any links - still included as sibling",
  895. },
  896. {
  897. name: "edge case: exactly 80 characters no links",
  898. content: "This paragraph has exactly eighty characters and should be included ok.",
  899. expectIncluded: true,
  900. description: "Content with exactly 80 chars and no links should be included",
  901. },
  902. {
  903. name: "edge case: 79 characters no links with sentence",
  904. content: "This paragraph has seventy-nine characters and should be included.",
  905. expectIncluded: true,
  906. description: "Content with 79 chars, no links, and sentence should be included",
  907. },
  908. {
  909. name: "sentence with period at end",
  910. content: "Sentence ending with period.",
  911. expectIncluded: true,
  912. description: "Short content ending with period should be included",
  913. },
  914. {
  915. name: "sentence with period in middle",
  916. content: "Sentence with period. And more",
  917. expectIncluded: true,
  918. description: "Short content with period in middle should be included",
  919. },
  920. }
  921. for _, tc := range testCases {
  922. t.Run(tc.name, func(t *testing.T) {
  923. html := fmt.Sprintf(`<html><body>
  924. <div id="main"><p>Main content</p></div>
  925. <p>%s</p>
  926. </body></html>`, tc.content)
  927. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  928. if err != nil {
  929. t.Fatalf("Failed to parse HTML: %v", err)
  930. }
  931. candidates := getCandidates(doc)
  932. topCandidate := getTopCandidate(doc, candidates)
  933. result := getArticle(topCandidate, candidates)
  934. // Check if the test content was included
  935. included := strings.Contains(result, tc.content) || strings.Contains(result, strings.ReplaceAll(tc.content, `'`, `"`))
  936. if included != tc.expectIncluded {
  937. t.Errorf("%s: Expected included=%v, got included=%v\nContent: %s\nResult: %s",
  938. tc.description, tc.expectIncluded, included, tc.content, result)
  939. }
  940. })
  941. }
  942. }
  943. func TestGetArticleTagWrapping(t *testing.T) {
  944. // Test that paragraph elements keep their tag, others become div
  945. html := `<html><body>
  946. <div id="main"><p>Main content</p></div>
  947. <p>Paragraph content that should stay as p tag.</p>
  948. <div>Div content that should become div tag.</div>
  949. <span>Span content that should become div tag.</span>
  950. <section>Section content that should become div tag.</section>
  951. </body></html>`
  952. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  953. if err != nil {
  954. t.Fatalf("Failed to parse HTML: %v", err)
  955. }
  956. candidates := getCandidates(doc)
  957. topCandidate := getTopCandidate(doc, candidates)
  958. result := getArticle(topCandidate, candidates)
  959. // Parse result to verify tag wrapping
  960. resultDoc, err := goquery.NewDocumentFromReader(strings.NewReader(result))
  961. if err != nil {
  962. t.Fatalf("Failed to parse result HTML: %v", err)
  963. }
  964. // Check that paragraph content is wrapped in <p> tags
  965. paragraphElements := resultDoc.Find("p")
  966. foundParagraphContent := false
  967. paragraphElements.Each(func(i int, s *goquery.Selection) {
  968. if strings.Contains(s.Text(), "Paragraph content") {
  969. foundParagraphContent = true
  970. }
  971. })
  972. if !foundParagraphContent {
  973. t.Error("Paragraph content should be wrapped in <p> tags")
  974. }
  975. // Check that non-paragraph content is wrapped in <div> tags
  976. divElements := resultDoc.Find("div")
  977. foundDivContent := false
  978. foundSpanContent := false
  979. foundSectionContent := false
  980. divElements.Each(func(i int, s *goquery.Selection) {
  981. text := s.Text()
  982. if strings.Contains(text, "Div content") {
  983. foundDivContent = true
  984. }
  985. if strings.Contains(text, "Span content") {
  986. foundSpanContent = true
  987. }
  988. if strings.Contains(text, "Section content") {
  989. foundSectionContent = true
  990. }
  991. })
  992. if !foundDivContent {
  993. t.Error("Div content should be wrapped in <div> tags")
  994. }
  995. if !foundSpanContent {
  996. t.Error("Span content should be wrapped in <div> tags")
  997. }
  998. if !foundSectionContent {
  999. t.Error("Section content should be wrapped in <div> tags")
  1000. }
  1001. // Verify overall structure
  1002. if !strings.HasPrefix(result, "<div>") || !strings.HasSuffix(result, "</div>") {
  1003. t.Error("Result should be wrapped in outer <div> tags")
  1004. }
  1005. }
  1006. func TestGetArticleEmptyAndEdgeCases(t *testing.T) {
  1007. testCases := []struct {
  1008. name string
  1009. html string
  1010. expected string
  1011. }{
  1012. {
  1013. name: "empty body",
  1014. html: `<html><body></body></html>`,
  1015. expected: `<div><div></div></div>`, // getTopCandidate returns body, body has no inner HTML
  1016. },
  1017. {
  1018. name: "only whitespace content",
  1019. html: `<html><body><div id="main"> </div></body></html>`,
  1020. expected: `<div><div><div id="main"> </div></div></div>`, // body is top candidate, includes inner div
  1021. },
  1022. {
  1023. name: "self-closing elements",
  1024. html: `<html><body><div id="main"><p>Content</p><br><img src="test.jpg"></div></body></html>`,
  1025. expected: `<div><div><div id="main"><p>Content</p><br/><img src="test.jpg"/></div></div></div>`, // body includes inner div
  1026. },
  1027. {
  1028. name: "nested structure with no text",
  1029. html: `<html><body><div id="main"><div><div></div></div></div></body></html>`,
  1030. expected: `<div><div><div id="main"><div><div></div></div></div></div></div>`, // body includes inner div
  1031. },
  1032. {
  1033. name: "complex nesting with mixed content",
  1034. html: `<html><body><div id="main"><div class="inner"><span>Nested content</span><p>Paragraph in nested structure.</p></div></div></body></html>`,
  1035. 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
  1036. },
  1037. }
  1038. for _, tc := range testCases {
  1039. t.Run(tc.name, func(t *testing.T) {
  1040. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  1041. if err != nil {
  1042. t.Fatalf("Failed to parse HTML: %v", err)
  1043. }
  1044. candidates := getCandidates(doc)
  1045. topCandidate := getTopCandidate(doc, candidates)
  1046. result := getArticle(topCandidate, candidates)
  1047. if result != tc.expected {
  1048. t.Errorf("\nExpected:\n%s\n\nGot:\n%s", tc.expected, result)
  1049. }
  1050. })
  1051. }
  1052. }
  1053. // Test helper functions used by getArticle
  1054. func TestGetLinkDensity(t *testing.T) {
  1055. testCases := []struct {
  1056. name string
  1057. html string
  1058. expected float32
  1059. }{
  1060. {
  1061. name: "no links",
  1062. html: `<div>This is plain text content with no links at all.</div>`,
  1063. expected: 0.0,
  1064. },
  1065. {
  1066. name: "all links",
  1067. html: `<div><a href="#">Link one</a><a href="#">Link two</a></div>`,
  1068. expected: 1.0,
  1069. },
  1070. {
  1071. name: "half links",
  1072. html: `<div>Plain text <a href="#">Link text</a></div>`,
  1073. expected: 0.45, // "Link text" is 9 chars, "Plain text Link text" is 20 chars
  1074. },
  1075. {
  1076. name: "nested links",
  1077. html: `<div>Text <a href="#">Link <span>nested</span></a> more text</div>`,
  1078. expected: float32(11) / float32(26), // "Link nested" vs "Text Link nested more text"
  1079. },
  1080. {
  1081. name: "empty content",
  1082. html: `<div></div>`,
  1083. expected: 0.0,
  1084. },
  1085. {
  1086. name: "whitespace only",
  1087. html: `<div> </div>`,
  1088. expected: 0.0,
  1089. },
  1090. {
  1091. name: "links with no text",
  1092. html: `<div>Text content <a href="#"></a></div>`,
  1093. expected: 0.0, // Empty link contributes 0 to link length
  1094. },
  1095. {
  1096. name: "multiple links",
  1097. html: `<div>Start <a href="#">first</a> middle <a href="#">second</a> end</div>`,
  1098. expected: float32(11) / float32(29), // "firstsecond" vs "Start first middle second end"
  1099. },
  1100. }
  1101. for _, tc := range testCases {
  1102. t.Run(tc.name, func(t *testing.T) {
  1103. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  1104. if err != nil {
  1105. t.Fatalf("Failed to parse HTML: %v", err)
  1106. }
  1107. selection := doc.Find("div").First()
  1108. result := getLinkDensity(selection)
  1109. // Use a small epsilon for float comparison
  1110. epsilon := float32(0.001)
  1111. if result < tc.expected-epsilon || result > tc.expected+epsilon {
  1112. t.Errorf("Expected link density %f, got %f for %s", tc.expected, result, tc.name)
  1113. }
  1114. })
  1115. }
  1116. }
  1117. func TestContainsSentence(t *testing.T) {
  1118. testCases := []struct {
  1119. name string
  1120. content string
  1121. expected bool
  1122. }{
  1123. {
  1124. name: "ends with period",
  1125. content: "This is a sentence.",
  1126. expected: true,
  1127. },
  1128. {
  1129. name: "contains period with space",
  1130. content: "First sentence. Second sentence",
  1131. expected: true,
  1132. },
  1133. {
  1134. name: "no sentence markers",
  1135. content: "Just a fragment",
  1136. expected: false,
  1137. },
  1138. {
  1139. name: "period without space",
  1140. content: "Something.else",
  1141. expected: false,
  1142. },
  1143. {
  1144. name: "empty string",
  1145. content: "",
  1146. expected: false,
  1147. },
  1148. {
  1149. name: "only period",
  1150. content: ".",
  1151. expected: true,
  1152. },
  1153. {
  1154. name: "period and space at end",
  1155. content: "Sentence. ",
  1156. expected: true,
  1157. },
  1158. {
  1159. name: "multiple sentences",
  1160. content: "First. Second. Third",
  1161. expected: true,
  1162. },
  1163. {
  1164. name: "period in middle only",
  1165. content: "Text. More text",
  1166. expected: true,
  1167. },
  1168. {
  1169. name: "whitespace around period",
  1170. content: "Text . More",
  1171. expected: true,
  1172. },
  1173. }
  1174. for _, tc := range testCases {
  1175. t.Run(tc.name, func(t *testing.T) {
  1176. result := containsSentence(tc.content)
  1177. if result != tc.expected {
  1178. t.Errorf("Expected %v for content %q, got %v", tc.expected, tc.content, result)
  1179. }
  1180. })
  1181. }
  1182. }
  1183. func TestScoreNode(t *testing.T) {
  1184. testCases := []struct {
  1185. name string
  1186. html string
  1187. expectedScore float32
  1188. expectedTag string
  1189. }{
  1190. {
  1191. name: "div element with no class or id",
  1192. html: `<div>Some content</div>`,
  1193. expectedScore: 5,
  1194. expectedTag: "div",
  1195. },
  1196. {
  1197. name: "pre element with no class or id",
  1198. html: `<pre>Some code</pre>`,
  1199. expectedScore: 3,
  1200. expectedTag: "pre",
  1201. },
  1202. {
  1203. name: "td element with no class or id",
  1204. html: `<table><tr><td>Table cell</td></tr></table>`,
  1205. expectedScore: 3,
  1206. expectedTag: "td",
  1207. },
  1208. {
  1209. name: "blockquote element with no class or id",
  1210. html: `<blockquote>Quote</blockquote>`,
  1211. expectedScore: 3,
  1212. expectedTag: "blockquote",
  1213. },
  1214. {
  1215. name: "img element with no class or id",
  1216. html: `<img src="test.jpg" alt="test">`,
  1217. expectedScore: 3,
  1218. expectedTag: "img",
  1219. },
  1220. {
  1221. name: "ol element with no class or id",
  1222. html: `<ol><li>Item</li></ol>`,
  1223. expectedScore: -3,
  1224. expectedTag: "ol",
  1225. },
  1226. {
  1227. name: "ul element with no class or id",
  1228. html: `<ul><li>Item</li></ul>`,
  1229. expectedScore: -3,
  1230. expectedTag: "ul",
  1231. },
  1232. {
  1233. name: "address element with no class or id",
  1234. html: `<address>Contact info</address>`,
  1235. expectedScore: -3,
  1236. expectedTag: "address",
  1237. },
  1238. {
  1239. name: "dl element with no class or id",
  1240. html: `<dl><dt>Term</dt><dd>Definition</dd></dl>`,
  1241. expectedScore: -3,
  1242. expectedTag: "dl",
  1243. },
  1244. {
  1245. name: "dd element with no class or id",
  1246. html: `<dd>Definition</dd>`,
  1247. expectedScore: -3,
  1248. expectedTag: "dd",
  1249. },
  1250. {
  1251. name: "dt element with no class or id",
  1252. html: `<dt>Term</dt>`,
  1253. expectedScore: -3,
  1254. expectedTag: "dt",
  1255. },
  1256. {
  1257. name: "li element with no class or id",
  1258. html: `<li>List item</li>`,
  1259. expectedScore: -3,
  1260. expectedTag: "li",
  1261. },
  1262. {
  1263. name: "form element with no class or id",
  1264. html: `<form>Form content</form>`,
  1265. expectedScore: -3,
  1266. expectedTag: "form",
  1267. },
  1268. {
  1269. name: "h1 element with no class or id",
  1270. html: `<h1>Heading</h1>`,
  1271. expectedScore: -5,
  1272. expectedTag: "h1",
  1273. },
  1274. {
  1275. name: "h2 element with no class or id",
  1276. html: `<h2>Heading</h2>`,
  1277. expectedScore: -5,
  1278. expectedTag: "h2",
  1279. },
  1280. {
  1281. name: "h3 element with no class or id",
  1282. html: `<h3>Heading</h3>`,
  1283. expectedScore: -5,
  1284. expectedTag: "h3",
  1285. },
  1286. {
  1287. name: "h4 element with no class or id",
  1288. html: `<h4>Heading</h4>`,
  1289. expectedScore: -5,
  1290. expectedTag: "h4",
  1291. },
  1292. {
  1293. name: "h5 element with no class or id",
  1294. html: `<h5>Heading</h5>`,
  1295. expectedScore: -5,
  1296. expectedTag: "h5",
  1297. },
  1298. {
  1299. name: "h6 element with no class or id",
  1300. html: `<h6>Heading</h6>`,
  1301. expectedScore: -5,
  1302. expectedTag: "h6",
  1303. },
  1304. {
  1305. name: "th element with no class or id",
  1306. html: `<table><tr><th>Header cell</th></tr></table>`,
  1307. expectedScore: -5,
  1308. expectedTag: "th",
  1309. },
  1310. {
  1311. name: "p element with no class or id (default case)",
  1312. html: `<p>Paragraph content</p>`,
  1313. expectedScore: 0,
  1314. expectedTag: "p",
  1315. },
  1316. {
  1317. name: "span element with no class or id (default case)",
  1318. html: `<span>Span content</span>`,
  1319. expectedScore: 0,
  1320. expectedTag: "span",
  1321. },
  1322. }
  1323. for _, tc := range testCases {
  1324. t.Run(tc.name, func(t *testing.T) {
  1325. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  1326. if err != nil {
  1327. t.Fatal(err)
  1328. }
  1329. selection := doc.Find(tc.expectedTag)
  1330. if selection.Length() == 0 {
  1331. t.Fatalf("Could not find element with tag %s", tc.expectedTag)
  1332. }
  1333. candidate := scoreNode(selection)
  1334. if candidate.score != tc.expectedScore {
  1335. t.Errorf("Expected score %f, got %f", tc.expectedScore, candidate.score)
  1336. }
  1337. if candidate.selection != selection {
  1338. t.Error("Expected selection to be preserved in candidate")
  1339. }
  1340. if candidate.Node() == nil {
  1341. t.Errorf("Expected valid node, got nil")
  1342. } else if candidate.Node().Data != tc.expectedTag {
  1343. t.Errorf("Expected node tag %s, got %s", tc.expectedTag, candidate.Node().Data)
  1344. }
  1345. })
  1346. }
  1347. }
  1348. func TestScoreNodeWithClassWeights(t *testing.T) {
  1349. testCases := []struct {
  1350. name string
  1351. html string
  1352. expectedScore float32
  1353. description string
  1354. }{
  1355. {
  1356. name: "div with positive class",
  1357. html: `<div class="content">Content</div>`,
  1358. expectedScore: 30, // 5 (div) + 25 (positive class)
  1359. description: "div base score + positive class weight",
  1360. },
  1361. {
  1362. name: "div with negative class",
  1363. html: `<div class="comment">Content</div>`,
  1364. expectedScore: -20, // 5 (div) + (-25) (negative class)
  1365. description: "div base score + negative class weight",
  1366. },
  1367. {
  1368. name: "div with positive id",
  1369. html: `<div id="main">Content</div>`,
  1370. expectedScore: 30, // 5 (div) + 25 (positive id)
  1371. description: "div base score + positive id weight",
  1372. },
  1373. {
  1374. name: "div with negative id",
  1375. html: `<div id="sidebar">Content</div>`,
  1376. expectedScore: -20, // 5 (div) + (-25) (negative id)
  1377. description: "div base score + negative id weight",
  1378. },
  1379. {
  1380. name: "div with both positive class and id",
  1381. html: `<div class="content" id="main">Content</div>`,
  1382. expectedScore: 55, // 5 (div) + 25 (positive class) + 25 (positive id)
  1383. description: "div base score + positive class weight + positive id weight",
  1384. },
  1385. {
  1386. name: "div with both negative class and id",
  1387. html: `<div class="comment" id="sidebar">Content</div>`,
  1388. expectedScore: -45, // 5 (div) + (-25) (negative class) + (-25) (negative id)
  1389. description: "div base score + negative class weight + negative id weight",
  1390. },
  1391. {
  1392. name: "div with mixed class and id weights",
  1393. html: `<div class="content" id="sidebar">Content</div>`,
  1394. expectedScore: 5, // 5 (div) + 25 (positive class) + (-25) (negative id)
  1395. description: "div base score + positive class weight + negative id weight",
  1396. },
  1397. {
  1398. name: "h1 with positive class (should still be negative overall)",
  1399. html: `<h1 class="content">Heading</h1>`,
  1400. expectedScore: 20, // -5 (h1) + 25 (positive class)
  1401. description: "h1 base score + positive class weight",
  1402. },
  1403. {
  1404. name: "ul with negative class (more negative)",
  1405. html: `<ul class="comment">List</ul>`,
  1406. expectedScore: -28, // -3 (ul) + (-25) (negative class)
  1407. description: "ul base score + negative class weight",
  1408. },
  1409. {
  1410. name: "p with neutral class/id (no weight change)",
  1411. html: `<p class="normal" id="regular">Paragraph</p>`,
  1412. expectedScore: 0, // 0 (p) + 0 (neutral class) + 0 (neutral id)
  1413. description: "p base score with neutral class and id",
  1414. },
  1415. }
  1416. for _, tc := range testCases {
  1417. t.Run(tc.name, func(t *testing.T) {
  1418. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  1419. if err != nil {
  1420. t.Fatal(err)
  1421. }
  1422. // Find the first non-html/body element
  1423. 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()
  1424. if selection.Length() == 0 {
  1425. t.Fatal("Could not find element")
  1426. }
  1427. candidate := scoreNode(selection)
  1428. if candidate.score != tc.expectedScore {
  1429. t.Errorf("%s: Expected score %f, got %f", tc.description, tc.expectedScore, candidate.score)
  1430. }
  1431. })
  1432. }
  1433. }
  1434. func TestScoreNodeEdgeCases(t *testing.T) {
  1435. t.Run("empty selection", func(t *testing.T) {
  1436. doc, err := goquery.NewDocumentFromReader(strings.NewReader(`<div></div>`))
  1437. if err != nil {
  1438. t.Fatal(err)
  1439. }
  1440. // Create empty selection
  1441. emptySelection := doc.Find("nonexistent")
  1442. if emptySelection.Length() != 0 {
  1443. t.Fatal("Expected empty selection")
  1444. }
  1445. // scoreNode should handle empty selection gracefully
  1446. candidate := scoreNode(emptySelection)
  1447. if candidate == nil {
  1448. t.Error("Expected non-nil candidate even for empty selection")
  1449. }
  1450. // Should have score 0 and empty selection
  1451. if candidate != nil && candidate.score != 0 {
  1452. t.Errorf("Expected score 0 for empty selection, got %f", candidate.score)
  1453. }
  1454. if candidate.selection.Length() != 0 {
  1455. t.Error("Expected candidate to preserve empty selection")
  1456. }
  1457. // Node() should return nil for empty selection
  1458. if candidate.Node() != nil {
  1459. t.Error("Expected Node() to return nil for empty selection")
  1460. }
  1461. // String() should handle empty selection gracefully
  1462. str := candidate.String()
  1463. expected := "empty => 0.000000"
  1464. if str != expected {
  1465. t.Errorf("Expected String() to return %q, got %q", expected, str)
  1466. }
  1467. })
  1468. t.Run("multiple elements in selection", func(t *testing.T) {
  1469. html := `<div>
  1470. <p class="article">First paragraph</p>
  1471. <p class="sidebar">Second paragraph</p>
  1472. </div>`
  1473. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  1474. if err != nil {
  1475. t.Fatal(err)
  1476. }
  1477. // Select all p elements
  1478. selection := doc.Find("p")
  1479. if selection.Length() != 2 {
  1480. t.Fatalf("Expected 2 p elements, got %d", selection.Length())
  1481. }
  1482. // scoreNode should only consider the first element in the selection
  1483. candidate := scoreNode(selection)
  1484. // Should score based on first p element (class="article")
  1485. expectedScore := float32(25) // 0 (p) + 25 (positive class)
  1486. if candidate.score != expectedScore {
  1487. t.Errorf("Expected score %f, got %f", expectedScore, candidate.score)
  1488. }
  1489. if candidate.Node() == nil {
  1490. t.Error("Expected valid node, got nil")
  1491. } else if candidate.Node().Data != "p" {
  1492. t.Errorf("Expected node tag p, got %s", candidate.Node().Data)
  1493. }
  1494. })
  1495. t.Run("nested elements", func(t *testing.T) {
  1496. html := `<div class="article">
  1497. <p class="content">
  1498. <span class="highlight">Text</span>
  1499. </p>
  1500. </div>`
  1501. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  1502. if err != nil {
  1503. t.Fatal(err)
  1504. }
  1505. // Test scoring each level
  1506. divSelection := doc.Find("div")
  1507. divCandidate := scoreNode(divSelection)
  1508. expectedDivScore := float32(30) // 5 (div) + 25 (positive class)
  1509. if divCandidate.score != expectedDivScore {
  1510. t.Errorf("Div score: expected %f, got %f", expectedDivScore, divCandidate.score)
  1511. }
  1512. pSelection := doc.Find("p")
  1513. pCandidate := scoreNode(pSelection)
  1514. expectedPScore := float32(25) // 0 (p) + 25 (positive class)
  1515. if pCandidate.score != expectedPScore {
  1516. t.Errorf("P score: expected %f, got %f", expectedPScore, pCandidate.score)
  1517. }
  1518. spanSelection := doc.Find("span")
  1519. spanCandidate := scoreNode(spanSelection)
  1520. expectedSpanScore := float32(0) // 0 (span) + 0 (neutral class)
  1521. if spanCandidate.score != expectedSpanScore {
  1522. t.Errorf("Span score: expected %f, got %f", expectedSpanScore, spanCandidate.score)
  1523. }
  1524. })
  1525. }
  1526. func TestTransformMisusedDivsIntoParagraphs(t *testing.T) {
  1527. testCases := []struct {
  1528. name string
  1529. input string
  1530. expected string
  1531. description string
  1532. }{
  1533. {
  1534. name: "div with only text should become paragraph",
  1535. input: `<div>Simple text content</div>`,
  1536. expected: `<p>Simple text content</p>`,
  1537. description: "div containing only text should be converted to p",
  1538. },
  1539. {
  1540. name: "div with inline elements should become paragraph",
  1541. input: `<div>Text with <span>inline</span> and <em>emphasis</em></div>`,
  1542. expected: `<p>Text with <span>inline</span> and <em>emphasis</em></p>`,
  1543. description: "div with inline elements should be converted to p",
  1544. },
  1545. {
  1546. name: "div with strong and other inline elements",
  1547. input: `<div>Some <strong>bold</strong> and <i>italic</i> text</div>`,
  1548. expected: `<p>Some <strong>bold</strong> and <i>italic</i> text</p>`,
  1549. description: "div with inline formatting should be converted to p",
  1550. },
  1551. {
  1552. name: "div with anchor tag should NOT become paragraph",
  1553. input: `<div>Text with <a href="#">link</a></div>`,
  1554. expected: `<div>Text with <a href="#">link</a></div>`,
  1555. description: "div containing anchor tag should remain div (matches regex)",
  1556. },
  1557. {
  1558. name: "div with paragraph should NOT become paragraph",
  1559. input: `<div><p>Nested paragraph</p></div>`,
  1560. expected: `<div><p>Nested paragraph</p></div>`,
  1561. description: "div containing p tag should remain div",
  1562. },
  1563. {
  1564. name: "div with blockquote should NOT become paragraph",
  1565. input: `<div><blockquote>Quote</blockquote></div>`,
  1566. expected: `<div><blockquote>Quote</blockquote></div>`,
  1567. description: "div containing blockquote should remain div",
  1568. },
  1569. {
  1570. name: "div with nested div should NOT become paragraph",
  1571. input: `<div><div>Nested div</div></div>`,
  1572. expected: `<div><p>Nested div</p></div>`,
  1573. description: "outer div has nested div (matches regex), inner div has text only (gets converted)",
  1574. },
  1575. {
  1576. name: "div with img should NOT become paragraph",
  1577. input: `<div><img src="test.jpg" alt="test"></div>`,
  1578. expected: `<div><img src="test.jpg" alt="test"/></div>`,
  1579. description: "div containing img should remain div",
  1580. },
  1581. {
  1582. name: "div with ol should NOT become paragraph",
  1583. input: `<div><ol><li>Item</li></ol></div>`,
  1584. expected: `<div><ol><li>Item</li></ol></div>`,
  1585. description: "div containing ol should remain div",
  1586. },
  1587. {
  1588. name: "div with ul should NOT become paragraph",
  1589. input: `<div><ul><li>Item</li></ul></div>`,
  1590. expected: `<div><ul><li>Item</li></ul></div>`,
  1591. description: "div containing ul should remain div",
  1592. },
  1593. {
  1594. name: "div with pre should NOT become paragraph",
  1595. input: `<div><pre>Code block</pre></div>`,
  1596. expected: `<div><pre>Code block</pre></div>`,
  1597. description: "div containing pre should remain div",
  1598. },
  1599. {
  1600. name: "div with table should NOT become paragraph",
  1601. input: `<div><table><tr><td>Cell</td></tr></table></div>`,
  1602. expected: `<div><table><tbody><tr><td>Cell</td></tr></tbody></table></div>`,
  1603. description: "div containing table should remain div (note: GoQuery adds tbody)",
  1604. },
  1605. {
  1606. name: "div with dl should NOT become paragraph",
  1607. input: `<div><dl><dt>Term</dt><dd>Definition</dd></dl></div>`,
  1608. expected: `<div><dl><dt>Term</dt><dd>Definition</dd></dl></div>`,
  1609. description: "div containing dl should remain div",
  1610. },
  1611. {
  1612. name: "empty div should become paragraph",
  1613. input: `<div></div>`,
  1614. expected: `<p></p>`,
  1615. description: "empty div should be converted to p",
  1616. },
  1617. {
  1618. name: "div with only whitespace should become paragraph",
  1619. input: `<div> </div>`,
  1620. expected: `<p> </p>`,
  1621. description: "div with only whitespace should be converted to p",
  1622. },
  1623. {
  1624. name: "div with self-closing anchor tag should NOT become paragraph",
  1625. input: `<div>Text <a/> more text</div>`,
  1626. expected: `<div>Text <a> more text</a></div>`,
  1627. description: "div with self-closing anchor should remain div (note: GoQuery normalizes self-closing tags)",
  1628. },
  1629. {
  1630. name: "case insensitive matching - uppercase A",
  1631. input: `<div>Text with <A href="#">link</A></div>`,
  1632. expected: `<div>Text with <a href="#">link</a></div>`,
  1633. description: "regex should be case insensitive (note: GoQuery normalizes case)",
  1634. },
  1635. {
  1636. name: "case insensitive matching - uppercase IMG",
  1637. input: `<div><IMG src="test.jpg"></div>`,
  1638. expected: `<div><img src="test.jpg"/></div>`,
  1639. description: "regex should be case insensitive (note: GoQuery normalizes case)",
  1640. },
  1641. {
  1642. name: "multiple divs transformation",
  1643. input: `<div>Text only</div><div><p>Has paragraph</p></div><div>More text</div>`,
  1644. expected: `<p>Text only</p><div><p>Has paragraph</p></div><p>More text</p>`,
  1645. description: "should transform multiple divs appropriately",
  1646. },
  1647. {
  1648. name: "nested divs where inner gets transformed",
  1649. input: `<div><div>Inner text only</div><p>Paragraph</p></div>`,
  1650. expected: `<div><p>Inner text only</p><p>Paragraph</p></div>`,
  1651. description: "inner div should be transformed even if outer div isn't",
  1652. },
  1653. }
  1654. for _, tc := range testCases {
  1655. t.Run(tc.name, func(t *testing.T) {
  1656. // Wrap input in a basic HTML structure
  1657. html := fmt.Sprintf(`<html><body>%s</body></html>`, tc.input)
  1658. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  1659. if err != nil {
  1660. t.Fatalf("Failed to parse HTML: %v", err)
  1661. }
  1662. // Apply the transformation
  1663. transformMisusedDivsIntoParagraphs(doc)
  1664. // Extract the body content
  1665. bodyHtml, err := doc.Find("body").Html()
  1666. if err != nil {
  1667. t.Fatalf("Failed to get body HTML: %v", err)
  1668. }
  1669. // Clean up whitespace for comparison
  1670. result := strings.TrimSpace(bodyHtml)
  1671. expected := strings.TrimSpace(tc.expected)
  1672. if result != expected {
  1673. t.Errorf("%s\nExpected: %s\nGot: %s", tc.description, expected, result)
  1674. }
  1675. })
  1676. }
  1677. }
  1678. func TestTransformMisusedDivsIntoParagraphsEdgeCases(t *testing.T) {
  1679. t.Run("document with no divs", func(t *testing.T) {
  1680. html := `<html><body><p>No divs here</p><span>Just other elements</span></body></html>`
  1681. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  1682. if err != nil {
  1683. t.Fatal(err)
  1684. }
  1685. // Should not panic or cause issues
  1686. transformMisusedDivsIntoParagraphs(doc)
  1687. bodyHtml, _ := doc.Find("body").Html()
  1688. expected := `<p>No divs here</p><span>Just other elements</span>`
  1689. if strings.TrimSpace(bodyHtml) != expected {
  1690. t.Errorf("Expected no changes to document without divs")
  1691. }
  1692. })
  1693. t.Run("empty document", func(t *testing.T) {
  1694. html := `<html><body></body></html>`
  1695. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  1696. if err != nil {
  1697. t.Fatal(err)
  1698. }
  1699. // Should not panic with empty document
  1700. transformMisusedDivsIntoParagraphs(doc)
  1701. bodyHtml, _ := doc.Find("body").Html()
  1702. if strings.TrimSpace(bodyHtml) != "" {
  1703. t.Errorf("Expected empty body to remain empty")
  1704. }
  1705. })
  1706. t.Run("deeply nested divs", func(t *testing.T) {
  1707. html := `<html><body><div><div><div>Deep text</div></div></div></body></html>`
  1708. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  1709. if err != nil {
  1710. t.Fatal(err)
  1711. }
  1712. transformMisusedDivsIntoParagraphs(doc)
  1713. bodyHtml, _ := doc.Find("body").Html()
  1714. // The outer divs contain other divs (matches regex), so they remain divs
  1715. // Only the innermost div with just text gets converted to p
  1716. expected := `<div><div><p>Deep text</p></div></div>`
  1717. if strings.TrimSpace(bodyHtml) != expected {
  1718. t.Errorf("Expected nested div transformation\nGot: %s\nExpected: %s", strings.TrimSpace(bodyHtml), expected)
  1719. }
  1720. })
  1721. t.Run("complex mixed content", func(t *testing.T) {
  1722. html := `<html><body>
  1723. <div>Text only div</div>
  1724. <div><a href="#">Link div</a></div>
  1725. <div><span>Inline</span> text</div>
  1726. <div><p>Block element</p></div>
  1727. </body></html>`
  1728. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  1729. if err != nil {
  1730. t.Fatal(err)
  1731. }
  1732. transformMisusedDivsIntoParagraphs(doc)
  1733. // Count paragraphs and divs
  1734. pCount := doc.Find("p").Length()
  1735. divCount := doc.Find("div").Length()
  1736. // Should have 3 paragraphs (original p + 2 converted divs) and 2 divs (link div + block element div)
  1737. expectedPCount := 3
  1738. expectedDivCount := 2
  1739. if pCount != expectedPCount {
  1740. t.Errorf("Expected %d paragraphs, got %d", expectedPCount, pCount)
  1741. }
  1742. if divCount != expectedDivCount {
  1743. t.Errorf("Expected %d divs, got %d", expectedDivCount, divCount)
  1744. }
  1745. })
  1746. }
  1747. func TestCandidateString(t *testing.T) {
  1748. testCases := []struct {
  1749. name string
  1750. html string
  1751. expected string
  1752. setup func(*goquery.Document) *candidate
  1753. }{
  1754. {
  1755. name: "empty candidate",
  1756. html: `<div></div>`,
  1757. expected: "empty => 0.000000",
  1758. setup: func(doc *goquery.Document) *candidate {
  1759. emptySelection := doc.Find("nonexistent")
  1760. return &candidate{selection: emptySelection, score: 0}
  1761. },
  1762. },
  1763. {
  1764. name: "candidate with no class or id",
  1765. html: `<div>Content</div>`,
  1766. expected: "div => 5.000000",
  1767. setup: func(doc *goquery.Document) *candidate {
  1768. selection := doc.Find("div")
  1769. return scoreNode(selection)
  1770. },
  1771. },
  1772. {
  1773. name: "candidate with class only",
  1774. html: `<div class="content">Content</div>`,
  1775. expected: "div.content => 30.000000",
  1776. setup: func(doc *goquery.Document) *candidate {
  1777. selection := doc.Find("div")
  1778. return scoreNode(selection)
  1779. },
  1780. },
  1781. {
  1782. name: "candidate with id only",
  1783. html: `<div id="main">Content</div>`,
  1784. expected: "div#main => 30.000000",
  1785. setup: func(doc *goquery.Document) *candidate {
  1786. selection := doc.Find("div")
  1787. return scoreNode(selection)
  1788. },
  1789. },
  1790. {
  1791. name: "candidate with both class and id",
  1792. html: `<div class="content" id="main">Content</div>`,
  1793. expected: "div#main.content => 55.000000",
  1794. setup: func(doc *goquery.Document) *candidate {
  1795. selection := doc.Find("div")
  1796. return scoreNode(selection)
  1797. },
  1798. },
  1799. {
  1800. name: "candidate with multiple classes",
  1801. html: `<div class="article main content">Content</div>`,
  1802. expected: "div.article main content => 30.000000",
  1803. setup: func(doc *goquery.Document) *candidate {
  1804. selection := doc.Find("div")
  1805. return scoreNode(selection)
  1806. },
  1807. },
  1808. {
  1809. name: "paragraph candidate with negative class",
  1810. html: `<p class="comment">Comment text</p>`,
  1811. expected: "p.comment => -25.000000",
  1812. setup: func(doc *goquery.Document) *candidate {
  1813. selection := doc.Find("p")
  1814. return scoreNode(selection)
  1815. },
  1816. },
  1817. {
  1818. name: "heading candidate with positive id",
  1819. html: `<h1 id="main">Heading</h1>`,
  1820. expected: "h1#main => 20.000000",
  1821. setup: func(doc *goquery.Document) *candidate {
  1822. selection := doc.Find("h1")
  1823. return scoreNode(selection)
  1824. },
  1825. },
  1826. {
  1827. name: "candidate with special characters in class",
  1828. html: `<div class="my-class_name">Content</div>`,
  1829. expected: "div.my-class_name => 5.000000",
  1830. setup: func(doc *goquery.Document) *candidate {
  1831. selection := doc.Find("div")
  1832. return scoreNode(selection)
  1833. },
  1834. },
  1835. {
  1836. name: "candidate with empty class attribute",
  1837. html: `<div class="">Content</div>`,
  1838. expected: "div => 5.000000",
  1839. setup: func(doc *goquery.Document) *candidate {
  1840. selection := doc.Find("div")
  1841. return scoreNode(selection)
  1842. },
  1843. },
  1844. {
  1845. name: "candidate with empty id attribute",
  1846. html: `<div id="">Content</div>`,
  1847. expected: "div => 5.000000",
  1848. setup: func(doc *goquery.Document) *candidate {
  1849. selection := doc.Find("div")
  1850. return scoreNode(selection)
  1851. },
  1852. },
  1853. {
  1854. name: "custom score candidate",
  1855. html: `<span>Content</span>`,
  1856. expected: "span => 42.500000",
  1857. setup: func(doc *goquery.Document) *candidate {
  1858. selection := doc.Find("span")
  1859. c := scoreNode(selection)
  1860. c.score = 42.5 // Override score for testing
  1861. return c
  1862. },
  1863. },
  1864. }
  1865. for _, tc := range testCases {
  1866. t.Run(tc.name, func(t *testing.T) {
  1867. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  1868. if err != nil {
  1869. t.Fatalf("Failed to parse HTML: %v", err)
  1870. }
  1871. candidate := tc.setup(doc)
  1872. result := candidate.String()
  1873. if result != tc.expected {
  1874. t.Errorf("Expected: %s, Got: %s", tc.expected, result)
  1875. }
  1876. })
  1877. }
  1878. }
  1879. func TestCandidateListString(t *testing.T) {
  1880. testCases := []struct {
  1881. name string
  1882. html string
  1883. expected string
  1884. setup func(*goquery.Document) candidateList
  1885. }{
  1886. {
  1887. name: "empty candidate list",
  1888. html: `<div></div>`,
  1889. expected: "",
  1890. setup: func(doc *goquery.Document) candidateList {
  1891. return make(candidateList)
  1892. },
  1893. },
  1894. {
  1895. name: "single candidate",
  1896. html: `<div class="content">Content</div>`,
  1897. expected: "div.content => 30.000000",
  1898. setup: func(doc *goquery.Document) candidateList {
  1899. candidates := make(candidateList)
  1900. selection := doc.Find("div")
  1901. candidate := scoreNode(selection)
  1902. candidates[selection.Get(0)] = candidate
  1903. return candidates
  1904. },
  1905. },
  1906. {
  1907. name: "multiple candidates",
  1908. html: `<div class="content">Content</div><p class="text">Paragraph</p><h1 id="main">Title</h1>`,
  1909. setup: func(doc *goquery.Document) candidateList {
  1910. candidates := make(candidateList)
  1911. divSelection := doc.Find("div")
  1912. divCandidate := scoreNode(divSelection)
  1913. candidates[divSelection.Get(0)] = divCandidate
  1914. pSelection := doc.Find("p")
  1915. pCandidate := scoreNode(pSelection)
  1916. candidates[pSelection.Get(0)] = pCandidate
  1917. h1Selection := doc.Find("h1")
  1918. h1Candidate := scoreNode(h1Selection)
  1919. candidates[h1Selection.Get(0)] = h1Candidate
  1920. return candidates
  1921. },
  1922. },
  1923. {
  1924. name: "candidates with mixed scores",
  1925. html: `<div class="comment">Comment</div><p class="content">Good content</p>`,
  1926. setup: func(doc *goquery.Document) candidateList {
  1927. candidates := make(candidateList)
  1928. divSelection := doc.Find("div")
  1929. divCandidate := scoreNode(divSelection)
  1930. candidates[divSelection.Get(0)] = divCandidate
  1931. pSelection := doc.Find("p")
  1932. pCandidate := scoreNode(pSelection)
  1933. candidates[pSelection.Get(0)] = pCandidate
  1934. return candidates
  1935. },
  1936. },
  1937. {
  1938. name: "candidate with empty selection",
  1939. html: `<div>Test</div>`,
  1940. setup: func(doc *goquery.Document) candidateList {
  1941. candidates := make(candidateList)
  1942. // Add a regular candidate
  1943. divSelection := doc.Find("div")
  1944. divCandidate := scoreNode(divSelection)
  1945. candidates[divSelection.Get(0)] = divCandidate
  1946. // Add a candidate with empty selection (this is artificial but tests the edge case)
  1947. emptySelection := doc.Find("nonexistent")
  1948. emptyCandidate := &candidate{selection: emptySelection, score: 0}
  1949. // We can't use emptySelection.Get(0) as key since it would panic,
  1950. // so we'll create a dummy node for this test
  1951. dummyNode := &html.Node{Type: html.ElementNode, Data: "dummy"}
  1952. candidates[dummyNode] = emptyCandidate
  1953. return candidates
  1954. },
  1955. },
  1956. }
  1957. for _, tc := range testCases {
  1958. t.Run(tc.name, func(t *testing.T) {
  1959. doc, err := goquery.NewDocumentFromReader(strings.NewReader(tc.html))
  1960. if err != nil {
  1961. t.Fatalf("Failed to parse HTML: %v", err)
  1962. }
  1963. candidates := tc.setup(doc)
  1964. result := candidates.String()
  1965. if tc.name == "empty candidate list" {
  1966. if result != tc.expected {
  1967. t.Errorf("Expected: %s, Got: %s", tc.expected, result)
  1968. }
  1969. return
  1970. }
  1971. // For multiple candidates, we need to check that all expected parts are present
  1972. // since map iteration order is not guaranteed
  1973. switch tc.name {
  1974. case "multiple candidates":
  1975. expectedParts := []string{"div.content => 30.000000", "p.text => 25.000000", "h1#main => 20.000000"}
  1976. for _, part := range expectedParts {
  1977. if !strings.Contains(result, part) {
  1978. t.Errorf("Expected result to contain: %s, Got: %s", part, result)
  1979. }
  1980. }
  1981. // Check that it's comma-separated
  1982. if !strings.Contains(result, ", ") {
  1983. t.Errorf("Expected comma-separated format, Got: %s", result)
  1984. }
  1985. case "candidates with mixed scores":
  1986. expectedParts := []string{"div.comment => -20.000000", "p.content => 25.000000"}
  1987. for _, part := range expectedParts {
  1988. if !strings.Contains(result, part) {
  1989. t.Errorf("Expected result to contain: %s, Got: %s", part, result)
  1990. }
  1991. }
  1992. case "candidate with empty selection":
  1993. // Should contain both the regular candidate and the empty one
  1994. if !strings.Contains(result, "div => 5.000000") {
  1995. t.Errorf("Expected result to contain div candidate, Got: %s", result)
  1996. }
  1997. if !strings.Contains(result, "empty => 0.000000") {
  1998. t.Errorf("Expected result to contain empty candidate, Got: %s", result)
  1999. }
  2000. default:
  2001. // Single candidate test cases
  2002. if result != tc.expected {
  2003. t.Errorf("Expected: %s, Got: %s", tc.expected, result)
  2004. }
  2005. }
  2006. })
  2007. }
  2008. }
  2009. func TestCandidateStringEdgeCases(t *testing.T) {
  2010. t.Run("candidate with nil node but valid selection", func(t *testing.T) {
  2011. // This tests the case where Node() returns nil but selection exists
  2012. html := `<div>Test</div>`
  2013. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  2014. if err != nil {
  2015. t.Fatal(err)
  2016. }
  2017. emptySelection := doc.Find("nonexistent")
  2018. candidate := &candidate{
  2019. selection: emptySelection,
  2020. score: 10.5,
  2021. }
  2022. result := candidate.String()
  2023. expected := "empty => 10.500000"
  2024. if result != expected {
  2025. t.Errorf("Expected: %s, Got: %s", expected, result)
  2026. }
  2027. })
  2028. t.Run("candidate with zero score", func(t *testing.T) {
  2029. html := `<div>Test</div>`
  2030. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  2031. if err != nil {
  2032. t.Fatal(err)
  2033. }
  2034. selection := doc.Find("div")
  2035. candidate := &candidate{
  2036. selection: selection,
  2037. score: 0,
  2038. }
  2039. result := candidate.String()
  2040. expected := "div => 0.000000"
  2041. if result != expected {
  2042. t.Errorf("Expected: %s, Got: %s", expected, result)
  2043. }
  2044. })
  2045. t.Run("candidate with negative score", func(t *testing.T) {
  2046. html := `<h1>Test</h1>`
  2047. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  2048. if err != nil {
  2049. t.Fatal(err)
  2050. }
  2051. selection := doc.Find("h1")
  2052. candidate := &candidate{
  2053. selection: selection,
  2054. score: -10.5,
  2055. }
  2056. result := candidate.String()
  2057. expected := "h1 => -10.500000"
  2058. if result != expected {
  2059. t.Errorf("Expected: %s, Got: %s", expected, result)
  2060. }
  2061. })
  2062. t.Run("candidate with very long class and id", func(t *testing.T) {
  2063. html := `<div class="very-long-class-name-that-might-cause-issues" id="very-long-id-name-that-might-also-cause-formatting-issues">Test</div>`
  2064. doc, err := goquery.NewDocumentFromReader(strings.NewReader(html))
  2065. if err != nil {
  2066. t.Fatal(err)
  2067. }
  2068. selection := doc.Find("div")
  2069. candidate := scoreNode(selection)
  2070. result := candidate.String()
  2071. expected := "div#very-long-id-name-that-might-also-cause-formatting-issues.very-long-class-name-that-might-cause-issues => 5.000000"
  2072. if result != expected {
  2073. t.Errorf("Expected: %s, Got: %s", expected, result)
  2074. }
  2075. })
  2076. }
  2077. func TestExtractContentWithBrokenReader(t *testing.T) {
  2078. if _, _, err := ExtractContent(&brokenReader{}); err == nil {
  2079. t.Error("Expected ExtractContent to return an error with broken reader")
  2080. }
  2081. }
  2082. // brokenReader implements io.Reader but always returns an error
  2083. type brokenReader struct{}
  2084. func (br *brokenReader) Read(p []byte) (n int, err error) {
  2085. return 0, errors.New("simulated read error")
  2086. }