webpage_quality_analyzer 1.0.2

High-performance webpage quality analyzer with 115 comprehensive metrics - Rust library with WASM, C++, and Python bindings
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
/// Comprehensive tests for Phase 1 - Enhanced Metric Registry
///
/// These tests validate the profile-aware metric system implementation

#[cfg(test)]
mod enhanced_metric_registry_tests {
    use crate::metrics::definitions::MetricScorer;
    use crate::metrics::{
        create_enhanced_scorer, get_all_metrics, MetricCategory, MetricRegistryOps, MetricValue,
        ProfileMetricConfig, ReadabilityScorer, ScoringFunction, ThresholdSet, WordCountScorer,
    };

    #[test]
    fn test_metric_registry_initialization() {
        // Test that the registry initializes with enhanced metrics
        let word_count_def = MetricRegistryOps::get_metric_definition("word_count");
        assert!(
            word_count_def.is_ok(),
            "word_count metric should be registered"
        );

        let definition = word_count_def.unwrap();
        assert_eq!(definition.field_name, "word_count");
        assert_eq!(definition.category, MetricCategory::Content);
        assert!(
            definition.profile_configurations.len() > 0,
            "Should have profile configurations"
        );
    }

    #[test]
    fn test_profile_specific_configurations() {
        // Test content_article profile has different config than product profile
        let content_config = MetricRegistryOps::get_profile_config("word_count", "content_article");
        let product_config = MetricRegistryOps::get_profile_config("word_count", "product");

        assert!(content_config.is_ok() && product_config.is_ok());

        let content_cfg = content_config.unwrap();
        let product_cfg = product_config.unwrap();

        // Content article should have higher thresholds and weight
        assert!(
            content_cfg.thresholds.excellent > product_cfg.thresholds.excellent,
            "Content articles should have higher word count thresholds"
        );
        assert!(
            content_cfg.weight > product_cfg.weight,
            "Content articles should have higher word count weight"
        );
        assert!(
            content_cfg.penalty_multiplier > product_cfg.penalty_multiplier,
            "Content articles should penalize low word count more heavily"
        );
    }

    #[test]
    fn test_profile_aware_scoring() {
        let word_count_scorer = WordCountScorer;

        // Test same word count gets different scores in different profiles
        let word_count = MetricValue::Usize(300);

        let content_config = ProfileMetricConfig {
            weight: 0.25,
            enabled: true,
            thresholds: ThresholdSet {
                excellent: 1500.0,
                good: 800.0,
                fair: 400.0,
                poor: 100.0,
            },
            penalty_multiplier: 2.5,
            bonus_conditions: Vec::new(),
            scoring_function_override: None,
        };

        let product_config = ProfileMetricConfig {
            weight: 0.08,
            enabled: true,
            thresholds: ThresholdSet {
                excellent: 300.0,
                good: 150.0,
                fair: 75.0,
                poor: 25.0,
            },
            penalty_multiplier: 0.8,
            bonus_conditions: Vec::new(),
            scoring_function_override: None,
        };

        let content_score = word_count_scorer.score_metric(word_count.clone(), &content_config);
        let product_score = word_count_scorer.score_metric(word_count, &product_config);

        // 300 words should score poorly for content but excellently for product
        assert!(product_score > content_score + 20.0,
            "Product profile should score 300 words much higher than content profile. Content: {}, Product: {}",
            content_score, product_score);
        assert!(
            product_score >= 90.0,
            "300 words should be excellent for product pages"
        );
        assert!(
            content_score <= 70.0,
            "300 words should be poor for content articles"
        );
    }

    #[test]
    fn test_readability_reverse_scoring() {
        let readability_scorer = ReadabilityScorer;
        let config = ProfileMetricConfig {
            weight: 0.20,
            enabled: true,
            thresholds: ThresholdSet {
                excellent: 8.0, // Lower FK = better readability
                good: 12.0,
                fair: 16.0,
                poor: 20.0,
            },
            penalty_multiplier: 1.5,
            bonus_conditions: Vec::new(),
            scoring_function_override: None,
        };

        // Lower FK scores should get higher ratings
        let excellent_readability =
            readability_scorer.score_metric(MetricValue::OptionF32(Some(6.0)), &config);
        let poor_readability =
            readability_scorer.score_metric(MetricValue::OptionF32(Some(25.0)), &config);

        assert!(
            excellent_readability > poor_readability + 50.0,
            "Lower FK scores should rate much higher. FK 6.0: {}, FK 25.0: {}",
            excellent_readability,
            poor_readability
        );
        assert!(excellent_readability >= 90.0, "FK 6.0 should be excellent");
        assert!(poor_readability <= 30.0, "FK 25.0 should be poor");
    }

