llm_readability 0.0.17

Readability library for LLM's built in Rust
Documentation
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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
pub mod dom;
pub mod error;
pub mod extractor;
pub mod rcdom;
pub mod scorer;

#[cfg(all(test, feature = "tokio"))]
mod async_tests {
    use super::error::Error;
    use super::extractor;
    use std::io;
    use tokio::io::{AsyncRead, ReadBuf};

    /// Compile-time assertion that the async futures are `Send`. This is the
    /// whole point of depending on `spider-html5ever` / `spider-tendril`: the
    /// returned futures hold the parser across `.await` points, and the
    /// parser stack must be `Send` for `tokio::spawn` on a multi-threaded
    /// runtime to compile.
    #[test]
    fn async_futures_are_send() {
        fn assert_send<T: Send>(_: &T) {}

        let url = url::Url::parse("https://example.com/").unwrap();
        let bytes = b"<!doctype html><html><body><p>x</p></body></html>".to_vec();
        let fut = extractor::extract_async(bytes, url.clone());
        assert_send(&fut);

        // The reader future is `Send` whenever the reader itself is `Send`.
        // tokio::io::Empty is Send, so this composes.
        let reader = tokio::io::empty();
        let fut = extractor::extract_async_reader(reader, url);
        assert_send(&fut);
    }

    /// AsyncRead that yields a fixed payload one tiny chunk at a time.
    /// Exercises the streaming sink path under fragmented reads.
    struct ChunkedReader {
        data: Vec<u8>,
        pos: usize,
        chunk: usize,
    }

    impl AsyncRead for ChunkedReader {
        fn poll_read(
            mut self: std::pin::Pin<&mut Self>,
            _cx: &mut std::task::Context<'_>,
            buf: &mut ReadBuf<'_>,
        ) -> std::task::Poll<io::Result<()>> {
            let remaining = self.data.len() - self.pos;
            if remaining == 0 {
                return std::task::Poll::Ready(Ok(()));
            }
            let n = remaining.min(self.chunk).min(buf.remaining());
            let start = self.pos;
            buf.put_slice(&self.data[start..start + n]);
            self.pos += n;
            std::task::Poll::Ready(Ok(()))
        }
    }

    /// AsyncRead that errors on the second poll. Exercises the IO-error
    /// branch of the streaming loop.
    struct FlakyReader {
        data: Vec<u8>,
        pos: usize,
        first_poll: bool,
    }

    impl AsyncRead for FlakyReader {
        fn poll_read(
            mut self: std::pin::Pin<&mut Self>,
            _cx: &mut std::task::Context<'_>,
            buf: &mut ReadBuf<'_>,
        ) -> std::task::Poll<io::Result<()>> {
            if !self.first_poll {
                return std::task::Poll::Ready(Err(io::Error::new(io::ErrorKind::Other, "flaky")));
            }
            self.first_poll = false;
            let remaining = self.data.len() - self.pos;
            let n = remaining.min(buf.remaining());
            let start = self.pos;
            buf.put_slice(&self.data[start..start + n]);
            self.pos += n;
            std::task::Poll::Ready(Ok(()))
        }
    }

    fn small_html() -> String {
        r#"<!DOCTYPE html><html lang="en"><head><title>Tiny</title></head>
<body><article><h1>Tiny Heading</h1>
<p>First paragraph with sufficient prose for the readability scorer to consider it.</p>
<p>Second paragraph adds weight so this article wins as the top candidate.</p>
<p>Third paragraph for additional content scoring.</p>
</article></body></html>"#
            .to_string()
    }

    fn large_html() -> String {
        // Build a payload >> ASYNC_BYTE_THRESHOLD (128 KiB) to force the
        // streaming/spawn_blocking path.
        let mut out = String::from(
            r#"<!DOCTYPE html><html lang="en"><head><title>Big Article</title></head><body><article><h1>Big Heading</h1>"#,
        );
        for i in 0..2000 {
            out.push_str(&format!(
                "<p>Paragraph number {} with enough text to score, lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua.</p>",
                i
            ));
        }
        out.push_str("</article></body></html>");
        assert!(
            out.len() > extractor::ASYNC_BYTE_THRESHOLD,
            "fixture must exceed threshold"
        );
        out
    }

