Spaces:
Sleeping
Sleeping
Download tests/test_accuracy.py from faseehsandhu/Digitalytics: direct link, hf CLI and curl.
- Browser
- Download file 15 kB
-
https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/tests/test_accuracy.py
- Command line
-
hf download hf://spaces/faseehsandhu/Digitalytics/tests/test_accuracy.py
-
curl -L -o test_accuracy.py https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/tests/test_accuracy.py
15 kB
| """ | |
| test_accuracy.py | |
| Pytest tests for accuracy validation and reporting. | |
| Tests the accuracy validators and report generation. | |
| """ | |
| import pytest | |
| import json | |
| from pathlib import Path | |
| from accuracy_validators import ( | |
| CitationValidator, | |
| RelevanceScorer, | |
| HallucinationDetector, | |
| AreaInsightsValidator, | |
| FormatValidator, | |
| AccuracyAnalyzer | |
| ) | |
| from report_generator import ReportGenerator | |
| class TestCitationValidator: | |
| """Test citation validation.""" | |
| def test_citation_extraction(self): | |
| """Test extracting citations from response.""" | |
| response = """ | |
| 1. **HbA1c Level** (Dataset: EJI_2024) | |
| 2. **Glucose** (Source: AHRF-2025) | |
| """ | |
| validator = CitationValidator() | |
| citations = validator._extract_citations(response) | |
| assert len(citations) >= 2 | |
| assert "EJI_2024" in citations | |
| assert "AHRF-2025" in citations | |
| def test_dataset_normalization(self): | |
| """Test dataset name normalization.""" | |
| validator = CitationValidator() | |
| assert validator._normalize_dataset("EJI_2024") == "EJI_2024" | |
| assert validator._normalize_dataset("eji 2024") == "EJI_2024" | |
| assert validator._normalize_dataset(" AHRF-2025 ") == "AHRF-2025" | |
| def test_validate_sufficient_citations(self): | |
| """Test validation of citation count.""" | |
| validator = CitationValidator() | |
| response = """ | |
| 1. **Column A** (Dataset: EJI_2024) | |
| 2. **Column B** (Dataset: AHRF-2025) | |
| 3. **Column C** (Dataset: SVI_2022) | |
| """ | |
| test_case = { | |
| "test_id": "TEST_001", | |
| "name": "Test", | |
| "expected_datasets": ["EJI_2024"], | |
| "min_recommendations": 2 | |
| } | |
| result = validator.validate(response, test_case) | |
| assert result["citation_count"] >= 2 | |
| assert result["passed"] is True | |
| def test_validate_insufficient_citations(self): | |
| """Test validation fails with insufficient citations.""" | |
| validator = CitationValidator() | |
| response = "Here is some information but no citations." | |
| test_case = { | |
| "test_id": "TEST_001", | |
| "name": "Test", | |
| "expected_datasets": ["EJI_2024"], | |
| "min_recommendations": 3 | |
| } | |
| result = validator.validate(response, test_case) | |
| assert result["passed"] is False | |
| assert len(result["issues"]) > 0 | |
| def test_validate_unknown_dataset(self): | |
| """Test validation detects unknown datasets.""" | |
| validator = CitationValidator() | |
| response = "**Column** (Dataset: UNKNOWN_DATASET_2025)" | |
| test_case = { | |
| "test_id": "TEST_001", | |
| "name": "Test", | |
| "expected_datasets": [], | |
| "min_recommendations": 0 | |
| } | |
| result = validator.validate(response, test_case) | |
| assert result["passed"] is False | |
| assert len(result["issues"]) > 0 | |
| class TestRelevanceScorer: | |
| """Test relevance scoring.""" | |
| def test_high_relevance_score(self): | |
| """Test high relevance score.""" | |
| scorer = RelevanceScorer() | |
| response = "diabetes risk prediction involves glucose, hba1c, and family history factors" | |
| test_case = { | |
| "test_id": "TEST_001", | |
| "expected_column_patterns": ["diabetes", "glucose", "hba1c"] | |
| } | |
| result = scorer.validate(response, test_case) | |
| assert result["score"] >= 0.5 | |
| assert len(result["matched_patterns"]) > 0 | |
| def test_low_relevance_score(self): | |
| """Test low relevance score.""" | |
| scorer = RelevanceScorer() | |
| response = "The weather is nice today." | |
| test_case = { | |
| "test_id": "TEST_001", | |
| "expected_column_patterns": ["diabetes", "hospital", "readmission"] | |
| } | |
| result = scorer.validate(response, test_case) | |
| assert result["score"] < 0.4 | |
| assert result["passed"] is False | |
| def test_no_expected_patterns(self): | |
| """Test relevance scoring with no expected patterns.""" | |
| scorer = RelevanceScorer() | |
| response = "Hello there!" | |
| test_case = { | |
| "test_id": "TEST_001", | |
| "expected_column_patterns": [] | |
| } | |
| result = scorer.validate(response, test_case) | |
| assert result["score"] == 1.0 | |
| assert result["passed"] is True | |
| class TestHallucinationDetector: | |
| """Test hallucination detection.""" | |
| def test_column_extraction(self): | |
| """Test extracting column names from response.""" | |
| response = """ | |
| 1. **HbA1c Level** (Dataset: EJI_2024) | |
| 2. **Age Group** (Dataset: SVI_2022) | |
| """ | |
| columns = HallucinationDetector._extract_column_names(response) | |
| assert "HbA1c Level" in columns or "HbA1c" in str(columns).lower() | |
| assert len(columns) >= 1 | |
| def test_realistic_column_name_validation(self): | |
| """Test validation of realistic column names.""" | |
| detector = HallucinationDetector.__new__(HallucinationDetector) | |
| # Valid column names | |
| assert detector._is_likely_real("HbA1c Level", []) is True | |
| assert detector._is_likely_real("patient_age", []) is True | |
| assert detector._is_likely_real("BMI", []) is True | |
| assert detector._is_likely_real("Poverty Rate %", []) is True | |
| # Less likely column names | |
| assert detector._is_likely_real("XYZ123ABC", []) is False | |
| def test_hallucination_detection_with_mock_data(self): | |
| """Test detecting hallucinated columns.""" | |
| # This would need a real data dictionary service | |
| # For now, test the structure | |
| response = "**FakeColumn123** (Dataset: EJI_2024)" | |
| columns = HallucinationDetector._extract_column_names(response) | |
| assert len(columns) > 0 | |
| # FakeColumn123 would be detected as hallucinated if not in actual data | |
| class TestAreaInsightsValidator: | |
| """Test area insights validation.""" | |
| def test_validate_geographic_mention(self): | |
| """Test validation of geographic mention.""" | |
| validator = AreaInsightsValidator() | |
| response = "For San Francisco, the available data includes..." | |
| test_case = { | |
| "test_id": "AREA_001", | |
| "type": "area_insights", | |
| "location_name": "San Francisco", | |
| "expected_datasets": ["EJI_2024"] | |
| } | |
| result = validator.validate(response, test_case) | |
| assert result["mentions_location"] is True | |
| def test_validate_non_area_insights_test(self): | |
| """Test that non-area-insights tests pass validation.""" | |
| validator = AreaInsightsValidator() | |
| response = "Some generic response" | |
| test_case = { | |
| "test_id": "CHAT_001", | |
| "type": "chat" | |
| } | |
| result = validator.validate(response, test_case) | |
| assert result["score"] == 1.0 | |
| def test_validate_fallback_detection(self): | |
| """Test detection of fallback responses.""" | |
| validator = AreaInsightsValidator() | |
| response = "This ZIP code is invalid. No data available for this area. Using general knowledge instead." | |
| test_case = { | |
| "test_id": "AREA_005", | |
| "type": "area_insights", | |
| "location_name": "Invalid ZIP", | |
| "should_fallback_to_general": True, | |
| "expected_datasets": [] | |
| } | |
| result = validator.validate(response, test_case) | |
| assert result["fallback_used"] is True | |
| class TestFormatValidator: | |
| """Test format validation.""" | |
| def test_validate_structured_list_format(self): | |
| """Test detection of structured list format.""" | |
| validator = FormatValidator() | |
| response = """ | |
| 1. First item | |
| 2. Second item | |
| 3. Third item | |
| """ | |
| test_case = { | |
| "test_id": "TEST_001", | |
| "min_recommendations": 3 | |
| } | |
| result = validator.validate(response, test_case) | |
| assert result["has_structured_list"] is True | |
| assert result["score"] >= 0.7 | |
| def test_validate_bold_formatting(self): | |
| """Test detection of bold formatting.""" | |
| validator = FormatValidator() | |
| response = "**Column Name** is important" | |
| test_case = { | |
| "test_id": "TEST_001", | |
| "min_recommendations": 1 | |
| } | |
| result = validator.validate(response, test_case) | |
| assert result["uses_bold_formatting"] is True | |
| def test_validate_response_too_short(self): | |
| """Test validation of minimum response length.""" | |
| validator = FormatValidator() | |
| response = "No." | |
| test_case = { | |
| "test_id": "TEST_001", | |
| "min_recommendations": 3 | |
| } | |
| result = validator.validate(response, test_case) | |
| assert result["passed"] is False | |
| assert any("too short" in issue.lower() for issue in result["issues"]) | |
| def test_validate_enough_content(self): | |
| """Test validation with sufficient content.""" | |
| validator = FormatValidator() | |
| response = "This is a sufficiently detailed response with enough content to meet minimum requirements." | |
| test_case = { | |
| "test_id": "TEST_001", | |
| "min_recommendations": 1 | |
| } | |
| result = validator.validate(response, test_case) | |
| assert result["passed"] is True | |
| class TestAccuracyAnalyzer: | |
| """Test the comprehensive accuracy analyzer.""" | |
| def test_analyzer_initialization(self): | |
| """Test analyzer initializes correctly.""" | |
| analyzer = AccuracyAnalyzer() | |
| assert analyzer.citation_validator is not None | |
| assert analyzer.relevance_scorer is not None | |
| assert analyzer.format_validator is not None | |
| def test_single_response_analysis(self): | |
| """Test analyzing a single response.""" | |
| analyzer = AccuracyAnalyzer() | |
| test_case = { | |
| "test_id": "TEST_001", | |
| "name": "Sample Test", | |
| "query": "What columns help predict diabetes?", | |
| "expected_datasets": ["EJI_2024"], | |
| "expected_column_patterns": ["diabetes", "glucose"], | |
| "min_recommendations": 2, | |
| "type": "chat" | |
| } | |
| response = """ | |
| Based on the available data, here are relevant columns: | |
| 1. **HbA1c Level** (Dataset: EJI_2024) - Primary diabetes indicator | |
| 2. **Fasting Glucose** (Dataset: EJI_2024) - Blood glucose concentration | |
| """ | |
| analysis = analyzer.analyze_response(test_case, response) | |
| assert analysis["test_id"] == "TEST_001" | |
| assert analysis["overall_score"] >= 0.0 | |
| assert "validations" in analysis | |
| assert len(analysis["validations"]) > 0 | |
| def test_batch_analysis(self): | |
| """Test batch analysis of multiple results.""" | |
| analyzer = AccuracyAnalyzer() | |
| test_cases = [ | |
| { | |
| "test_id": "TEST_001", | |
| "name": "Test 1", | |
| "expected_datasets": ["EJI_2024"], | |
| "expected_column_patterns": ["diabetes"], | |
| "min_recommendations": 1, | |
| "type": "chat" | |
| }, | |
| { | |
| "test_id": "TEST_002", | |
| "name": "Test 2", | |
| "expected_datasets": ["AHRF-2025"], | |
| "expected_column_patterns": ["hospital"], | |
| "min_recommendations": 1, | |
| "type": "chat" | |
| } | |
| ] | |
| test_results = [ | |
| { | |
| "test_id": "TEST_001", | |
| "response": "**HbA1c** (Dataset: EJI_2024)" | |
| }, | |
| { | |
| "test_id": "TEST_002", | |
| "response": "**Hospital Beds** (Dataset: AHRF-2025)" | |
| } | |
| ] | |
| batch_result = analyzer.analyze_batch(test_results, test_cases) | |
| assert batch_result["total_tests"] == 2 | |
| assert batch_result["average_score"] >= 0.0 | |
| assert len(batch_result["analyses"]) == 2 | |
| class TestReportGenerator: | |
| """Test report generation.""" | |
| def test_html_report_generation(self, tmp_path): | |
| """Test HTML report generation.""" | |
| generator = ReportGenerator() | |
| batch_analysis = { | |
| "total_tests": 5, | |
| "passed_tests": 4, | |
| "failed_tests": 1, | |
| "average_score": 0.8, | |
| "pass_rate": 0.8, | |
| "analyses": [ | |
| { | |
| "test_id": "TEST_001", | |
| "test_name": "Test 1", | |
| "overall_score": 0.9, | |
| "overall_passed": True, | |
| "validations": { | |
| "citation": {"passed": True, "score": 1.0, "issues": []}, | |
| "relevance": {"passed": True, "score": 0.85, "issues": []} | |
| }, | |
| "response_snippet": "Sample response..." | |
| } | |
| ] | |
| } | |
| output_file = tmp_path / "report.html" | |
| result_path = generator.generate_html_report(batch_analysis, str(output_file)) | |
| assert Path(result_path).exists() | |
| with open(result_path) as f: | |
| content = f.read() | |
| assert "Data Dictionary Chatbot" in content | |
| assert "Accuracy Analysis" in content | |
| def test_markdown_report_generation(self, tmp_path): | |
| """Test Markdown report generation.""" | |
| generator = ReportGenerator() | |
| batch_analysis = { | |
| "total_tests": 3, | |
| "passed_tests": 2, | |
| "failed_tests": 1, | |
| "average_score": 0.75, | |
| "pass_rate": 0.667, | |
| "analyses": [] | |
| } | |
| output_file = tmp_path / "report.md" | |
| result_path = generator.generate_markdown_report(batch_analysis, str(output_file)) | |
| assert Path(result_path).exists() | |
| with open(result_path) as f: | |
| content = f.read() | |
| assert "Accuracy Report" in content | |
| assert "Total Tests" in content | |
| def test_assessment_text_generation(self): | |
| """Test assessment text generation for different pass rates.""" | |
| assert "Excellent" in ReportGenerator._get_assessment_text(0.95) | |
| assert "Good" in ReportGenerator._get_assessment_text(0.85) | |
| assert "Fair" in ReportGenerator._get_assessment_text(0.70) | |
| assert "Poor" in ReportGenerator._get_assessment_text(0.50) | |
| assert "Critical" in ReportGenerator._get_assessment_text(0.30) | |
| if __name__ == "__main__": | |
| pytest.main([__file__, "-v"]) | |