    #[test]
    fn test_registry_operations() {
        // Test category-based metric retrieval
        let content_metrics =
            MetricRegistryOps::get_category_metrics(MetricCategory::Content, "content_article");
        assert!(
            !content_metrics.is_empty(),
            "Should have content metrics for content_article profile"
        );

        // Verify all metrics are from content category
        for (metric_def, _) in &content_metrics {
            assert_eq!(metric_def.category, MetricCategory::Content);
        }

        // Test profile metrics retrieval
        let profile_metrics = MetricRegistryOps::get_profile_metrics("content_article");
        assert!(
            profile_metrics.contains_key("word_count"),
            "Should include word_count for content_article"
        );
        assert!(
            profile_metrics.contains_key("readability_fk"),
            "Should include readability_fk for content_article"
        );
    }

    #[test]
    fn test_profile_availability() {
        let available_profiles = MetricRegistryOps::list_available_profiles();

        // Check that our enhanced profiles are available
        assert!(available_profiles.contains(&"content_article".to_string()));
        assert!(available_profiles.contains(&"news".to_string()));
        assert!(available_profiles.contains(&"product".to_string()));
        assert!(available_profiles.contains(&"portfolio".to_string()));

        // Should be sorted
        let mut sorted_profiles = available_profiles.clone();
        sorted_profiles.sort();
        assert_eq!(
            available_profiles, sorted_profiles,
            "Profiles should be sorted"
        );
    }

    #[test]
    fn test_registry_stats() {
        let stats = MetricRegistryOps::get_registry_stats();

        assert!(stats.total_metrics > 0, "Should have metrics registered");
        assert!(
            stats.configurable_metrics > 0,
            "Should have configurable metrics"
        );
        assert!(
            stats
                .metrics_by_category
                .contains_key(&MetricCategory::Content),
            "Should have content metrics"
        );
        assert!(
            stats
                .profiles_with_overrides
                .contains_key("content_article"),
            "Should track content_article overrides"
        );
    }

    #[test]
    fn test_metric_validation() {
        let word_count_scorer = WordCountScorer;
        let validation_rules = vec![crate::metrics::ValidationRule {
            rule_type: crate::metrics::ValidationRuleType::MinValue(0.0),
            error_message: "Word count cannot be negative",
        }];

        // Valid value should pass
        let valid_result =
            word_count_scorer.validate_metric_value(&MetricValue::Usize(100), &validation_rules);
        assert!(
            valid_result.is_ok(),
            "Valid word count should pass validation"
        );

        // This would fail in practice but our MetricValue::Usize can't be negative
        // The validation is more relevant for f32 values
        let zero_result =
            word_count_scorer.validate_metric_value(&MetricValue::Usize(0), &validation_rules);
        assert!(
            zero_result.is_ok(),
            "Zero word count should pass validation"
        );
    }

    #[test]
    fn test_bonus_conditions() {
        let word_count_scorer = WordCountScorer;
        let bonus_conditions = vec![crate::metrics::BonusCondition {
            condition_type: crate::metrics::BonusConditionType::ValueBetween {
                min: 1500.0,
                max: 3000.0,
            },
            bonus_points: 5.0,
            description: "Optimal content length".to_string(),
        }];

        let base_score = 85.0;

        // Word count in bonus range should get bonus
        let bonus_score = word_count_scorer.apply_bonuses(
            base_score,
            MetricValue::Usize(2000),
            &bonus_conditions,
        );
        assert_eq!(
            bonus_score, 90.0,
            "Should apply 5 point bonus for optimal length"
        );

        // Word count outside range should not get bonus
        let no_bonus_score =
            word_count_scorer.apply_bonuses(base_score, MetricValue::Usize(500), &bonus_conditions);
        assert_eq!(
            no_bonus_score, 85.0,
            "Should not apply bonus for non-optimal length"
        );
    }

    #[test]
    fn test_enhanced_scorer_factory() {
        // Test that factory creates appropriate scorers
        let word_count_scorer = create_enhanced_scorer(
            &ScoringFunction::Linear {
                min_value: 0.0,
                max_value: 3000.0,
                reverse_scoring: false,
            },
            "word_count",
        );

        let readability_scorer = create_enhanced_scorer(
            &ScoringFunction::CustomFunction {
                function_name: "readability_scorer".to_string(),
            },
            "readability_fk",
        );

        // Test that they produce reasonable scores
        let config = ProfileMetricConfig::default();

        let word_score = word_count_scorer.score_metric(MetricValue::Usize(1000), &config);
        let readability_score =
            readability_scorer.score_metric(MetricValue::OptionF32(Some(10.0)), &config);

        assert!(
            word_score > 0.0 && word_score <= 100.0,
            "Word count score should be in valid range"
        );
        assert!(
            readability_score > 0.0 && readability_score <= 100.0,
            "Readability score should be in valid range"
        );
    }