    #[tokio::test]
    async fn extract_async_small_inline() {
        let html = small_html();
        let url = url::Url::parse("https://example.com/").unwrap();
        let product = extractor::extract_async(html.into_bytes(), url)
            .await
            .unwrap();
        assert!(product.content.contains("Tiny Heading"));
        assert!(product.text.contains("First paragraph"));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn extract_async_large_offloaded() {
        let html = large_html();
        let url = url::Url::parse("https://example.com/").unwrap();
        let product = extractor::extract_async(html.into_bytes(), url)
            .await
            .unwrap();
        assert!(product.content.contains("Big Heading"));
        assert!(product.text.contains("Paragraph number 0"));
        assert!(product.text.contains("Paragraph number 1999"));
    }

    #[tokio::test]
    async fn extract_async_reader_small_inline() {
        let html = small_html();
        let url = url::Url::parse("https://example.com/").unwrap();
        let reader = ChunkedReader {
            data: html.into_bytes(),
            pos: 0,
            chunk: 1024,
        };
        let product = extractor::extract_async_reader(reader, url).await.unwrap();
        assert!(product.content.contains("Tiny Heading"));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn extract_async_reader_large_streaming() {
        let html = large_html();
        let url = url::Url::parse("https://example.com/").unwrap();
        // Tiny chunk size to stress the streaming sink and channel backpressure.
        let reader = ChunkedReader {
            data: html.into_bytes(),
            pos: 0,
            chunk: 4096,
        };
        let product = extractor::extract_async_reader(reader, url).await.unwrap();
        assert!(product.content.contains("Big Heading"));
        assert!(product.text.contains("Paragraph number 0"));
        assert!(product.text.contains("Paragraph number 1999"));
    }

    #[tokio::test(flavor = "multi_thread", worker_threads = 2)]
    async fn extract_async_reader_io_error_after_threshold() {
        // Payload larger than threshold so we cross into the streaming path,
        // then the reader errors on the next poll.
        let html = large_html();
        let url = url::Url::parse("https://example.com/").unwrap();
        let reader = FlakyReader {
            data: html.into_bytes(),
            pos: 0,
            first_poll: true,
        };
        let result = extractor::extract_async_reader(reader, url).await;
        // Either we read everything before the error (if the first poll
        // covered the whole body) or we surface the IO error. Both are
        // acceptable; the critical guarantee is that the future completes
        // — no hang, no panic.
        match result {
            Ok(_) => {}
            Err(Error::IOError(_)) => {}
            Err(Error::Unexpected) => {}
            Err(other) => panic!("unexpected error variant: {other}"),
        }
    }

    #[tokio::test]
    async fn extract_async_matches_sync_output() {
        let html = small_html();
        let url = url::Url::parse("https://example.com/").unwrap();
        let sync_product = extractor::extract(&mut html.as_bytes(), &url).unwrap();
        let async_product = extractor::extract_async(html.into_bytes(), url)
            .await
            .unwrap();
        assert_eq!(sync_product.content, async_product.content);
        assert_eq!(sync_product.text, async_product.text);
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_html_readability() {
        use maud::{html, DOCTYPE};

        let page_title = "Readability Test";
        let page_h1 = "Reading is fun";

        let markup = html! {
            (DOCTYPE)
            html lang="fr" {
                meta charset="utf-8";
                title { (page_title) }
                h1 { (page_h1) }
                a href="spider.cloud";
                pre {
                    r#"The content is ready for reading"#
                }
            }
        }
        .into_string();

        match extractor::extract(
            &mut markup.as_bytes(),
            &url::Url::parse("https://spider.cloud").unwrap(),
        ) {
            Ok(product) => {
                assert!(
                    product
                        .content
                        .contains(&format!("<title>{}</title>", page_title)),
                    "Title is missing or incorrect"
                );
                assert!(
                    product.content.contains(&format!("<h1>{page_h1}</h1>")),
                    "H1 tag is missing or incorrect"
                );
                assert!(
                    product.content.contains("The content is ready for reading"),
                    "Expected phrase is missing"
                );
                assert!(
                    product
                        .content
                        .contains(&r###"<html class="paper" lang="fr">"###),
                    "Html lang is missing or incorrect"
                );
            }
            Err(_) => println!("error occured"),
        }
    }

    #[test]
    fn test_extract_article_content() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Test Article</title></head>
<body>
    <header><nav>Navigation links here</nav></header>
    <article>
        <h1>Main Article Heading</h1>
        <p>This is the first paragraph of the main article content. It should be extracted.</p>
        <p>This is the second paragraph with more substantive content for the reader.</p>
        <p>A third paragraph adds weight to ensure this is identified as main content.</p>
    </article>
    <footer>Footer content</footer>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com/article").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.content.contains("Main Article Heading"));
        assert!(result.content.contains("first paragraph"));
        assert!(result.content.contains("second paragraph"));
        assert!(result.text.contains("Main Article Heading"));
    }

    #[test]
    fn test_extract_preserves_title() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>My Page Title</title></head>
<body>
    <article>
        <h1>Article Heading</h1>
        <p>Content paragraph one with enough text to be meaningful.</p>
        <p>Content paragraph two with additional text for scoring.</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.content.contains("<title>My Page Title</title>"));
    }

    #[test]
    fn test_extract_removes_scripts() {
        let html = r#"<!DOCTYPE html>
<html>
<head>
    <title>Page with Scripts</title>
    <script>alert('malicious');</script>
</head>
<body>
    <article>
        <h1>Clean Article</h1>
        <p>This content should be clean without any script tags.</p>
        <p>Another paragraph to add weight to the content block.</p>
        <script>console.log('inline script');</script>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        // Note: The library adds its own <script>window.isReaderPage = true;</script>
        // so we check for the malicious content being removed, not the absence of all scripts
        assert!(!result.content.contains("malicious"));
        assert!(!result.content.contains("inline script"));
        assert!(result.content.contains("Clean Article"));
    }

    #[test]
    fn test_extract_removes_styles() {
        let html = r#"<!DOCTYPE html>
<html>
<head>
    <title>Page with Styles</title>
    <style>.hidden { display: none; }</style>
</head>
<body>
    <article>
        <h1>Styled Article</h1>
        <p>Content without inline styles in the output.</p>
        <p>More content to ensure proper extraction.</p>
    </article>
    <style>body { color: red; }</style>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(!result.content.contains("<style>"));
        assert!(!result.content.contains("display: none"));
        assert!(result.content.contains("Styled Article"));
    }

    #[test]
    fn test_extract_handles_nested_divs() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Nested Divs</title></head>
<body>
    <div class="wrapper">
        <div class="container">
            <div class="content">
                <article>
                    <h1>Deeply Nested Content</h1>
                    <p>This paragraph is nested several levels deep in div elements.</p>
                    <p>Another paragraph to add content weight for scoring.</p>
                </article>
            </div>
        </div>
    </div>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.content.contains("Deeply Nested Content"));
        assert!(result.text.contains("nested several levels deep"));
    }

    #[test]
    fn test_extract_language_attribute() {
        let html = r#"<!DOCTYPE html>
<html lang="de">
<head><title>German Article</title></head>
<body>
    <article>
        <h1>Deutscher Artikel</h1>
        <p>Dies ist ein deutscher Artikel mit genug Text für die Extraktion.</p>
        <p>Ein weiterer Absatz um das Gewicht zu erhöhen.</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.de").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.content.contains(r#"lang="de""#));
    }

    #[test]
    fn test_extract_fixes_relative_image_urls() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Images</title></head>
