Spaces:
Sleeping
Sleeping
Download tests/test_chat_automation.py from faseehsandhu/Digitalytics: direct link, hf CLI and curl.
- Browser
- Download file 9 kB
-
https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/tests/test_chat_automation.py
- Command line
-
hf download hf://spaces/faseehsandhu/Digitalytics/tests/test_chat_automation.py
-
curl -L -o test_chat_automation.py https://huggingface.co/spaces/faseehsandhu/Digitalytics/resolve/main/tests/test_chat_automation.py
9 kB
| """ | |
| test_chat_automation.py | |
| Pytest tests for chat automation functionality. | |
| Executes the chat automation harness and validates test execution. | |
| """ | |
| import pytest | |
| import json | |
| from pathlib import Path | |
| from chat_automation import ChatAutomation, MockAzureOpenAIService | |
| class TestChatAutomationMock: | |
| """Test suite for chat automation with mock service.""" | |
| def test_mock_service_initialization(self): | |
| """Test that mock service initializes correctly.""" | |
| service = MockAzureOpenAIService() | |
| assert service is not None | |
| assert service.call_count == 0 | |
| def test_mock_service_diabetes_response(self): | |
| """Test mock service returns appropriate response for diabetes query.""" | |
| service = MockAzureOpenAIService() | |
| response = service.get_chat_response( | |
| query="I'm building a diabetes risk prediction model", | |
| context="", | |
| chat_history=[], | |
| system_prompt="" | |
| ) | |
| assert response is not None | |
| assert len(response) > 50 | |
| assert "diabetes" in response.lower() or "glucose" in response.lower() | |
| assert service.call_count == 1 | |
| def test_mock_service_greeting_response(self): | |
| """Test mock service handles greetings.""" | |
| service = MockAzureOpenAIService() | |
| response = service.get_chat_response( | |
| query="Hi there!", | |
| context="", | |
| chat_history=[], | |
| system_prompt="" | |
| ) | |
| assert response is not None | |
| assert "hello" in response.lower() or "help" in response.lower() | |
| def test_chat_automation_initialization_mock(self, chat_automation_mock): | |
| """Test ChatAutomation initializes with mock service.""" | |
| assert chat_automation_mock is not None | |
| assert chat_automation_mock.use_mock is True | |
| assert chat_automation_mock.test_results == [] | |
| def test_should_run_retrieval_logic(self): | |
| """Test the retrieval decision logic.""" | |
| # Should not retrieve for simple queries | |
| assert ChatAutomation._should_run_retrieval("hi") is False | |
| assert ChatAutomation._should_run_retrieval("hello") is False | |
| assert ChatAutomation._should_run_retrieval("bye") is False | |
| # Should retrieve for complex queries | |
| assert ChatAutomation._should_run_retrieval("What columns help predict diabetes?") is True | |
| assert ChatAutomation._should_run_retrieval("Tell me about the SVI dataset") is True | |
| def test_format_context(self): | |
| """Test context formatting for LLM.""" | |
| chunks = [ | |
| {"text": "Column A description", "dataset": "EJI_2024", "line_number": 1}, | |
| {"text": "Column B description", "dataset": "AHRF-2025", "line_number": 2} | |
| ] | |
| context = ChatAutomation._format_context(chunks) | |
| assert "Retrieved Data Dictionary Entries" in context | |
| assert "EJI_2024" in context | |
| assert "AHRF-2025" in context | |
| assert "Column A description" in context | |
| def test_extract_citations(self): | |
| """Test citation extraction from response text.""" | |
| response = """ | |
| 1. **HbA1c Level** (Dataset: EJI_2024) | |
| 2. **Fasting Glucose** (Source: AHRF-2025) | |
| 3. **BMI** (Dataset: SVI_2022) | |
| """ | |
| citations = ChatAutomation._extract_citations(response) | |
| assert len(citations) >= 3 | |
| assert "EJI_2024" in citations | |
| assert "AHRF-2025" in citations | |
| assert "SVI_2022" in citations | |
| def test_run_single_chat_test_mock(self, chat_automation_mock, chat_interface_tests): | |
| """Test running a single chat test with mock service.""" | |
| if not chat_interface_tests: | |
| pytest.skip("No chat interface tests available") | |
| test_case = chat_interface_tests[0] | |
| result = chat_automation_mock.run_chat_test(test_case) | |
| assert result["test_id"] == test_case["test_id"] | |
| assert result["query"] == test_case["query"] | |
| assert "response" in result | |
| assert result["execution_time_ms"] >= 0 | |
| assert "citations" in result | |
| def test_run_area_insights_test_mock(self, chat_automation_mock, area_insights_tests): | |
| """Test running an area insights test with mock service.""" | |
| if not area_insights_tests: | |
| pytest.skip("No area insights tests available") | |
| test_case = area_insights_tests[0] | |
| result = chat_automation_mock.run_area_insights_test(test_case) | |
| assert result["test_id"] == test_case["test_id"] | |
| assert result["type"] == "area_insights" | |
| assert "response" in result | |
| def test_save_results_to_json(self, chat_automation_mock, tmp_path, chat_interface_tests): | |
| """Test saving results to JSON file.""" | |
| if not chat_interface_tests: | |
| pytest.skip("No chat interface tests available") | |
| # Run a test | |
| test_result = chat_automation_mock.run_chat_test(chat_interface_tests[0]) | |
| chat_automation_mock.test_results = [test_result] | |
| # Save results | |
| output_file = tmp_path / "test_results.json" | |
| saved_path = chat_automation_mock.save_results(str(output_file)) | |
| # Verify file exists and contains data | |
| assert Path(saved_path).exists() | |
| with open(saved_path) as f: | |
| data = json.load(f) | |
| assert len(data) == 1 | |
| assert data[0]["test_id"] == chat_interface_tests[0]["test_id"] | |
| def test_run_all_tests_mock(self, chat_automation_mock, test_cases): | |
| """Test running all test cases with mock service.""" | |
| results = chat_automation_mock.run_all_tests() | |
| expected_count = len(test_cases.get("chat_interface_tests", [])) + len(test_cases.get("area_insights_tests", [])) | |
| assert len(results) > 0 | |
| assert len(results) <= expected_count # May be less if some tests are skipped | |
| class TestChatAutomationIntegration: | |
| """Integration tests for chat automation (requires real services).""" | |
| def test_real_service_initialization(self): | |
| """Test ChatAutomation with real service.""" | |
| try: | |
| automation = ChatAutomation(use_mock=False) | |
| assert automation is not None | |
| assert automation.use_mock is False | |
| except ValueError: | |
| # Expected if credentials not configured | |
| pytest.skip("Azure OpenAI credentials not configured") | |
| def test_real_chat_test(self, chat_interface_tests): | |
| """Test running real chat test.""" | |
| if not chat_interface_tests: | |
| pytest.skip("No chat interface tests available") | |
| try: | |
| automation = ChatAutomation(use_mock=False) | |
| result = automation.run_chat_test(chat_interface_tests[0]) | |
| assert result["success"] | |
| except ValueError: | |
| pytest.skip("Azure OpenAI credentials not configured") | |
| class TestTestCaseValidation: | |
| """Validate test case structure and content.""" | |
| def test_test_cases_loaded(self, test_cases): | |
| """Test that test cases are properly loaded.""" | |
| assert test_cases is not None | |
| assert "chat_interface_tests" in test_cases | |
| assert "area_insights_tests" in test_cases | |
| assert "validation_rules" in test_cases | |
| def test_chat_test_case_structure(self, chat_interface_tests): | |
| """Test chat test cases have required fields.""" | |
| required_fields = ["test_id", "name", "query", "expected_datasets", "type"] | |
| for test_case in chat_interface_tests: | |
| for field in required_fields: | |
| assert field in test_case, f"Missing field '{field}' in test case {test_case.get('test_id')}" | |
| assert test_case["type"] == "chat" | |
| def test_area_insights_test_case_structure(self, area_insights_tests): | |
| """Test area insights test cases have required fields.""" | |
| required_fields = ["test_id", "name", "query", "type"] | |
| for test_case in area_insights_tests: | |
| for field in required_fields: | |
| assert field in test_case, f"Missing field '{field}' in test case {test_case.get('test_id')}" | |
| assert test_case["type"] == "area_insights" | |
| def test_validation_rules_defined(self, validation_rules): | |
| """Test that validation rules are defined.""" | |
| expected_rules = [ | |
| "citation_format", | |
| "no_hallucination", | |
| "dataset_accuracy", | |
| "relevance", | |
| "completeness" | |
| ] | |
| for rule in expected_rules: | |
| assert rule in validation_rules, f"Missing validation rule: {rule}" | |
| if __name__ == "__main__": | |
| pytest.main([__file__, "-v"]) | |