-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdefuddle_test.go
More file actions
1112 lines (956 loc) · 36.2 KB
/
Copy pathdefuddle_test.go
File metadata and controls
1112 lines (956 loc) · 36.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package defuddle
import (
"context"
"strings"
"testing"
"github.com/dotcommander/defuddle/internal/scoring"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestNewDefuddle(t *testing.T) {
t.Parallel()
html := `<html><head><title>Test</title></head><body><h1>Hello World</h1><p>This is a test.</p></body></html>`
defuddle, err := NewDefuddle(html, nil)
require.NoError(t, err, "Failed to create Defuddle instance")
require.NotNil(t, defuddle, "Defuddle instance is nil")
}
func TestParse(t *testing.T) {
t.Parallel()
html := `<html><head><title>Test Article</title></head><body><h1>Hello World</h1><p>This is a test article with some content.</p></body></html>`
defuddle, err := NewDefuddle(html, nil)
require.NoError(t, err, "Failed to create Defuddle instance")
result, err := defuddle.Parse(context.Background())
require.NoError(t, err, "Failed to parse")
require.NotNil(t, result, "Result is nil")
assert.Equal(t, "Test Article", result.Title, "Expected title 'Test Article'")
assert.Greater(t, result.WordCount, 0, "Word count should be greater than 0")
t.Logf("Title: %s", result.Title)
t.Logf("Word count: %d", result.WordCount)
t.Logf("Parse time: %d ms", result.ParseTime)
}
func TestParseWithMetadata(t *testing.T) {
t.Parallel()
html := `<html>
<head>
<title>Advanced Test Article - Test Site</title>
<meta name="description" content="This is a comprehensive test article">
<meta name="author" content="John Doe">
<meta property="og:title" content="Advanced Test Article">
<meta property="og:description" content="OpenGraph description">
<meta property="og:image" content="https://example.com/image.jpg">
</head>
<body>
<header>Site Header</header>
<nav>Navigation menu</nav>
<article>
<h1>Advanced Test Article</h1>
<p class="author">By John Doe</p>
<p>This is the main content of the article with multiple paragraphs.</p>
<p>Here is another paragraph with more detailed content to test the word counting feature.</p>
</article>
<aside class="sidebar">Sidebar content</aside>
<footer>Site footer</footer>
</body>
</html>`
defuddle, err := NewDefuddle(html, nil)
require.NoError(t, err, "Failed to create Defuddle instance")
result, err := defuddle.Parse(context.Background())
require.NoError(t, err, "Failed to parse")
// Test title extraction and cleaning
assert.Equal(t, "Advanced Test Article", result.Title, "Expected cleaned title 'Advanced Test Article'")
// Test description extraction
assert.Equal(t, "This is a comprehensive test article", result.Description, "Expected description 'This is a comprehensive test article'")
// Test author extraction
assert.Equal(t, "John Doe", result.Author, "Expected author 'John Doe'")
// Test image extraction
assert.Equal(t, "https://example.com/image.jpg", result.Image, "Expected image 'https://example.com/image.jpg'")
// Test meta tags collection
assert.NotEmpty(t, result.MetaTags, "Expected meta tags to be collected")
// Test word count
assert.Greater(t, result.WordCount, 10, "Expected word count > 10")
t.Logf("Title: %s", result.Title)
t.Logf("Description: %s", result.Description)
t.Logf("Author: %s", result.Author)
t.Logf("Image: %s", result.Image)
t.Logf("Word count: %d", result.WordCount)
t.Logf("Meta tags: %d", len(result.MetaTags))
}
func TestContentExtraction(t *testing.T) {
t.Parallel()
html := `<html>
<head><title>Content Test</title></head>
<body>
<div class="ad">Advertisement content</div>
<header>Site header</header>
<nav>Navigation</nav>
<main>
<article>
<h1>Main Article</h1>
<p>This is the main content that should be extracted.</p>
<p>Multiple paragraphs of valuable content.</p>
</article>
</main>
<aside class="sidebar">Sidebar</aside>
<div class="comments">Comments section</div>
<footer>Footer</footer>
</body>
</html>`
defuddle, err := NewDefuddle(html, nil)
require.NoError(t, err, "Failed to create Defuddle instance")
result, err := defuddle.Parse(context.Background())
require.NoError(t, err, "Failed to parse")
// The content should contain the main article
assert.Contains(t, result.Content, "Main Article", "Expected content to contain 'Main Article'")
assert.Contains(t, result.Content, "main content that should be extracted", "Expected content to contain main article text")
// Test that clutter removal worked (these might be removed by selectors)
t.Logf("Content length: %d characters", len(result.Content))
t.Logf("Word count: %d", result.WordCount)
}
func TestSelectorRemoval(t *testing.T) {
t.Parallel()
html := `<html>
<head><title>Selector Test</title></head>
<body>
<div class="advertisement">Ad content</div>
<div id="navigation">Nav content</div>
<div class="post-meta">Meta info</div>
<article>
<h1>Clean Article</h1>
<p>This content should remain after selector removal.</p>
</article>
<div class="comments">Comments</div>
<footer>Footer</footer>
</body>
</html>`
// Test with selector removal enabled (default)
defuddle, err := NewDefuddle(html, nil)
require.NoError(t, err, "Failed to create Defuddle instance")
result, err := defuddle.Parse(context.Background())
require.NoError(t, err, "Failed to parse")
// Main content should be preserved
assert.Contains(t, result.Content, "Clean Article", "Expected main content to be preserved")
t.Logf("Content after selector removal: %s", result.Content)
}
func TestCountWords(t *testing.T) {
t.Parallel()
html := `<html><body><p>This is a test with five words.</p></body></html>`
defuddle, err := NewDefuddle(html, nil)
require.NoError(t, err, "Failed to create Defuddle instance")
count := defuddle.countWords("<p>This is a test with five words.</p>")
assert.Equal(t, 7, count, "Expected word count 7")
}
func TestRetryLogic(t *testing.T) {
t.Parallel()
// HTML with very little content to trigger retry logic
html := `<html>
<head><title>Short Article</title></head>
<body>
<div class="ad">Large advertisement content that might be removed</div>
<div class="navigation">Navigation with many links</div>
<article>
<h1>Short</h1>
<p>Brief.</p>
</article>
</body>
</html>`
defuddle, err := NewDefuddle(html, nil)
require.NoError(t, err, "Failed to create Defuddle instance")
result, err := defuddle.Parse(context.Background())
require.NoError(t, err, "Failed to parse")
// Should have some content even if word count is low
assert.Greater(t, result.WordCount, 0, "Expected some word count even for short content")
t.Logf("Short content word count: %d", result.WordCount)
}
func TestAdvancedAlgorithms(t *testing.T) {
t.Parallel()
html := `<html>
<head>
<title>Advanced Algorithm Test</title>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Article",
"headline": "Advanced Algorithm Test",
"author": {
"@type": "Person",
"name": "Jane Smith"
},
"datePublished": "2024-01-15",
"description": "Testing advanced algorithms"
}
</script>
</head>
<body>
<!-- HTML comments should be removed -->
<div style="display: none;">Hidden content</div>
<img src="small.jpg" width="20" height="20" alt="Small image">
<img src="large.jpg" width="400" height="300" alt="Large image">
<article>
<h1>Advanced Algorithm Test</h1>
<h1>Another H1 that should become H2</h1>
<div role="paragraph">This should become a paragraph</div>
<div role="list">
<div role="listitem">
<span class="label">1)</span>
<div class="content">
<div role="paragraph">First item</div>
</div>
</div>
<div role="listitem">
<span class="label">2)</span>
<div class="content">
<div role="paragraph">Second item</div>
</div>
</div>
</div>
<p>Main content with <a id="fnref1" href="#fn1">1</a>.</p>
<div class="footnotes"><ol>
<li id="fn1"><p>The footnote definition text.</p></li>
</ol></div>
<div class="wrapper-div">
<p>Content inside wrapper div</p>
</div>
<br><br><br><!-- Excessive breaks -->
<p></p><!-- Empty paragraph -->
<h3>Trailing heading</h3>
</article>
</body>
</html>`
defuddle, err := NewDefuddle(html, &Options{
Debug: true,
ProcessCode: true,
ProcessImages: true,
ProcessHeadings: true,
ProcessMath: true,
ProcessFootnotes: true,
ProcessRoles: true,
})
require.NoError(t, err, "Failed to create Defuddle instance")
result, err := defuddle.Parse(context.Background())
require.NoError(t, err, "Failed to parse")
// Test schema.org data extraction
assert.NotNil(t, result.SchemaOrgData, "Expected schema.org data to be extracted")
// Test title extraction from schema.org
assert.Equal(t, "Advanced Algorithm Test", result.Title, "Expected title 'Advanced Algorithm Test'")
// Test that H1 matching title was removed and other H1 became H2
assert.NotContains(t, result.Content, "<h1>Advanced Algorithm Test</h1>", "Expected first H1 matching title to be removed")
assert.Contains(t, result.Content, "<h2>Another H1 that should become H2</h2>", "Expected second H1 to be converted to H2")
// Test role-based element conversion
assert.Contains(t, result.Content, "<p>This should become a paragraph</p>", "Expected div with paragraph role to be converted to p tag")
// Test list conversion
assert.Contains(t, result.Content, "<ol>", "Expected ordered list to be created from role-based markup")
// Test that small images are removed (this might not work perfectly in test due to simplified implementation)
// The large image should remain
if !strings.Contains(result.Content, "large.jpg") {
t.Log("Note: Large image was removed - this is expected in simplified test environment")
}
// Test footnote standardization: inline ref becomes <sup id="fnref:N">
// and definition list is rebuilt as <div id="footnotes"><ol>
assert.Contains(t, result.Content, `id="fnref:`, "Expected standardized inline footnote reference with fnref: id")
assert.Contains(t, result.Content, `id="footnotes"`, "Expected standardized footnote definition list with id=footnotes")
// Trailing heading removal: when a footnotes section is appended after the heading,
// the heading is no longer at the trailing position, so it is preserved.
// This matches the TypeScript behavior where standardizeFootnotes runs before
// removeTrailingHeadings, so headings followed only by the footnotes section are kept.
// The test verifies the footnotes section is present (already asserted above).
// Test word count
assert.Greater(t, result.WordCount, 0, "Expected non-zero word count")
t.Logf("Advanced test - Title: %s", result.Title)
t.Logf("Advanced test - Word count: %d", result.WordCount)
contentPreview := result.Content
if len(contentPreview) > 200 {
contentPreview = contentPreview[:200]
}
t.Logf("Advanced test - Content preview: %s", contentPreview)
}
func TestContentScorer(t *testing.T) {
t.Parallel()
html := `
<html>
<body>
<div class="content">
<h1>Test Article</h1>
<p>This is a test paragraph with some content.</p>
<p>Another paragraph with more content.</p>
</div>
<div class="sidebar">
<a href="#">Link 1</a>
<a href="#">Link 2</a>
<a href="#">Link 3</a>
</div>
</body>
</html>`
defuddle, err := NewDefuddle(html, nil)
require.NoError(t, err, "Failed to create Defuddle instance")
// Test ScoreElement function
contentDiv := defuddle.doc.Find(".content").First()
require.Equal(t, 1, contentDiv.Length(), "Content div not found")
score := scoring.ScoreElement(contentDiv)
assert.Greater(t, score, 0.0, "Content div should have positive score")
// Test sidebar scoring (should be lower)
sidebarDiv := defuddle.doc.Find(".sidebar").First()
require.Equal(t, 1, sidebarDiv.Length(), "Sidebar div not found")
sidebarScore := scoring.ScoreElement(sidebarDiv)
assert.Greater(t, score, sidebarScore, "Content should score higher than sidebar")
}
func TestAdvancedElementProcessing(t *testing.T) {
t.Parallel()
html := `
<!DOCTYPE html>
<html>
<head>
<title>Advanced Element Processing Test</title>
</head>
<body>
<article>
<h1>Advanced Element Processing Test</h1>
<div role="paragraph">This should become a paragraph element.</div>
<pre><code class="language-javascript">
function hello() {
console.log("Hello, World!");
}
</code></pre>
<div role="list">
<div role="listitem">First item</div>
<div role="listitem">Second item</div>
</div>
<img src="test.jpg" alt="Test image" width="100" height="100">
<p>This is a regular paragraph with <sup><a href="#fn1">1</a></sup> footnote.</p>
<div id="footnotes">
<p id="fn1">1. This is a footnote.</p>
</div>
</article>
</body>
</html>
`
options := &Options{
ProcessCode: true,
ProcessImages: true,
ProcessHeadings: true,
ProcessFootnotes: true,
ProcessRoles: true,
Markdown: true,
}
defuddle, err := NewDefuddle(html, options)
if err != nil {
t.Fatalf("Failed to create Defuddle instance: %v", err)
}
result, err := defuddle.Parse(context.Background())
if err != nil {
t.Fatalf("Failed to parse content: %v", err)
}
// Check that content was extracted
if result.Content == "" {
t.Error("Expected content to be extracted")
}
// Check that Markdown was generated
if result.ContentMarkdown == nil {
t.Error("Expected Markdown content to be generated")
} else {
t.Logf("Markdown content: %s", *result.ContentMarkdown)
}
// Check that roles were processed (div[role="paragraph"] -> p)
if !strings.Contains(result.Content, "<p>This should become a paragraph element.</p>") {
t.Error("Expected role='paragraph' div to be converted to <p> tag")
}
// Check that code blocks were processed
if !strings.Contains(result.Content, "language-javascript") {
t.Error("Expected code block language to be preserved")
}
t.Logf("Advanced processing - Title: %s", result.Title)
t.Logf("Advanced processing - Word count: %d", result.WordCount)
t.Logf("Advanced processing - Content preview: %s", result.Content[:min(len(result.Content), 300)])
}
func TestDefaultOptions(t *testing.T) {
t.Parallel()
tests := []struct {
name string
instanceOptions *Options
overrideOptions *Options
expectedExact bool
expectedPartial bool
expectedDebug bool
expectedURL string
}{
{
name: "Nil options should get defaults",
instanceOptions: nil,
overrideOptions: nil,
expectedExact: true, // Default
expectedPartial: true, // Default
expectedDebug: false, // Zero value
expectedURL: "", // Zero value
},
{
name: "Empty options should get defaults",
instanceOptions: &Options{},
overrideOptions: nil,
expectedExact: true, // nil *bool → default true
expectedPartial: true, // nil *bool → default true
expectedDebug: false, // Zero value
expectedURL: "", // Zero value
},
{
name: "Instance options should override defaults",
instanceOptions: &Options{
RemoveExactSelectors: PtrBool(false),
RemovePartialSelectors: PtrBool(false),
Debug: true,
URL: "https://example.com",
},
overrideOptions: nil,
expectedExact: false, // Explicitly set false
expectedPartial: false, // Explicitly set false
expectedDebug: true, // From instance
expectedURL: "https://example.com", // From instance
},
{
name: "Override options should take precedence",
instanceOptions: &Options{
RemoveExactSelectors: PtrBool(false),
RemovePartialSelectors: PtrBool(false),
Debug: true,
URL: "https://instance.com",
},
overrideOptions: &Options{
RemoveExactSelectors: PtrBool(true),
RemovePartialSelectors: PtrBool(true),
URL: "https://override.com",
},
expectedExact: true, // From override
expectedPartial: true, // From override
expectedDebug: false, // From override (zero value in Go is false)
expectedURL: "https://override.com", // From override
},
{
name: "Partial override preserves unset fields (TypeScript parity)",
instanceOptions: &Options{
RemoveExactSelectors: PtrBool(false),
RemovePartialSelectors: PtrBool(false),
Debug: true,
URL: "https://instance.com",
},
overrideOptions: &Options{
RemovePartialSelectors: PtrBool(false), // Only override one boolean
},
expectedExact: false, // From instance (override nil = not set)
expectedPartial: false, // From override
expectedDebug: false, // From override (zero value in Go overwrites)
expectedURL: "https://instance.com", // From instance (empty string doesn't overwrite)
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
t.Parallel()
// Create a Defuddle instance with instance options
defuddle := &Defuddle{
options: tt.instanceOptions,
}
// Merge options (this is what happens in parseInternal)
merged := defuddle.mergeOptions(tt.overrideOptions)
// Verify results
if BoolDefault(merged.RemoveExactSelectors, true) != tt.expectedExact {
t.Errorf("RemoveExactSelectors: expected %v, got %v",
tt.expectedExact, BoolDefault(merged.RemoveExactSelectors, true))
}
if BoolDefault(merged.RemovePartialSelectors, true) != tt.expectedPartial {
t.Errorf("RemovePartialSelectors: expected %v, got %v",
tt.expectedPartial, BoolDefault(merged.RemovePartialSelectors, true))
}
if merged.Debug != tt.expectedDebug {
t.Errorf("Debug: expected %v, got %v",
tt.expectedDebug, merged.Debug)
}
if merged.URL != tt.expectedURL {
t.Errorf("URL: expected %q, got %q",
tt.expectedURL, merged.URL)
}
})
}
}
func TestTypescriptCompatibility(t *testing.T) {
t.Parallel()
// Test the exact scenario from TypeScript version:
// const options = {
// removeExactSelectors: true,
// removePartialSelectors: true,
// ...this.options,
// ...overrideOptions
// };
// In TS, overrideOptions = { removePartialSelectors: false } does NOT
// overwrite removeExactSelectors because it was never set in the spread.
// Go now matches this via *bool pointers — nil means "not set".
defuddle := &Defuddle{
options: &Options{
RemoveExactSelectors: PtrBool(true),
RemovePartialSelectors: PtrBool(true),
Debug: true,
},
}
// Retry scenario: only disable partial selectors
retryOptions := &Options{
RemovePartialSelectors: PtrBool(false),
}
merged := defuddle.mergeOptions(retryOptions)
// RemoveExactSelectors: true from instance, nil in override → preserved
if BoolDefault(merged.RemoveExactSelectors, true) != true {
t.Errorf("Expected RemoveExactSelectors=true (from instance, override nil), got %v",
BoolDefault(merged.RemoveExactSelectors, true))
}
// RemovePartialSelectors: explicitly false from override
if BoolDefault(merged.RemovePartialSelectors, true) != false {
t.Errorf("Expected RemovePartialSelectors=false (from override), got %v",
BoolDefault(merged.RemovePartialSelectors, true))
}
// Debug is plain bool — override zero value overwrites
if merged.Debug != false {
t.Errorf("Expected Debug=false (from override zero value), got %v",
merged.Debug)
}
}
func TestNewDefuddleDefaults(t *testing.T) {
t.Parallel()
html := "<html><body><h1>Test</h1></body></html>"
// Test with nil options
defuddle1, err := NewDefuddle(html, nil)
if err != nil {
t.Fatalf("Failed to create Defuddle with nil options: %v", err)
}
if defuddle1.options != nil {
t.Errorf("Expected nil options to remain nil, got %+v", defuddle1.options)
}
if defuddle1.debug != false {
t.Errorf("Expected debug=false with nil options, got %v", defuddle1.debug)
}
// Test with empty options
defuddle2, err := NewDefuddle(html, &Options{})
if err != nil {
t.Fatalf("Failed to create Defuddle with empty options: %v", err)
}
if defuddle2.debug != false {
t.Errorf("Expected debug=false with empty options, got %v", defuddle2.debug)
}
// Test with debug option
defuddle3, err := NewDefuddle(html, &Options{Debug: true})
if err != nil {
t.Fatalf("Failed to create Defuddle with debug options: %v", err)
}
if defuddle3.debug != true {
t.Errorf("Expected debug=true, got %v", defuddle3.debug)
}
}
func TestSchemaOrgImprovement(t *testing.T) {
t.Parallel()
// Test the improved schema.org processing with json-gold
html := `
<!DOCTYPE html>
<html>
<head>
<title>Schema.org Test</title>
<script type="application/ld+json">
{
"@context": "https://schema.org",
"@type": "Article",
"headline": "Test Article with JSON-LD",
"author": {
"@type": "Person",
"name": "Jane Doe"
},
"datePublished": "2024-01-15T10:00:00Z",
"description": "Testing improved schema.org processing"
}
</script>
</head>
<body>
<article>
<h1>Test Article with JSON-LD</h1>
<p>This article tests our improved schema.org processing with json-gold library.</p>
</article>
</body>
</html>
`
defuddle, err := NewDefuddle(html, &Options{Debug: true})
if err != nil {
t.Fatalf("Failed to create Defuddle instance: %v", err)
}
result, err := defuddle.Parse(context.Background())
if err != nil {
t.Fatalf("Failed to parse content: %v", err)
}
// Check that schema.org data was extracted and processed
if result.SchemaOrgData == nil {
t.Error("Expected schema.org data to be extracted")
}
// Verify title extraction
assert.Equal(t, "Test Article with JSON-LD", result.Title, "Expected title to be extracted from schema.org")
// Log the processed schema data structure
t.Logf("Schema.org data extracted: %+v", result.SchemaOrgData)
}
func TestRemoveImages(t *testing.T) {
t.Parallel()
html := `<html>
<head><title>Test Article</title></head>
<body>
<h1>Test Article</h1>
<p>This is some text content.</p>
<img src="test1.jpg" alt="Test image 1">
<p>More content.</p>
<svg><rect width="100" height="100"/></svg>
<p>Final content.</p>
<video src="test.mp4"></video>
<canvas width="200" height="100"></canvas>
<picture><img src="test2.jpg" alt="Test image 2"></picture>
</body>
</html>`
t.Run("removeImages=false should keep images", func(t *testing.T) {
t.Parallel()
defuddleInstance, err := NewDefuddle(html, &Options{
RemoveImages: false,
})
if err != nil {
t.Fatal(err)
}
result, err := defuddleInstance.Parse(context.Background())
if err != nil {
t.Fatal(err)
}
t.Logf("Content with images: %s", result.Content)
// Should contain images when removeImages is false
if !strings.Contains(result.Content, "<img") {
t.Error("Expected to find img tags when removeImages=false")
}
if !strings.Contains(result.Content, "<svg") {
t.Error("Expected to find svg tags when removeImages=false")
}
if !strings.Contains(result.Content, "<video") {
t.Error("Expected to find video tags when removeImages=false")
}
})
t.Run("removeImages=true should remove all images", func(t *testing.T) {
t.Parallel()
defuddleInstance, err := NewDefuddle(html, &Options{
RemoveImages: true,
})
if err != nil {
t.Fatal(err)
}
result, err := defuddleInstance.Parse(context.Background())
if err != nil {
t.Fatal(err)
}
t.Logf("Content without images: %s", result.Content)
// Should not contain images when removeImages is true
if strings.Contains(result.Content, "<img") {
t.Error("Found img tags when removeImages=true, they should be removed")
}
if strings.Contains(result.Content, "<svg") {
t.Error("Found svg tags when removeImages=true, they should be removed")
}
if strings.Contains(result.Content, "<video") {
t.Error("Found video tags when removeImages=true, they should be removed")
}
if strings.Contains(result.Content, "<canvas") {
t.Error("Found canvas tags when removeImages=true, they should be removed")
}
if strings.Contains(result.Content, "<picture") {
t.Error("Found picture tags when removeImages=true, they should be removed")
}
// Should still contain text content
if !strings.Contains(result.Content, "This is some text content") {
t.Error("Text content should be preserved when removeImages=true")
}
// Title is typically in result.Title, not in content body
if result.Title != "Test Article" {
t.Errorf("Expected title to be 'Test Article', got '%s'", result.Title)
}
})
}
func TestParseFromString(t *testing.T) {
t.Parallel()
html := `
<!DOCTYPE html>
<html>
<head>
<title>Test Page</title>
<meta name="description" content="This is a test page">
</head>
<body>
<h1>Main Heading</h1>
<p>This is the main content of the test page.</p>
<p>Another paragraph with more content.</p>
</body>
</html>
`
options := &Options{
Markdown: true,
URL: "https://example.com/test",
}
result, err := ParseFromString(context.Background(), html, options)
require.NoError(t, err, "ParseFromString failed")
// Check basic fields
assert.NotEmpty(t, result.Title, "Expected title to be extracted")
assert.NotEmpty(t, result.Content, "Expected content to be extracted")
require.NotNil(t, result.ContentMarkdown)
assert.NotEmpty(t, *result.ContentMarkdown, "Expected markdown content to be generated")
// Check that domain is extracted
assert.Equal(t, "example.com", result.Domain)
t.Logf("Title: %s", result.Title)
t.Logf("Content length: %d", len(result.Content))
t.Logf("Markdown length: %d", len(*result.ContentMarkdown))
}
func TestParseFromStringWithoutOptions(t *testing.T) {
t.Parallel()
html := `<html><body><h1>Simple Test</h1><p>Content</p></body></html>`
result, err := ParseFromString(context.Background(), html, nil)
require.NoError(t, err, "ParseFromString with nil options failed")
assert.NotEmpty(t, result.Content, "Expected content to be extracted even with nil options")
}
func TestParseIdempotent(t *testing.T) {
t.Parallel()
// Regression test: Parse() must produce identical results on repeated calls.
// Previously, parseInternal mutated d.doc (no clone), so the second call
// operated on a gutted document.
html := `<html>
<head><title>Idempotent Test</title></head>
<body>
<div style="display:none">Hidden element that gets removed</div>
<img src="tiny.png" width="10" height="10" alt="small">
<nav class="navigation">Nav links</nav>
<article>
<h1>Idempotent Test</h1>
<p>Main content paragraph one with enough words to be meaningful.</p>
<p>Second paragraph adds more content for the word count threshold.</p>
</article>
<footer>Site footer</footer>
</body>
</html>`
d, err := NewDefuddle(html, nil)
require.NoError(t, err)
result1, err := d.Parse(context.Background())
require.NoError(t, err)
result2, err := d.Parse(context.Background())
require.NoError(t, err)
assert.Equal(t, result1.Content, result2.Content, "Second Parse() must produce identical content")
assert.Equal(t, result1.WordCount, result2.WordCount, "Second Parse() must produce identical word count")
assert.Equal(t, result1.Title, result2.Title, "Second Parse() must produce identical title")
}
// --- Content selection tests ---
func TestFindMainContent_ArticleElement(t *testing.T) {
t.Parallel()
html := `<html><head><title>Test</title></head><body>
<nav>Navigation links here</nav>
<article>
<h2>Main Article</h2>
<p>This is the main content with enough words to be detected as meaningful content by the scoring algorithm.</p>
<p>Second paragraph adds more content for word count thresholds and ensures detection works.</p>
</article>
<aside>Sidebar content</aside>
</body></html>`
d, err := NewDefuddle(html, nil)
require.NoError(t, err)
result, err := d.Parse(context.Background())
require.NoError(t, err)
assert.Contains(t, result.Content, "Main Article")
assert.Contains(t, result.Content, "main content")
assert.NotContains(t, result.Content, "Navigation links")
}
func TestFindMainContent_ListingPageGuard(t *testing.T) {
t.Parallel()
// When a container has >= 3 article children, the listing-page guard
// prevents descending into one child. Verify all articles are present.
html := `<html><head><title>Blog</title></head><body>
<main>
<article>
<h2>Post One</h2>
<p>First blog post with enough content to pass word count thresholds and appear in final output for verification.</p>
<p>Adding extra paragraph to ensure sufficient word count for each individual article element in the listing.</p>
</article>
<article>
<h2>Post Two</h2>
<p>Second blog post with enough content to pass word count thresholds and appear in final output for verification.</p>
<p>Adding extra paragraph to ensure sufficient word count for each individual article element in the listing.</p>
</article>
<article>
<h2>Post Three</h2>
<p>Third blog post with enough content to pass word count thresholds and appear in final output for verification.</p>
<p>Adding extra paragraph to ensure sufficient word count for each individual article element in the listing.</p>
</article>
</main>
</body></html>`
d, err := NewDefuddle(html, nil)
require.NoError(t, err)
result, err := d.Parse(context.Background())
require.NoError(t, err)
// All three articles should be present (parent selected, not single child)
assert.Contains(t, result.Content, "Post One")
assert.Contains(t, result.Content, "Post Three")
}
func TestFindMainContent_ContentSelector(t *testing.T) {
t.Parallel()
html := `<html><head><title>Test</title></head><body>
<div id="noise"><p>This is noisy sidebar content that could confuse the scorer.</p></div>
<div id="target"><p>This is the actual target content selected by the user-specified CSS selector.</p></div>
</body></html>`
d, err := NewDefuddle(html, &Options{ContentSelector: "#target"})
require.NoError(t, err)
result, err := d.Parse(context.Background())
require.NoError(t, err)
assert.Contains(t, result.Content, "actual target content")
}
func TestFindMainContent_MainElement(t *testing.T) {
t.Parallel()
html := `<html><head><title>Test</title></head><body>
<header>Site Header</header>
<main>
<p>Primary content area with enough words to meet the scoring threshold for detection.</p>
<p>Additional paragraph ensures this block has sufficient text to be the winning candidate.</p>
</main>
<footer>Site Footer</footer>
</body></html>`
d, err := NewDefuddle(html, nil)
require.NoError(t, err)
result, err := d.Parse(context.Background())
require.NoError(t, err)
assert.Contains(t, result.Content, "Primary content area")
assert.NotContains(t, result.Content, "Site Header")
assert.NotContains(t, result.Content, "Site Footer")
}
func TestExtractorPath_SanitizesUnsafeHTML(t *testing.T) {
t.Parallel()
html := `<html><head>
<title>owner/repo issue</title>
<meta name="expected-hostname" content="github.com">
</head><body>
<div data-testid="issue-title">Issue title</div>
<div data-testid="issue-viewer-issue-container">
<a data-testid="issue-body-header-author" href="/attacker">attacker</a>
<relative-time datetime="2026-01-02T03:04:05Z"></relative-time>
<div data-testid="issue-body-viewer"><div class="markdown-body">
<p><img src="x" onerror="alert(1)"></p>
<a href="javascript:alert(2)">bad link</a>
<form><button formaction="data:application/pdf,evil">bad action</button></form>
<script>alert(3)</script><style>body{display:none}</style><noscript>unsafe fallback</noscript>
</div></div>
</div>
</body></html>`
d, err := NewDefuddle(html, &Options{URL: "https://github.com/owner/repo/issues/1"})
require.NoError(t, err)
result, err := d.Parse(context.Background())
require.NoError(t, err)
assert.NotContains(t, result.Content, "onerror")
assert.NotContains(t, result.Content, "javascript:alert")
assert.NotContains(t, result.Content, "formaction")
assert.NotContains(t, result.Content, "alert(3)")
assert.NotContains(t, result.Content, "display:none")
assert.NotContains(t, result.Content, "unsafe fallback")
assert.Contains(t, result.Content, "bad link")
}
func TestGenericPath_SanitizesSelectedRoot(t *testing.T) {
t.Parallel()
html := `<html><body><main id="content" onclick="evil()" href="java	script:evil()"><p>Safe article content.</p></main></body></html>`
d, err := NewDefuddle(html, &Options{ContentSelector: "#content"})
require.NoError(t, err)
result, err := d.Parse(context.Background())
require.NoError(t, err)
assert.Contains(t, result.Content, "Safe article content")
assert.NotContains(t, result.Content, "onclick")