<body>
    <article>
        <h1>Article with Images</h1>
        <p>Here is an image: <img src="/images/photo.jpg" alt="Photo"></p>
        <p>More content to ensure this is identified as the main article.</p>
        <p>Additional text paragraph for scoring weight.</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com/articles/test").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result
            .content
            .contains("https://example.com/images/photo.jpg"));
    }

    #[test]
    fn test_extract_fixes_relative_anchor_urls() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Links</title></head>
<body>
    <article>
        <h1>Article with Links</h1>
        <p>Check out <a href="/other-article">this other article</a> for more info.</p>
        <p>More content to give this section enough weight to be extracted.</p>
        <p>Third paragraph for additional scoring weight in the algorithm.</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com/articles/test").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.content.contains("https://example.com/other-article"));
    }

    #[test]
    fn test_extract_handles_empty_content() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Empty Page</title></head>
<body></body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url);

        assert!(result.is_ok());
    }

    #[test]
    fn test_extract_removes_sidebar_content() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Page with Sidebar</title></head>
<body>
    <div class="sidebar">
        <p>Sidebar content that should be removed or deprioritized.</p>
    </div>
    <article class="main-content">
        <h1>Main Article</h1>
        <p>This is the main content that should be extracted and prioritized.</p>
        <p>Another paragraph to add weight to this content section.</p>
        <p>Third paragraph ensures this block scores higher than the sidebar.</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.content.contains("Main Article"));
        assert!(result.text.contains("main content"));
    }

    #[test]
    fn test_extract_removes_ad_content() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Page with Ads</title></head>
<body>
    <div class="ad-break">
        <p>Advertisement content</p>
    </div>
    <article>
        <h1>Article Without Ads</h1>
        <p>The main article content should be free of advertisements.</p>
        <p>More substantive content for the readability algorithm.</p>
        <p>Additional paragraph to ensure proper content scoring.</p>
    </article>
    <div class="sponsor">Sponsored content</div>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.content.contains("Article Without Ads"));
    }

    #[test]
    fn test_extract_handles_blockquotes() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Article with Quote</title></head>
<body>
    <article>
        <h1>Article Title</h1>
        <p>Introduction paragraph with some context.</p>
        <blockquote>
            <p>This is an important quote that should be preserved in the output.</p>
        </blockquote>
        <p>Conclusion paragraph wrapping up the article.</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.content.contains("blockquote"));
        assert!(result.text.contains("important quote"));
    }

    #[test]
    fn test_extract_handles_lists() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Article with Lists</title></head>
<body>
    <article>
        <h1>Article with Lists</h1>
        <p>Here are some key points about the topic:</p>
        <ul>
            <li>First important point</li>
            <li>Second important point</li>
            <li>Third important point</li>
        </ul>
        <p>And here is a numbered list of steps:</p>
        <ol>
            <li>Step one</li>
            <li>Step two</li>
            <li>Step three</li>
        </ol>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.text.contains("First important point"));
        assert!(result.text.contains("Step one"));
    }

    #[test]
    fn test_extract_preserves_headings_hierarchy() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Article with Headings</title></head>
<body>
    <article>
        <h1>Main Title</h1>
        <p>Introduction to the article with substantial content.</p>
        <h2>Section One</h2>
        <p>Content for section one with meaningful text.</p>
        <h2>Section Two</h2>
        <p>Content for section two with more information.</p>
        <h3>Subsection</h3>
        <p>Detailed content in the subsection area.</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.content.contains("<h1>Main Title</h1>"));
        assert!(result.content.contains("<h2>Section One</h2>"));
        assert!(result.content.contains("<h2>Section Two</h2>"));
    }

    #[test]
    fn test_extract_handles_preformatted_text() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Code Article</title></head>
<body>
    <article>
        <h1>Code Example</h1>
        <p>Here is a code example that demonstrates the concept:</p>
        <pre>
