readability_test.go 75 KB

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