    #[test]
    fn test_profile_compilation() {
        // Test that metrics can be retrieved from the registry
        let all_metrics = get_all_metrics();

        // Check that word_count exists
        let word_count_metric = all_metrics.iter().find(|m| m.field_name == "word_count");
        assert!(word_count_metric.is_some(), "word_count should exist");

        if let Some(metric) = word_count_metric {
            assert_eq!(
                metric.category,
                MetricCategory::Content,
                "word_count should be in Content category"
            );
            assert!(
                metric.default_weight > 0.0,
                "word_count should have a positive default weight"
            );
        }
    }

    #[test]
    fn test_dramatic_score_differences() {
        // Test the core objective: different profiles should produce dramatically different scores
        let test_scenarios = vec![
            // (word_count, profile, expected_score_range)
            (50, "content_article", (0.0, 20.0)), // Severe penalty for low content
            (50, "product", (35.0, 55.0)),        // Moderate for product (between poor and fair)
            (1500, "content_article", (80.0, 100.0)), // Excellent for content
            (1500, "product", (85.0, 100.0)),      // Excellent for product too (way above threshold)
            (300, "news", (70.0, 95.0)),          // Good for news
            (300, "content_article", (45.0, 75.0)), // Fair for content
        ];

        let word_count_scorer = WordCountScorer;

        for (word_count, profile, (min_expected, max_expected)) in test_scenarios {
            let config = MetricRegistryOps::get_profile_config("word_count", profile).unwrap();
            let score = word_count_scorer.score_metric(MetricValue::Usize(word_count), &config);

            assert!(
                score >= min_expected && score <= max_expected,
                "Profile '{}' with {} words should score between {}-{}, got {}",
                profile,
                word_count,
                min_expected,
                max_expected,
                score
            );
        }
    }
}

/// Integration tests for the complete Phase 1 implementation
#[cfg(test)]
mod phase1_integration_tests {
    use super::*;
    use crate::metrics::*;

    #[test]
    fn test_complete_profile_metric_pipeline() {
        // Test the complete pipeline: Registry -> Profile Config -> Scorer -> Score

        // 1. Get metric definition from registry
        let metric_def = MetricRegistryOps::get_metric_definition("word_count").unwrap();
        assert_eq!(metric_def.field_name, "word_count");

        // 2. Get profile-specific configuration
        let content_config =
            MetricRegistryOps::get_profile_config("word_count", "content_article").unwrap();
        assert!(content_config.enabled);
        assert!(content_config.weight > 0.0);

        // 3. Create appropriate scorer
        let scorer = create_enhanced_scorer(&metric_def.scoring_function, "word_count");

        // 4. Score a metric value
        let test_value = MetricValue::Usize(800);
        let score = scorer.score_metric(test_value, &content_config);

        // 5. Verify reasonable score
        assert!(
            score >= 0.0 && score <= 100.0,
            "Score should be in valid range"
        );
        assert!(
            score > 50.0,
            "800 words should score reasonably well for content articles"
        );

        // 6. Compare with different profile
        let product_config =
            MetricRegistryOps::get_profile_config("word_count", "product").unwrap();
        let product_score = scorer.score_metric(MetricValue::Usize(800), &product_config);

        // Product profile should score 800 words differently (likely higher due to lower expectations)
        assert!(
            product_score != score,
            "Different profiles should produce different scores"
        );
    }

    #[test]
    fn test_registry_completeness() {
        // Verify that our enhanced registry has all the essential metrics
        let essential_metrics = vec![
            "word_count",
            "readability_fk",
            "main_text_ratio",
            "headings_count",
            "title_len",
            "images_count",
        ];

        for metric_name in essential_metrics {
            assert!(
                registry_utils::metric_exists(metric_name),
                "Essential metric '{}' should exist in registry",
                metric_name
            );
        }

        // Verify profile coverage
        let profiles = vec!["content_article", "news", "product", "portfolio"];
        for profile in profiles {
            let profile_metrics = MetricRegistryOps::get_profile_metrics(profile);
            assert!(
                !profile_metrics.is_empty(),
                "Profile '{}' should have metric configurations",
                profile
            );
        }
    }
}