fn main() {
    println!("Hello, world!");
}
        </pre>
        <p>The code above shows a simple Rust program.</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.content.contains("<pre>"));
        assert!(result.text.contains("println!"));
    }

    #[test]
    fn test_extract_japanese_content() {
        let html = r#"<!DOCTYPE html>
<html lang="ja">
<head><title>日本語記事</title></head>
<body>
    <article>
        <h1>日本語の見出し</h1>
        <p>これは日本語で書かれた記事です。日本語の句読点(。、!?)を含みます。</p>
        <p>二番目の段落には、さらに多くの内容があります。</p>
        <p>三番目の段落は、コンテンツブロックに重みを加えます。</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.jp").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.content.contains("日本語の見出し"));
        assert!(result.content.contains(r#"lang="ja""#));
    }

    #[test]
    fn test_extract_chinese_content() {
        let html = r#"<!DOCTYPE html>
<html lang="zh">
<head><title>中文文章</title></head>
<body>
    <article>
        <h1>中文标题</h1>
        <p>这是一篇中文文章。它包含中文标点符号,如句号。和逗号,</p>
        <p>第二段包含更多的内容和信息。</p>
        <p>第三段增加了文章的权重。</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.cn").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.content.contains("中文标题"));
        assert!(result.content.contains(r#"lang="zh""#));
    }

    #[test]
    fn test_extract_removes_comments() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Page with Comments</title></head>
<body>
    <!-- This is an HTML comment that should be removed -->
    <article>
        <h1>Article Title</h1>
        <!-- Another comment inside the article -->
        <p>Main content paragraph that should be preserved.</p>
        <p>Second paragraph with more content for scoring.</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(!result.content.contains("<!--"));
        assert!(!result.content.contains("HTML comment"));
        assert!(result.content.contains("Article Title"));
    }

    #[test]
    fn test_extract_removes_noscript() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Page with Noscript</title></head>
<body>
    <noscript>
        <p>JavaScript is required for this page.</p>
    </noscript>
    <article>
        <h1>Main Article</h1>
        <p>Content that should be extracted normally.</p>
        <p>More content for the readability algorithm to process.</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(!result.content.contains("<noscript>"));
        assert!(!result.content.contains("JavaScript is required"));
        assert!(result.content.contains("Main Article"));
    }

    #[test]
    fn test_extract_base_url_in_output() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Test</title></head>
<body>
    <article>
        <h1>Test Article</h1>
        <p>Content for the article with enough text to be extracted.</p>
        <p>Additional content paragraph for scoring purposes.</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com/path/to/article").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result
            .content
            .contains(r#"<base href="https://example.com/path/to/article">"#));
    }

    #[test]
    fn test_extract_text_output() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Text Test</title></head>
<body>
    <article>
        <h1>Plain Text Test</h1>
        <p>This text should appear in the plain text output.</p>
        <p>So should this second paragraph of content.</p>
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.text.contains("Plain Text Test"));
        assert!(result.text.contains("should appear in the plain text"));
        assert!(!result.text.contains("<p>"));
        assert!(!result.text.contains("<h1>"));
    }

    #[test]
    fn test_extract_handles_malformed_html() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Malformed</title>
<body>
    <article>
        <h1>Unclosed Tags
        <p>Missing closing tags but still valid enough to parse.
        <p>Another paragraph without closing tag.
    </article>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url);

        assert!(result.is_ok());
    }

    #[test]
    fn test_extract_removes_footer() {
        let html = r#"<!DOCTYPE html>
<html>
<head><title>Page with Footer</title></head>
<body>
    <article>
        <h1>Main Article Content</h1>
        <p>This is the main article that should be extracted.</p>
        <p>More content to ensure proper extraction and scoring.</p>
        <p>Third paragraph for additional weight in the algorithm.</p>
    </article>
    <footer>
        <p>Copyright 2024 Example Inc. All rights reserved.</p>
        <nav>
            <a href="/privacy">Privacy</a>
            <a href="/terms">Terms</a>
        </nav>
    </footer>
</body>
</html>"#;

        let url = url::Url::parse("https://example.com").unwrap();
        let result = extractor::extract(&mut html.as_bytes(), &url).unwrap();

        assert!(result.content.contains("Main Article Content"));
        assert!(!result.content.contains("Copyright 2024"));
    }

    #[test]
    fn test_product_debug() {
        let product = extractor::Product {
            content: String::from("<html>test</html>"),
            text: String::from("test"),
        };

        let debug_str = format!("{:?}", product);
        assert!(debug_str.contains("Product"));
        assert!(debug_str.contains("content"));
        assert!(debug_str.contains("text"));
    }
}

#[cfg(test)]
mod dom_tests {
    use super::*;
    use crate::rcdom::RcDom;
    use html5ever::parse_document;
    use html5ever::tendril::TendrilSink;

    fn parse_html(html: &str) -> RcDom {
        parse_document(RcDom::default(), Default::default())
            .from_utf8()
            .read_from(&mut html.as_bytes())
            .unwrap()
    }

    fn find_element<'a>(
        handle: &'a crate::rcdom::Handle,
        tag: &str,
    ) -> Option<crate::rcdom::Handle> {
        if let Some(name) = dom::get_tag_name(handle) {
            if name == tag {
                return Some(handle.clone());
            }
        }
        for child in handle.children.borrow().iter() {
            if let Some(found) = find_element(child, tag) {
                return Some(found);
            }
        }
        None
    }

    #[test]
    fn test_get_tag_name() {
        let dom = parse_html("<html><body><div>test</div></body></html>");
        let div = find_element(&dom.document, "div").unwrap();
        assert_eq!(dom::get_tag_name(&div), Some("div".to_string()));
    }

    #[test]
    fn test_get_attr() {
        let dom =
            parse_html(r#"<html><body><div id="main" class="container">test</div></body></html>"#);
        let div = find_element(&dom.document, "div").unwrap();
        assert_eq!(dom::get_attr("id", &div), Some("main".to_string()));
        assert_eq!(dom::get_attr("class", &div), Some("container".to_string()));
        assert_eq!(dom::get_attr("nonexistent", &div), None);
    }

    #[test]
    fn test_extract_text() {
        let dom = parse_html("<html><body><p>Hello <strong>World</strong>!</p></body></html>");
        let p = find_element(&dom.document, "p").unwrap();
        let mut text = String::new();
        dom::extract_text(&p, &mut text, true);
        assert!(text.contains("Hello"));
        assert!(text.contains("World"));
    }

    #[test]
    fn test_extract_text_shallow() {
        let dom = parse_html("<html><body><p>Hello <strong>World</strong>!</p></body></html>");
        let p = find_element(&dom.document, "p").unwrap();
        let mut text = String::new();
        dom::extract_text(&p, &mut text, false);
        assert!(text.contains("Hello"));
        assert!(!text.contains("World"));
    }

    #[test]
    fn test_text_len() {
        let dom = parse_html("<html><body><p>Hello World</p></body></html>");
        let p = find_element(&dom.document, "p").unwrap();
        let len = dom::text_len(&p);
        assert_eq!(len, 11);
    }

    #[test]
    fn test_find_node() {
        let dom = parse_html(
            "<html><body><div><a href='#'>Link 1</a><a href='#'>Link 2</a></div></body></html>",
        );
        let div = find_element(&dom.document, "div").unwrap();
        let mut links = vec![];
        dom::find_node(&div, "a", &mut links);
        assert_eq!(links.len(), 2);
    }

    #[test]
    fn test_has_link() {
        let dom = parse_html("<html><body><p>No link here</p></body></html>");
        let p = find_element(&dom.document, "p").unwrap();
        assert!(!dom::has_link(&p));

        let dom2 = parse_html("<html><body><p><a href='#'>Link</a></p></body></html>");
        let p2 = find_element(&dom2.document, "p").unwrap();
        assert!(dom::has_link(&p2));
    }

    #[test]
    fn test_is_empty() {
        let dom = parse_html("<html><body><div></div></body></html>");
        let div = find_element(&dom.document, "div").unwrap();
        assert!(dom::is_empty(&div));

        let dom2 = parse_html("<html><body><div><p>Content</p></div></body></html>");
        let div2 = find_element(&dom2.document, "div").unwrap();
        assert!(!dom::is_empty(&div2));
    }

    #[test]
    fn test_has_nodes() {
        let dom = parse_html("<html><body><div><p>Para</p></div></body></html>");
        let div = find_element(&dom.document, "div").unwrap();
        assert!(dom::has_nodes(&div, &vec!["p"]));
        assert!(!dom::has_nodes(&div, &vec!["span"]));
    }

    #[test]
    fn test_text_children_count() {
        let dom = parse_html("<html><body><div>Short<p></p>This is a longer text node that exceeds twenty characters</div></body></html>");
        let div = find_element(&dom.document, "div").unwrap();
        let count = dom::text_children_count(&div);
        assert_eq!(count, 1);
    }
}

#[cfg(test)]
mod scorer_tests {
    use super::*;
    use crate::rcdom::RcDom;
    use html5ever::parse_document;
    use html5ever::tendril::TendrilSink;

    fn parse_html(html: &str) -> RcDom {
        parse_document(RcDom::default(), Default::default())
            .from_utf8()
            .read_from(&mut html.as_bytes())
            .unwrap()
    }

    fn find_element(handle: &crate::rcdom::Handle, tag: &str) -> Option<crate::rcdom::Handle> {
        if let Some(name) = dom::get_tag_name(handle) {
            if name == tag {
                return Some(handle.clone());
            }
        }
        for child in handle.children.borrow().iter() {
            if let Some(found) = find_element(child, tag) {
                return Some(found);
            }
        }
        None
    }

    #[test]
    fn test_is_candidate_paragraph() {
        let dom =
            parse_html("<html><body><p>This is enough text to be considered.</p></body></html>");
        let p = find_element(&dom.document, "p").unwrap();
        assert!(scorer::is_candidate(&p));
    }

    #[test]
    fn test_is_candidate_short_text() {
        let dom = parse_html("<html><body><p>Hi</p></body></html>");
        let p = find_element(&dom.document, "p").unwrap();
        assert!(!scorer::is_candidate(&p));
    }

    #[test]
    fn test_get_class_weight_positive() {
        let dom =
            parse_html(r#"<html><body><div class="article content">Test</div></body></html>"#);
        let div = find_element(&dom.document, "div").unwrap();
        let weight = scorer::get_class_weight(&div);
        assert!(weight > 0.0);
    }

    #[test]
    fn test_get_class_weight_negative() {
        let dom =
            parse_html(r#"<html><body><div class="sidebar comment">Test</div></body></html>"#);
        let div = find_element(&dom.document, "div").unwrap();
        let weight = scorer::get_class_weight(&div);
        assert!(weight < 0.0);
    }

    #[test]
    fn test_get_class_weight_neutral() {
        let dom = parse_html(r#"<html><body><div class="wrapper">Test</div></body></html>"#);
        let div = find_element(&dom.document, "div").unwrap();
        let weight = scorer::get_class_weight(&div);
        assert_eq!(weight, 0.0);
    }

    #[test]
    fn test_init_content_score_article() {
        let dom = parse_html("<html><body><article>Test content</article></body></html>");
        let article = find_element(&dom.document, "article").unwrap();
        let score = scorer::init_content_score(&article);
        assert!(score >= 10.0);
    }

    #[test]
    fn test_init_content_score_form() {
        let dom = parse_html("<html><body><form>Test content</form></body></html>");
        let form = find_element(&dom.document, "form").unwrap();
        let score = scorer::init_content_score(&form);
        assert!(score <= -3.0);
    }

    #[test]
    fn test_calc_content_score() {
        let dom = parse_html("<html><body><p>This is a sentence. Here is another one! And a question?</p></body></html>");
        let p = find_element(&dom.document, "p").unwrap();
        let score = scorer::calc_content_score(&p);
        assert!(score > 1.0);
    }

    #[test]
    fn test_get_link_density() {
        let dom = parse_html(
            "<html><body><div>Regular text <a href='#'>link</a> more text</div></body></html>",
        );
        let div = find_element(&dom.document, "div").unwrap();
        let density = scorer::get_link_density(&div);
        assert!(density > 0.0);
        assert!(density < 1.0);
    }

    #[test]
    fn test_get_link_density_no_links() {
        let dom = parse_html("<html><body><div>Regular text without any links</div></body></html>");
        let div = find_element(&dom.document, "div").unwrap();
        let density = scorer::get_link_density(&div);
        assert_eq!(density, 0.0);
    }

    #[test]
    fn test_get_link_density_all_links() {
        let dom = parse_html("<html><body><div><a href='#'>All link text</a></div></body></html>");
        let div = find_element(&dom.document, "div").unwrap();
        let density = scorer::get_link_density(&div);
        assert!((density - 1.0).abs() < 0.01);
    }

    #[test]
    fn test_local_url() {
        assert!(scorer::local_url("/path/to/resource"));
        assert!(scorer::local_url("relative/path"));
        assert!(!scorer::local_url("http://example.com"));
        assert!(!scorer::local_url("https://example.com"));
        assert!(!scorer::local_url("//example.com/path"));
    }

    #[test]
    fn test_fix_img_path() {
        let dom = parse_html(r#"<html><body><img src="/images/test.jpg"></body></html>"#);
        let img = find_element(&dom.document, "img").unwrap();
        let url = url::Url::parse("https://example.com/article").unwrap();

        let result = scorer::fix_img_path(&img, &url);
        assert!(result);

        let src = dom::get_attr("src", &img).unwrap();
        assert_eq!(src, "https://example.com/images/test.jpg");
    }

    #[test]
    fn test_fix_anchor_path() {
        let dom = parse_html(r#"<html><body><a href="/other-page">Link</a></body></html>"#);
        let a = find_element(&dom.document, "a").unwrap();
        let url = url::Url::parse("https://example.com/article").unwrap();

        let result = scorer::fix_anchor_path(&a, &url);
        assert!(result);

        let href = dom::get_attr("href", &a).unwrap();
        assert_eq!(href, "https://example.com/other-page");
    }

    #[test]
    fn test_preprocess_extracts_title() {
        let html = "<html><head><title>Page Title</title></head><body><p>Content</p></body></html>";
        let mut dom = parse_html(html);
        let mut title = String::new();
        let mut lang = String::new();
        let handle = dom.document.clone();

        scorer::preprocess(&mut dom, &handle, &mut title, &mut lang);

        assert_eq!(title, "Page Title");
    }

    #[test]
    fn test_preprocess_extracts_lang() {
        let html = r#"<html lang="es"><head><title>Title</title></head><body><p>Content</p></body></html>"#;
        let mut dom = parse_html(html);
        let mut title = String::new();
        let mut lang = String::new();
        let handle = dom.document.clone();

        scorer::preprocess(&mut dom, &handle, &mut title, &mut lang);

        assert_eq!(lang, "es");
    }

    #[test]
    fn test_is_candidate_div_with_block_children() {
        let dom =
            parse_html("<html><body><div><p>Some paragraph content here</p></div></body></html>");
        let div = find_element(&dom.document, "div").unwrap();
        assert!(scorer::is_candidate(&div));
    }

    #[test]
    fn test_is_candidate_div_without_block_children() {
        let dom = parse_html("<html><body><div>Just some text</div></body></html>");
        let div = find_element(&dom.document, "div").unwrap();
        assert!(!scorer::is_candidate(&div));
    }

    #[test]
    fn test_is_candidate_h1() {
        let dom = parse_html("<html><body><h1>Main Heading Title</h1></body></html>");
        let h1 = find_element(&dom.document, "h1").unwrap();
        assert!(scorer::is_candidate(&h1));
    }

    #[test]
    fn test_is_candidate_h2() {
        let dom = parse_html("<html><body><h2>Section Heading</h2></body></html>");
        let h2 = find_element(&dom.document, "h2").unwrap();
        assert!(scorer::is_candidate(&h2));
    }

    #[test]
    fn test_init_content_score_div() {
        let dom = parse_html("<html><body><div>Test</div></body></html>");
        let div = find_element(&dom.document, "div").unwrap();
        let score = scorer::init_content_score(&div);
        assert_eq!(score, 5.0);
    }

    #[test]
    fn test_init_content_score_blockquote() {
        let dom = parse_html("<html><body><blockquote>Quote</blockquote></body></html>");
        let bq = find_element(&dom.document, "blockquote").unwrap();
        let score = scorer::init_content_score(&bq);
        assert_eq!(score, 3.0);
    }

    #[test]
    fn test_init_content_score_th() {
        let dom = parse_html("<html><body><table><tr><th>Header</th></tr></table></body></html>");
        let th = find_element(&dom.document, "th").unwrap();
        let score = scorer::init_content_score(&th);
        assert_eq!(score, 5.0);
    }

    #[test]
    fn test_init_content_score_h1() {
        let dom = parse_html("<html><body><h1>Title</h1></body></html>");
        let h1 = find_element(&dom.document, "h1").unwrap();
        let score = scorer::init_content_score(&h1);
        assert_eq!(score, 10.0);
    }

    #[test]
    fn test_get_class_weight_with_id() {
        let dom = parse_html(r#"<html><body><div id="article">Test</div></body></html>"#);
        let div = find_element(&dom.document, "div").unwrap();
        let weight = scorer::get_class_weight(&div);
        assert!(weight > 0.0);
    }

    #[test]
    fn test_get_class_weight_negative_id() {
        let dom = parse_html(r#"<html><body><div id="sidebar">Test</div></body></html>"#);
        let div = find_element(&dom.document, "div").unwrap();
        let weight = scorer::get_class_weight(&div);
        assert!(weight < 0.0);
    }

    #[test]
    fn test_calc_content_score_japanese_punctuation() {
        let dom = parse_html(
            "<html><body><p>これは日本語です。テストです!質問ですか?</p></body></html>",
        );
        let p = find_element(&dom.document, "p").unwrap();
        let score = scorer::calc_content_score(&p);
        assert!(score > 1.0);
    }

    #[test]
    fn test_calc_content_score_chinese_punctuation() {
        let dom = parse_html("<html><body><p>这是中文。测试句子,有逗号!</p></body></html>");
        let p = find_element(&dom.document, "p").unwrap();
        let score = scorer::calc_content_score(&p);
        assert!(score > 1.0);
    }

    #[test]
    fn test_fix_img_path_absolute_url() {
        let dom =
            parse_html(r#"<html><body><img src="https://other.com/image.jpg"></body></html>"#);
        let img = find_element(&dom.document, "img").unwrap();
        let url = url::Url::parse("https://example.com/article").unwrap();

        let result = scorer::fix_img_path(&img, &url);
        assert!(result);

        let src = dom::get_attr("src", &img).unwrap();
        assert_eq!(src, "https://other.com/image.jpg");
    }

    #[test]
    fn test_fix_img_path_no_src() {
        let dom = parse_html(r#"<html><body><img alt="no src"></body></html>"#);
        let img = find_element(&dom.document, "img").unwrap();
        let url = url::Url::parse("https://example.com/article").unwrap();

        let result = scorer::fix_img_path(&img, &url);
        assert!(!result);
    }

    #[test]
    fn test_fix_anchor_path_absolute_url() {
        let dom =
            parse_html(r#"<html><body><a href="https://other.com/page">Link</a></body></html>"#);
        let a = find_element(&dom.document, "a").unwrap();
        let url = url::Url::parse("https://example.com/article").unwrap();

        let result = scorer::fix_anchor_path(&a, &url);
        assert!(result);

        let href = dom::get_attr("href", &a).unwrap();
        assert_eq!(href, "https://other.com/page");
    }

    #[test]
    fn test_fix_anchor_path_no_href() {
        let dom = parse_html(r#"<html><body><a name="anchor">Anchor</a></body></html>"#);
        let a = find_element(&dom.document, "a").unwrap();
        let url = url::Url::parse("https://example.com/article").unwrap();

        let result = scorer::fix_anchor_path(&a, &url);
        assert!(!result);
    }

    #[test]
    fn test_preprocess_removes_scripts() {
        let html =
            "<html><head><script>alert('test');</script></head><body><p>Content</p></body></html>";
        let mut dom = parse_html(html);
        let mut title = String::new();
        let mut lang = String::new();
        let handle = dom.document.clone();

        scorer::preprocess(&mut dom, &handle, &mut title, &mut lang);

        assert!(find_element(&dom.document, "script").is_none());
    }

    #[test]
    fn test_preprocess_removes_styles() {
        let html = "<html><head><style>.foo { color: red; }</style></head><body><p>Content</p></body></html>";
        let mut dom = parse_html(html);
        let mut title = String::new();
        let mut lang = String::new();
        let handle = dom.document.clone();

        scorer::preprocess(&mut dom, &handle, &mut title, &mut lang);

        assert!(find_element(&dom.document, "style").is_none());
    }

    #[test]
    fn test_preprocess_removes_links() {
        let html = r#"<html><head><link rel="stylesheet" href="style.css"></head><body><p>Content</p></body></html>"#;
        let mut dom = parse_html(html);
        let mut title = String::new();
        let mut lang = String::new();
        let handle = dom.document.clone();

        scorer::preprocess(&mut dom, &handle, &mut title, &mut lang);

        assert!(find_element(&dom.document, "link").is_none());
    }

    #[test]
    fn test_local_url_protocol_relative() {
        assert!(!scorer::local_url("//cdn.example.com/image.png"));
    }

    #[test]
    fn test_local_url_fragment() {
        assert!(scorer::local_url("#section"));
    }

    #[test]
    fn test_local_url_query_string() {
        assert!(scorer::local_url("page?query=value"));
    }
}

#[cfg(test)]
mod error_tests {
    use super::*;
    use std::io;

    #[test]
    fn test_error_display_url_parse() {
        let parse_err = url::Url::parse("not a url").unwrap_err();
        let err = error::Error::UrlParseError(parse_err);
        let display = format!("{}", err);
        assert!(display.contains("UrlParseError"));
    }

    #[test]
    fn test_error_display_unexpected() {
        let err = error::Error::Unexpected;
        let display = format!("{}", err);
        assert_eq!(display, "UnexpectedError");
    }

    #[test]
    fn test_error_display_io() {
        let io_err = io::Error::new(io::ErrorKind::NotFound, "file not found");
        let err = error::Error::IOError(io_err);
        let display = format!("{}", err);
        assert!(display.contains("InputOutputError"));
    }

    #[test]
    fn test_error_from_url_parse() {
        let parse_err = url::Url::parse(":::invalid").unwrap_err();
        let err: error::Error = parse_err.into();
        assert!(matches!(err, error::Error::UrlParseError(_)));
    }

    #[test]
    fn test_error_from_io() {
        let io_err = io::Error::new(io::ErrorKind::PermissionDenied, "access denied");
        let err: error::Error = io_err.into();
        assert!(matches!(err, error::Error::IOError(_)));
    }

    #[test]
    fn test_error_debug() {
        let err = error::Error::Unexpected;
        let debug = format!("{:?}", err);
        assert!(debug.contains("Unexpected"));
    }

    #[test]
    fn test_error_is_std_error() {
        use std::error::Error;
        let err = error::Error::Unexpected;
        let _: &dyn Error = &err;
    }
}

#[cfg(test)]
mod dom_attr_tests {
    use super::*;
    use crate::rcdom::RcDom;
    use html5ever::parse_document;
    use html5ever::tendril::TendrilSink;

    fn parse_html(html: &str) -> RcDom {
        parse_document(RcDom::default(), Default::default())
            .from_utf8()
            .read_from(&mut html.as_bytes())
            .unwrap()
    }

    fn find_element(handle: &crate::rcdom::Handle, tag: &str) -> Option<crate::rcdom::Handle> {
        if let Some(name) = dom::get_tag_name(handle) {
            if name == tag {
                return Some(handle.clone());
            }
        }
        for child in handle.children.borrow().iter() {
            if let Some(found) = find_element(child, tag) {
                return Some(found);
            }
        }
        None
    }

    #[test]
    fn test_set_attr() {
        let dom = parse_html(r#"<html><body><div id="test">Content</div></body></html>"#);
        let div = find_element(&dom.document, "div").unwrap();

        dom::set_attr("id", "new-id", &div);
        let id = dom::get_attr("id", &div).unwrap();
        assert_eq!(id, "new-id");
    }

    #[test]
    fn test_set_attr_nonexistent() {
        let dom = parse_html(r#"<html><body><div>Content</div></body></html>"#);
        let div = find_element(&dom.document, "div").unwrap();

        dom::set_attr("id", "new-id", &div);
        let id = dom::get_attr("id", &div);
        assert!(id.is_none());
    }

    #[test]
    fn test_clean_attr() {
        let dom = parse_html(r#"<html><body><div class="test-class">Content</div></body></html>"#);
        let div = find_element(&dom.document, "div").unwrap();

        if let crate::rcdom::NodeData::Element { ref attrs, .. } = div.data {
            let mut attrs_mut = attrs.borrow_mut();
            assert!(dom::attr("class", &attrs_mut).is_some());
            dom::clean_attr("class", &mut attrs_mut);
            assert!(dom::attr("class", &attrs_mut).is_none());
        }
    }

    #[test]
    fn test_clean_attr_nonexistent() {
        let dom = parse_html(r#"<html><body><div id="test-id">Content</div></body></html>"#);
        let div = find_element(&dom.document, "div").unwrap();

        if let crate::rcdom::NodeData::Element { ref attrs, .. } = div.data {
            let mut attrs_mut = attrs.borrow_mut();
            let initial_len = attrs_mut.len();
            dom::clean_attr("class", &mut attrs_mut);
            assert_eq!(attrs_mut.len(), initial_len);
        }
    }

    #[test]
    fn test_attr_function() {
        let dom = parse_html(
            r#"<html><body><div id="my-id" class="my-class">Content</div></body></html>"#,
        );
        let div = find_element(&dom.document, "div").unwrap();

        if let crate::rcdom::NodeData::Element { ref attrs, .. } = div.data {
            let attrs_ref = attrs.borrow();
            assert_eq!(dom::attr("id", &attrs_ref), Some("my-id".to_string()));
            assert_eq!(dom::attr("class", &attrs_ref), Some("my-class".to_string()));
            assert_eq!(dom::attr("style", &attrs_ref), None);
        }
    }

    #[test]
    fn test_get_tag_name_text_node() {
        let dom = parse_html("<html><body>Text content</body></html>");
        let body = find_element(&dom.document, "body").unwrap();
        for child in body.children.borrow().iter() {
            let tag_name = dom::get_tag_name(child);
            assert!(tag_name.is_none());
        }
    }

    #[test]
    fn test_is_empty_with_whitespace() {
        let dom = parse_html("<html><body><p>   </p></body></html>");
        let p = find_element(&dom.document, "p").unwrap();
        assert!(dom::is_empty(&p));
    }

    #[test]
    fn test_is_empty_with_nested_empty() {
        let dom = parse_html("<html><body><div><p></p></div></body></html>");
        let div = find_element(&dom.document, "div").unwrap();
        assert!(dom::is_empty(&div));
    }

    #[test]
    fn test_text_len_unicode() {
        let dom = parse_html("<html><body><p>日本語テスト</p></body></html>");
        let p = find_element(&dom.document, "p").unwrap();
        let len = dom::text_len(&p);
        assert_eq!(len, 6);
    }

    #[test]
    fn test_text_len_with_whitespace() {
        let dom = parse_html("<html><body><p>  hello world  </p></body></html>");
        let p = find_element(&dom.document, "p").unwrap();
        let len = dom::text_len(&p);
        assert_eq!(len, 11);
    }

    #[test]
    fn test_find_node_nested() {
        let dom =
            parse_html("<html><body><div><div><a href='#'>Link</a></div></div></body></html>");
        let body = find_element(&dom.document, "body").unwrap();
        let mut links = vec![];
        dom::find_node(&body, "a", &mut links);
        assert_eq!(links.len(), 1);
    }

    #[test]
    fn test_has_nodes_multiple_tags() {
        let dom = parse_html("<html><body><div><span>Text</span></div></body></html>");
        let div = find_element(&dom.document, "div").unwrap();
        assert!(dom::has_nodes(&div, &vec!["span", "p"]));
        assert!(!dom::has_nodes(&div, &vec!["p", "a"]));
    }

    #[test]
    fn test_extract_text_deep_nesting() {
        let dom =
            parse_html("<html><body><div><span><em>Deep</em> text</span></div></body></html>");
        let div = find_element(&dom.document, "div").unwrap();
        let mut text = String::new();
        dom::extract_text(&div, &mut text, true);
        assert!(text.contains("Deep"));
        assert!(text.contains("text"));
    }
}