Skip to content

~95% on SimpleQA (e.g. Qwen3.6-27B on a 3090). Supports all local and cloud LLMs (llama.cpp, Ollama, Google, ...). 10+ search engines - arXiv, PubMed, your private documents. Everything Local & Encrypted.

Apply pre-commit formatting and fix linting issues

LearningCircuitcff4175e998a
diff --git a/src/local_deep_research/config/llm_config.py b/src/local_deep_research/config/llm_config.py
index 4796998d95..b0b0f77b0c 100644
--- a/src/local_deep_research/config/llm_config.py
+++ b/src/local_deep_research/config/llm_config.py
@@ -397,18 +397,24 @@ def get_llm(
llm = ChatOllama(
model=model_name, base_url=base_url, **common_params
)
-
+
# Log the actual client configuration after creation
- logger.debug(f"ChatOllama created - base_url attribute: {getattr(llm, 'base_url', 'not found')}")
- if hasattr(llm, '_client'):
+ logger.debug(
+ f"ChatOllama created - base_url attribute: {getattr(llm, 'base_url', 'not found')}"
+ )
+ if hasattr(llm, "_client"):
client = llm._client
logger.debug(f"ChatOllama _client type: {type(client)}")
- if hasattr(client, '_client'):
+ if hasattr(client, "_client"):
inner_client = client._client
- logger.debug(f"ChatOllama inner client type: {type(inner_client)}")
- if hasattr(inner_client, 'base_url'):
- logger.debug(f"ChatOllama inner client base_url: {inner_client.base_url}")
-
+ logger.debug(
+ f"ChatOllama inner client type: {type(inner_client)}"
+ )
+ if hasattr(inner_client, "base_url"):
+ logger.debug(
+ f"ChatOllama inner client base_url: {inner_client.base_url}"
+ )
+
# Test invoke to validate model works
logger.info("Testing Ollama model with simple invocation")
test_result = llm.invoke("Hello")
@@ -558,22 +564,36 @@ def wrap_llm_without_think_tags(
def invoke(self, *args, **kwargs):
# Log detailed request information for Ollama models
- if hasattr(self.base_llm, 'base_url'):
- logger.debug(f"LLM Request - Base URL: {self.base_llm.base_url}")
- logger.debug(f"LLM Request - Model: {getattr(self.base_llm, 'model', 'unknown')}")
- logger.debug(f"LLM Request - Args count: {len(args)}, Kwargs: {list(kwargs.keys())}")
-
+ if hasattr(self.base_llm, "base_url"):
+ logger.debug(
+ f"LLM Request - Base URL: {self.base_llm.base_url}"
+ )
+ logger.debug(
+ f"LLM Request - Model: {getattr(self.base_llm, 'model', 'unknown')}"
+ )
+ logger.debug(
+ f"LLM Request - Args count: {len(args)}, Kwargs: {list(kwargs.keys())}"
+ )
+
# Log the prompt if it's in args
if args and len(args) > 0:
- prompt_text = str(args[0])[:200] + "..." if len(str(args[0])) > 200 else str(args[0])
+ prompt_text = (
+ str(args[0])[:200] + "..."
+ if len(str(args[0])) > 200
+ else str(args[0])
+ )
logger.debug(f"LLM Request - Prompt preview: {prompt_text}")
-
+
# Check if there's any client configuration
- if hasattr(self.base_llm, '_client'):
+ if hasattr(self.base_llm, "_client"):
client = self.base_llm._client
- if hasattr(client, '_client') and hasattr(client._client, 'base_url'):
- logger.debug(f"LLM Request - Client base URL: {client._client.base_url}")
-
+ if hasattr(client, "_client") and hasattr(
+ client._client, "base_url"
+ ):
+ logger.debug(
+ f"LLM Request - Client base URL: {client._client.base_url}"
+ )
+
try:
response = self.base_llm.invoke(*args, **kwargs)
logger.debug(f"LLM Response - Success, type: {type(response)}")
@@ -582,7 +602,9 @@ def wrap_llm_without_think_tags(
# Log any URL information from the error
error_str = str(e)
if "http://" in error_str or "https://" in error_str:
- logger.error(f"LLM Request - Error contains URL info: {error_str}")
+ logger.error(
+ f"LLM Request - Error contains URL info: {error_str}"
+ )
raise
# Process the response content if it has a content attribute
diff --git a/src/local_deep_research/error_handling/__init__.py b/src/local_deep_research/error_handling/__init__.py
index ebbda4f500..7c1d00319a 100644
--- a/src/local_deep_research/error_handling/__init__.py
+++ b/src/local_deep_research/error_handling/__init__.py
@@ -10,4 +10,4 @@ This module provides comprehensive error handling capabilities including:
from .error_reporter import ErrorReporter
from .report_generator import ErrorReportGenerator
-__all__ = ["ErrorReporter", "ErrorReportGenerator"]
\ No newline at end of file
+__all__ = ["ErrorReporter", "ErrorReportGenerator"]
diff --git a/src/local_deep_research/error_handling/error_reporter.py b/src/local_deep_research/error_handling/error_reporter.py
index a1a4eaf62e..2c3905d62c 100644
--- a/src/local_deep_research/error_handling/error_reporter.py
+++ b/src/local_deep_research/error_handling/error_reporter.py
@@ -10,6 +10,7 @@ from loguru import logger
class ErrorCategory(Enum):
"""Categories of errors that can occur during research"""
+
CONNECTION_ERROR = "connection_error"
MODEL_ERROR = "model_error"
SEARCH_ERROR = "search_error"
@@ -22,7 +23,7 @@ class ErrorReporter:
"""
Analyzes and categorizes errors to provide better user feedback
"""
-
+
def __init__(self):
self.error_patterns = {
ErrorCategory.CONNECTION_ERROR: [
@@ -57,36 +58,38 @@ class ErrorReporter:
r"File.*not found",
r"Cannot write.*file",
r"Disk.*full",
- ]
+ ],
}
-
+
def categorize_error(self, error_message: str) -> ErrorCategory:
"""
Categorize an error based on its message
-
+
Args:
error_message: The error message to categorize
-
+
Returns:
ErrorCategory: The categorized error type
"""
error_message = str(error_message).lower()
-
+
for category, patterns in self.error_patterns.items():
for pattern in patterns:
if re.search(pattern.lower(), error_message):
- logger.debug(f"Categorized error as {category.value}: {pattern}")
+ logger.debug(
+ f"Categorized error as {category.value}: {pattern}"
+ )
return category
-
+
return ErrorCategory.UNKNOWN_ERROR
-
+
def get_user_friendly_title(self, category: ErrorCategory) -> str:
"""
Get a user-friendly title for an error category
-
+
Args:
category: The error category
-
+
Returns:
str: User-friendly title
"""
@@ -99,14 +102,14 @@ class ErrorReporter:
ErrorCategory.UNKNOWN_ERROR: "Unexpected Error",
}
return titles.get(category, "Error")
-
+
def get_suggested_actions(self, category: ErrorCategory) -> list:
"""
Get suggested actions for resolving an error
-
+
Args:
category: The error category
-
+
Returns:
list: List of suggested actions
"""
@@ -149,20 +152,22 @@ class ErrorReporter:
],
}
return suggestions.get(category, ["Check the logs for more details"])
-
- def analyze_error(self, error_message: str, context: Optional[Dict[str, Any]] = None) -> Dict[str, Any]:
+
+ def analyze_error(
+ self, error_message: str, context: Optional[Dict[str, Any]] = None
+ ) -> Dict[str, Any]:
"""
Perform comprehensive error analysis
-
+
Args:
error_message: The error message to analyze
context: Optional context information
-
+
Returns:
dict: Comprehensive error analysis
"""
category = self.categorize_error(error_message)
-
+
analysis = {
"category": category,
"title": self.get_user_friendly_title(category),
@@ -171,30 +176,30 @@ class ErrorReporter:
"severity": self._determine_severity(category),
"recoverable": self._is_recoverable(category),
}
-
+
# Add context-specific information
if context:
analysis["context"] = context
analysis["has_partial_results"] = bool(
- context.get("findings") or
- context.get("current_knowledge") or
- context.get("search_results")
+ context.get("findings")
+ or context.get("current_knowledge")
+ or context.get("search_results")
)
-
+
return analysis
-
+
def _determine_severity(self, category: ErrorCategory) -> str:
"""Determine error severity level"""
severity_map = {
ErrorCategory.CONNECTION_ERROR: "high",
- ErrorCategory.MODEL_ERROR: "high",
+ ErrorCategory.MODEL_ERROR: "high",
ErrorCategory.SEARCH_ERROR: "medium",
ErrorCategory.SYNTHESIS_ERROR: "low", # Can often show partial results
ErrorCategory.FILE_ERROR: "medium",
ErrorCategory.UNKNOWN_ERROR: "high",
}
return severity_map.get(category, "medium")
-
+
def _is_recoverable(self, category: ErrorCategory) -> bool:
"""Determine if error is recoverable with user action"""
recoverable = {
@@ -205,4 +210,4 @@ class ErrorReporter:
ErrorCategory.FILE_ERROR: True,
ErrorCategory.UNKNOWN_ERROR: False,
}
- return recoverable.get(category, False)
\ No newline at end of file
+ return recoverable.get(category, False)
diff --git a/src/local_deep_research/error_handling/report_generator.py b/src/local_deep_research/error_handling/report_generator.py
index 01f8d10c70..60f04f209a 100644
--- a/src/local_deep_research/error_handling/report_generator.py
+++ b/src/local_deep_research/error_handling/report_generator.py
@@ -2,45 +2,44 @@
ErrorReportGenerator - Create user-friendly error reports
"""
-from datetime import datetime
-from typing import Dict, Any, Optional, List
+from typing import Dict, Any, Optional
from loguru import logger
-from .error_reporter import ErrorReporter, ErrorCategory
+from .error_reporter import ErrorReporter
class ErrorReportGenerator:
"""
Generates comprehensive, user-friendly error reports
"""
-
+
def __init__(self, llm=None):
"""
Initialize error report generator
-
+
Args:
llm: Optional LLM instance (unused, kept for compatibility)
"""
self.error_reporter = ErrorReporter()
-
+
def generate_error_report(
- self,
- error_message: str,
+ self,
+ error_message: str,
query: str,
partial_results: Optional[Dict[str, Any]] = None,
search_iterations: int = 0,
- research_id: Optional[int] = None
+ research_id: Optional[int] = None,
) -> str:
"""
Generate a comprehensive error report
-
+
Args:
error_message: The error that occurred
query: The research query
partial_results: Any partial results that were collected
search_iterations: Number of search iterations completed
research_id: Research ID for reference
-
+
Returns:
str: Formatted error report in Markdown
"""
@@ -50,42 +49,55 @@ class ErrorReportGenerator:
"query": query,
"search_iterations": search_iterations,
"research_id": research_id,
- "partial_results": partial_results
+ "partial_results": partial_results,
}
-
+
if partial_results:
context.update(partial_results)
-
- error_analysis = self.error_reporter.analyze_error(error_message, context)
-
+
+ error_analysis = self.error_reporter.analyze_error(
+ error_message, context
+ )
+
# Build the simplified report
report_parts = []
-
+
# Header with user-friendly error message and logs reference
- user_friendly_message = self._make_error_user_friendly(error_message)
- category = error_analysis.get("category")
+ user_friendly_message = self._make_error_user_friendly(
+ error_message
+ )
category_title = error_analysis.get("title", "Error")
-
- report_parts.append(f"# ⚠️ Research Failed")
+
+ report_parts.append("# ⚠️ Research Failed")
report_parts.append(f"\n**Error Type:** {category_title}")
report_parts.append(f"\n**What happened:** {user_friendly_message}")
- report_parts.append(f"\n*For detailed error information, scroll down to the research logs and select \"Errors\" from the filter.*")
-
+ report_parts.append(
+ '\n*For detailed error information, scroll down to the research logs and select "Errors" from the filter.*'
+ )
+
# Support links - moved up for better visibility
- report_parts.append(f"\n## 💬 Get Help")
+ report_parts.append("\n## 💬 Get Help")
report_parts.append("We're here to help you get this working:")
- report_parts.append("- **Chat with the community:** [Discord #help-and-support](https://discord.gg/ttcqQeFcJ3)")
- report_parts.append("- **Report bugs:** [GitHub Issues](https://github.com/LearningCircuit/local-deep-research/issues)")
- report_parts.append("- **Join discussions:** [Reddit r/LocalDeepResearch](https://www.reddit.com/r/LocalDeepResearch/) *(checked less frequently)*")
-
+ report_parts.append(
+ "- **Chat with the community:** [Discord #help-and-support](https://discord.gg/ttcqQeFcJ3)"
+ )
+ report_parts.append(
+ "- **Report bugs:** [GitHub Issues](https://github.com/LearningCircuit/local-deep-research/issues)"
+ )
+ report_parts.append(
+ "- **Join discussions:** [Reddit r/LocalDeepResearch](https://www.reddit.com/r/LocalDeepResearch/) *(checked less frequently)*"
+ )
+
# Show partial results if available (in expandable section)
if error_analysis.get("has_partial_results"):
partial_content = self._format_partial_results(partial_results)
if partial_content:
- report_parts.append(f"\n<details>\n<summary>📊 Partial Results Available</summary>\n\n{partial_content}\n</details>")
-
+ report_parts.append(
+ f"\n<details>\n<summary>📊 Partial Results Available</summary>\n\n{partial_content}\n</details>"
+ )
+
return "\n".join(report_parts)
-
+
except Exception as e:
# Fallback: always return something, even if error report generation fails
logger.exception(f"Failed to generate error report: {e}")
@@ -99,30 +111,36 @@ We're here to help you get this working:
- **Report bugs:** [GitHub Issues](https://github.com/LearningCircuit/local-deep-research/issues)
*Note: Error report generation failed - showing basic error information.*"""
-
- def _format_partial_results(self, partial_results: Optional[Dict[str, Any]]) -> str:
+
+ def _format_partial_results(
+ self, partial_results: Optional[Dict[str, Any]]
+ ) -> str:
"""
Format partial results for display
-
+
Args:
partial_results: Partial results data
-
+
Returns:
str: Formatted partial results
"""
if not partial_results:
return ""
-
+
formatted_parts = []
-
+
# Current knowledge summary
if "current_knowledge" in partial_results:
knowledge = partial_results["current_knowledge"]
if knowledge and len(knowledge.strip()) > 50:
formatted_parts.append("### Research Summary\n")
- formatted_parts.append(knowledge[:1000] + "..." if len(knowledge) > 1000 else knowledge)
+ formatted_parts.append(
+ knowledge[:1000] + "..."
+ if len(knowledge) > 1000
+ else knowledge
+ )
formatted_parts.append("")
-
+
# Search results
if "search_results" in partial_results:
results = partial_results["search_results"]
@@ -135,7 +153,7 @@ We're here to help you get this working:
if url:
formatted_parts.append(f" - URL: {url}")
formatted_parts.append("")
-
+
# Findings
if "findings" in partial_results:
findings = partial_results["findings"]
@@ -146,92 +164,128 @@ We're here to help you get this working:
if content and not content.startswith("Error:"):
phase = finding.get("phase", f"Finding {i}")
formatted_parts.append(f"**{phase}:**")
- formatted_parts.append(content[:500] + "..." if len(content) > 500 else content)
+ formatted_parts.append(
+ content[:500] + "..."
+ if len(content) > 500
+ else content
+ )
formatted_parts.append("")
-
+
if formatted_parts:
- formatted_parts.append("*Note: The above results were successfully collected before the error occurred.*")
-
+ formatted_parts.append(
+ "*Note: The above results were successfully collected before the error occurred.*"
+ )
+
return "\n".join(formatted_parts) if formatted_parts else ""
-
- def _get_technical_context(self, error_analysis: Dict[str, Any], partial_results: Optional[Dict[str, Any]]) -> str:
+
+ def _get_technical_context(
+ self,
+ error_analysis: Dict[str, Any],
+ partial_results: Optional[Dict[str, Any]],
+ ) -> str:
"""
Get additional technical context for the error
-
+
Args:
error_analysis: Error analysis results
partial_results: Partial results if available
-
+
Returns:
str: Technical context information
"""
context_parts = []
-
+
# Add timing information if available
if partial_results:
if "start_time" in partial_results:
- context_parts.append(f"- **Start Time:** {partial_results['start_time']}")
-
+ context_parts.append(
+ f"- **Start Time:** {partial_results['start_time']}"
+ )
+
if "last_activity" in partial_results:
- context_parts.append(f"- **Last Activity:** {partial_results['last_activity']}")
-
+ context_parts.append(
+ f"- **Last Activity:** {partial_results['last_activity']}"
+ )
+
# Add model information
if "model_config" in partial_results:
config = partial_results["model_config"]
- context_parts.append(f"- **Model:** {config.get('model_name', 'Unknown')}")
- context_parts.append(f"- **Provider:** {config.get('provider', 'Unknown')}")
-
+ context_parts.append(
+ f"- **Model:** {config.get('model_name', 'Unknown')}"
+ )
+ context_parts.append(
+ f"- **Provider:** {config.get('provider', 'Unknown')}"
+ )
+
# Add search information
if "search_config" in partial_results:
search_config = partial_results["search_config"]
- context_parts.append(f"- **Search Engine:** {search_config.get('engine', 'Unknown')}")
- context_parts.append(f"- **Max Results:** {search_config.get('max_results', 'Unknown')}")
-
+ context_parts.append(
+ f"- **Search Engine:** {search_config.get('engine', 'Unknown')}"
+ )
+ context_parts.append(
+ f"- **Max Results:** {search_config.get('max_results', 'Unknown')}"
+ )
+
# Add any error codes or HTTP status
if "status_code" in partial_results:
- context_parts.append(f"- **Status Code:** {partial_results['status_code']}")
-
+ context_parts.append(
+ f"- **Status Code:** {partial_results['status_code']}"
+ )
+
if "error_code" in partial_results:
- context_parts.append(f"- **Error Code:** {partial_results['error_code']}")
-
+ context_parts.append(
+ f"- **Error Code:** {partial_results['error_code']}"
+ )
+
# Add error-specific context based on category
category = error_analysis.get("category")
if category:
if "connection" in category.value.lower():
- context_parts.append(f"- **Network Error:** Connection-related issue detected")
- context_parts.append(f"- **Retry Recommended:** Check service status and try again")
+ context_parts.append(
+ "- **Network Error:** Connection-related issue detected"
+ )
+ context_parts.append(
+ "- **Retry Recommended:** Check service status and try again"
+ )
elif "model" in category.value.lower():
- context_parts.append(f"- **Model Error:** Issue with AI model or configuration")
- context_parts.append(f"- **Check:** Model service availability and parameters")
-
+ context_parts.append(
+ "- **Model Error:** Issue with AI model or configuration"
+ )
+ context_parts.append(
+ "- **Check:** Model service availability and parameters"
+ )
+
return "\n".join(context_parts) if context_parts else ""
-
- def generate_quick_error_summary(self, error_message: str) -> Dict[str, str]:
+
+ def generate_quick_error_summary(
+ self, error_message: str
+ ) -> Dict[str, str]:
"""
Generate a quick error summary for API responses
-
+
Args:
error_message: The error message
-
+
Returns:
dict: Quick error summary
"""
error_analysis = self.error_reporter.analyze_error(error_message)
-
+
return {
"title": error_analysis["title"],
"category": error_analysis["category"].value,
"severity": error_analysis["severity"],
- "recoverable": error_analysis["recoverable"]
+ "recoverable": error_analysis["recoverable"],
}
-
+
def _make_error_user_friendly(self, error_message: str) -> str:
"""
Replace cryptic technical error messages with user-friendly versions
-
+
Args:
error_message: The original technical error message
-
+
Returns:
str: User-friendly error message, or original if no replacement found
"""
@@ -242,14 +296,15 @@ We're here to help you get this working:
),
"POST predict.*EOF": (
"Lost connection to Ollama. This usually means Ollama stopped responding or there's a network issue. Try restarting Ollama or checking if it's still running."
- )
+ ),
}
-
+
# Check each pattern and replace if found
for pattern, replacement in error_replacements.items():
import re
+
if re.search(pattern, error_message, re.IGNORECASE):
return f"{replacement}\n\nTechnical error: {error_message}"
-
+
# If no specific replacement found, return original message
- return error_message
\ No newline at end of file
+ return error_message
diff --git a/src/local_deep_research/web/services/research_service.py b/src/local_deep_research/web/services/research_service.py
index 2202ec6073..39e59200fb 100644
--- a/src/local_deep_research/web/services/research_service.py
+++ b/src/local_deep_research/web/services/research_service.py
@@ -659,16 +659,22 @@ def run_research_process(
try:
# Check if we have an error in the findings and use enhanced error handling
- if isinstance(raw_formatted_findings, str) and raw_formatted_findings.startswith("Error:"):
- logger.info("Generating enhanced error report using ErrorReportGenerator")
-
+ if isinstance(
+ raw_formatted_findings, str
+ ) and raw_formatted_findings.startswith("Error:"):
+ logger.info(
+ "Generating enhanced error report using ErrorReportGenerator"
+ )
+
# Get LLM for error explanation if available
try:
llm = get_llm(research_id=research_id)
except Exception:
llm = None
- logger.warning("Could not get LLM for error explanation")
-
+ logger.warning(
+ "Could not get LLM for error explanation"
+ )
+
# Generate comprehensive error report
error_generator = ErrorReportGenerator(llm)
clean_markdown = error_generator.generate_error_report(
@@ -676,10 +682,13 @@ def run_research_process(
query=query,
partial_results=results,
search_iterations=results.get("iterations", 0),
- research_id=research_id
+ research_id=research_id,
+ )
+
+ logger.info(
+ "Generated enhanced error report with %d characters",
+ len(clean_markdown),
)
-
- logger.info("Generated enhanced error report with %d characters", len(clean_markdown))
else:
# Get the synthesized content from the LLM directly
clean_markdown = raw_formatted_findings
@@ -910,12 +919,16 @@ def run_research_process(
llm = get_llm(research_id=research_id)
except Exception:
llm = None
- logger.warning("Could not get LLM for error explanation in failure handler")
-
+ logger.warning(
+ "Could not get LLM for error explanation in failure handler"
+ )
+
# Get partial results if they exist
- partial_results = results if 'results' in locals() else None
- search_iterations = results.get("iterations", 0) if partial_results else 0
-
+ partial_results = results if "results" in locals() else None
+ search_iterations = (
+ results.get("iterations", 0) if partial_results else 0
+ )
+
# Generate comprehensive error report
error_generator = ErrorReportGenerator(llm)
enhanced_report_content = error_generator.generate_error_report(
@@ -923,31 +936,43 @@ def run_research_process(
query=query,
partial_results=partial_results,
search_iterations=search_iterations,
- research_id=research_id
+ research_id=research_id,
+ )
+
+ logger.info(
+ "Generated enhanced error report for failed research (length: %d)",
+ len(enhanced_report_content),
)
-
- logger.info("Generated enhanced error report for failed research (length: %d)", len(enhanced_report_content))
-
+
# Save enhanced error report as the actual report file
try:
- reports_folder = get_reports_folder()
+ reports_folder = OUTPUT_DIR
report_filename = f"research_{research_id}_error_report.md"
report_path = reports_folder / report_filename
-
+
with open(report_path, "w", encoding="utf-8") as f:
f.write(enhanced_report_content)
-
- logger.info("Saved enhanced error report to: %s", report_path)
-
+
+ logger.info(
+ "Saved enhanced error report to: %s", report_path
+ )
+
# Store the report path so it can be retrieved later
- report_path_to_save = str(report_path.relative_to(reports_folder.parent))
-
+ report_path_to_save = str(
+ report_path.relative_to(reports_folder.parent)
+ )
+
except Exception as report_error:
- logger.exception("Failed to save enhanced error report: %s", report_error)
+ logger.exception(
+ "Failed to save enhanced error report: %s", report_error
+ )
report_path_to_save = None
-
+
except Exception as error_gen_error:
- logger.exception("Failed to generate enhanced error report: %s", error_gen_error)
+ logger.exception(
+ "Failed to generate enhanced error report: %s",
+ error_gen_error,
+ )
enhanced_report_content = None
report_path_to_save = None
@@ -1008,9 +1033,9 @@ def run_research_process(
research.completed_at = completed_at
research.duration_seconds = duration_seconds
research.metadata = metadata
-
+
# Add error report path if available
- if 'report_path_to_save' in locals() and report_path_to_save:
+ if "report_path_to_save" in locals() and report_path_to_save:
research.report_path = report_path_to_save
db_session.commit()
diff --git a/tests/accessibility_tests/README.md b/tests/accessibility_tests/README.md
index f1461c8101..cb4003dcfe 100644
--- a/tests/accessibility_tests/README.md
+++ b/tests/accessibility_tests/README.md
@@ -206,4 +206,4 @@ When adding new UI features:
- [WCAG 2.1 Guidelines](https://www.w3.org/WAI/WCAG21/quickref/)
- [ARIA Authoring Practices Guide](https://www.w3.org/WAI/ARIA/apg/)
- [Playwright Accessibility Testing](https://playwright.dev/docs/accessibility-testing)
-- [axe-core Documentation](https://github.com/dequelabs/axe-core)
\ No newline at end of file
+- [axe-core Documentation](https://github.com/dequelabs/axe-core)
diff --git a/tests/accessibility_tests/__init__.py b/tests/accessibility_tests/__init__.py
index 127f06b784..6dc78a9e38 100644
--- a/tests/accessibility_tests/__init__.py
+++ b/tests/accessibility_tests/__init__.py
@@ -1 +1 @@
-# Accessibility Tests Module
\ No newline at end of file
+# Accessibility Tests Module
diff --git a/tests/accessibility_tests/test_accessibility.js b/tests/accessibility_tests/test_accessibility.js
index 63a1b03678..e056ba7287 100644
--- a/tests/accessibility_tests/test_accessibility.js
+++ b/tests/accessibility_tests/test_accessibility.js
@@ -9,7 +9,7 @@ test.describe('Research Form Accessibility', () => {
test.beforeEach(async ({ page }) => {
// Navigate to the research page
await page.goto('/research/');
-
+
// Wait for the page to load completely
await page.waitForLoadState('networkidle');
});
@@ -22,17 +22,17 @@ test.describe('Research Form Accessibility', () => {
// Check that each radio button has a proper ID and label
const quickRadio = await page.locator('#mode-quick');
const detailedRadio = await page.locator('#mode-detailed');
-
+
await expect(quickRadio).toBeVisible();
await expect(detailedRadio).toBeVisible();
-
+
// Check that labels are properly associated
const quickLabel = await page.locator('label[for="mode-quick"]');
const detailedLabel = await page.locator('label[for="mode-detailed"]');
-
+
await expect(quickLabel).toBeVisible();
await expect(detailedLabel).toBeVisible();
-
+
// Check default selection
await expect(quickRadio).toBeChecked();
await expect(detailedRadio).not.toBeChecked();
@@ -41,19 +41,19 @@ test.describe('Research Form Accessibility', () => {
test('mode selection should be accessible via keyboard', async ({ page }) => {
const quickLabel = await page.locator('label[for="mode-quick"]');
const detailedLabel = await page.locator('label[for="mode-detailed"]');
-
+
// Focus on quick mode first
await quickLabel.focus();
-
+
// Check initial state
await expect(quickLabel).toBeFocused();
await expect(await page.locator('#mode-quick')).toBeChecked();
-
+
// Navigate to detailed mode with arrow keys
await page.keyboard.press('ArrowRight');
await expect(detailedLabel).toBeFocused();
await expect(await page.locator('#mode-detailed')).toBeChecked();
-
+
// Navigate back with arrow keys
await page.keyboard.press('ArrowLeft');
await expect(quickLabel).toBeFocused();
@@ -62,14 +62,14 @@ test.describe('Research Form Accessibility', () => {
test('mode selection should respond to Enter and Space keys', async ({ page }) => {
const detailedLabel = await page.locator('label[for="mode-detailed"]');
-
+
// Focus on detailed mode
await detailedLabel.focus();
-
+
// Press Enter to select
await page.keyboard.press('Enter');
await expect(await page.locator('#mode-detailed')).toBeChecked();
-
+
// Focus back to quick mode and test Space key
const quickLabel = await page.locator('label[for="mode-quick"]');
await quickLabel.focus();
@@ -81,11 +81,11 @@ test.describe('Research Form Accessibility', () => {
// Check for fieldset and legend elements
const fieldset = await page.locator('fieldset');
const legend = await page.locator('legend');
-
+
await expect(fieldset).toBeVisible();
await expect(legend).toBeVisible();
await expect(legend).toHaveText('Research Mode');
-
+
// Check that radiogroup role is present
const radioGroup = await page.locator('[role="radiogroup"]');
await expect(radioGroup).toBeVisible();
@@ -93,17 +93,17 @@ test.describe('Research Form Accessibility', () => {
test('keyboard shortcuts should work in textarea', async ({ page }) => {
const textarea = await page.locator('#query');
-
+
// Focus on textarea
await textarea.focus();
-
+
// Type some text
await textarea.fill('Test research query');
-
+
// Test Shift+Enter for new line
await page.keyboard.press('Shift+Enter');
await textarea.type('Second line');
-
+
// Check that text contains newline
const textValue = await textarea.inputValue();
expect(textValue).toContain('\n');
@@ -114,11 +114,11 @@ test.describe('Research Form Accessibility', () => {
test('Enter key should submit form from textarea', async ({ page }) => {
const textarea = await page.locator('#query');
const startButton = await page.locator('#start-research-btn');
-
+
// Focus on textarea
await textarea.focus();
await textarea.fill('Test query for submission');
-
+
// Mock the form submission to avoid actual API call
await page.route('/research/api/start_research', (route) => {
route.fulfill({
@@ -127,10 +127,10 @@ test.describe('Research Form Accessibility', () => {
body: JSON.stringify({ status: 'success', research_id: 'test-123' })
});
});
-
+
// Press Enter to submit
await page.keyboard.press('Enter');
-
+
// Check that button shows loading state
await expect(startButton).toHaveText(/Starting.../);
});
@@ -138,7 +138,7 @@ test.describe('Research Form Accessibility', () => {
test('keyboard hints should be visible', async ({ page }) => {
const keyboardHint = await page.locator('.keyboard-hint');
const hintText = await page.locator('.hint-text');
-
+
await expect(keyboardHint).toBeVisible();
await expect(hintText).toBeVisible();
await expect(hintText).toHaveText('Press Enter to search • Shift+Enter for new line');
@@ -148,19 +148,19 @@ test.describe('Research Form Accessibility', () => {
// Check ARIA attributes on mode options
const quickLabel = await page.locator('label[for="mode-quick"]');
const detailedLabel = await page.locator('label[for="mode-detailed"]');
-
+
// Check role attributes
await expect(quickLabel).toHaveAttribute('role', 'radio');
await expect(detailedLabel).toHaveAttribute('role', 'radio');
-
+
// Check aria-checked attributes
await expect(quickLabel).toHaveAttribute('aria-checked', 'true');
await expect(detailedLabel).toHaveAttribute('aria-checked', 'false');
-
+
// Check tabindex attributes
await expect(quickLabel).toHaveAttribute('tabindex', '0');
await expect(detailedLabel).toHaveAttribute('tabindex', '-1');
-
+
// Check that icons have aria-hidden
const icons = await page.locator('.mode-icon i');
for (let i = 0; i < await icons.count(); i++) {
@@ -172,14 +172,14 @@ test.describe('Research Form Accessibility', () => {
const detailedLabel = await page.locator('label[for="mode-detailed"]');
const detailedRadio = await page.locator('#mode-detailed');
const quickRadio = await page.locator('#mode-quick');
-
+
// Click on detailed mode
await detailedLabel.click();
-
+
// Check that radio button state is updated
await expect(detailedRadio).toBeChecked();
await expect(quickRadio).not.toBeChecked();
-
+
// Check visual state is updated
await expect(detailedLabel).toHaveClass(/active/);
await expect(detailedLabel).toHaveAttribute('aria-checked', 'true');
@@ -189,22 +189,22 @@ test.describe('Research Form Accessibility', () => {
// Start from textarea
const textarea = await page.locator('#query');
await textarea.focus();
-
+
// Tab to mode selection
await page.keyboard.press('Tab');
const quickLabel = await page.locator('label[for="mode-quick"]');
await expect(quickLabel).toBeFocused();
-
+
// Tab through advanced options toggle
await page.keyboard.press('Tab');
const advancedToggle = await page.locator('.advanced-options-toggle');
await expect(advancedToggle).toBeFocused();
-
+
// Tab to notification toggle
await page.keyboard.press('Tab');
const notificationToggle = await page.locator('#notification-toggle');
await expect(notificationToggle).toBeFocused();
-
+
// Tab to submit button
await page.keyboard.press('Tab');
const submitButton = await page.locator('#start-research-btn');
@@ -213,18 +213,18 @@ test.describe('Research Form Accessibility', () => {
test('screen reader only elements should be properly hidden', async ({ page }) => {
const radioButtons = await page.locator('input[name="research_mode"]');
-
+
// Check that radio buttons have sr-only class
for (let i = 0; i < await radioButtons.count(); i++) {
await expect(radioButtons.nth(i)).toHaveClass(/sr-only/);
}
-
+
// Check that sr-only elements are visually hidden but accessible
const srOnlyStyle = await page.evaluate(() => {
const element = document.querySelector('.sr-only');
return window.getComputedStyle(element);
});
-
+
expect(srOnlyStyle.position).toBe('absolute');
expect(srOnlyStyle.width).toBe('1px');
expect(srOnlyStyle.height).toBe('1px');
@@ -232,13 +232,13 @@ test.describe('Research Form Accessibility', () => {
test('form submission should use radio button values', async ({ page }) => {
const detailedLabel = await page.locator('label[for="mode-detailed"]');
-
+
// Select detailed mode
await detailedLabel.click();
-
+
// Fill in required fields
await page.locator('#query').fill('Test query');
-
+
// Mock the API to capture the form data
let capturedData = null;
await page.route('/research/api/start_research', (route) => {
@@ -249,13 +249,13 @@ test.describe('Research Form Accessibility', () => {
body: JSON.stringify({ status: 'success', research_id: 'test-123' })
});
});
-
+
// Submit the form
await page.locator('#start-research-btn').click();
-
+
// Wait for the API call
await page.waitForTimeout(1000);
-
+
// Check that the correct mode was sent
expect(capturedData.mode).toBe('detailed');
});
@@ -265,12 +265,12 @@ test.describe('Accessibility Compliance', () => {
test('page should not have accessibility violations', async ({ page }) => {
await page.goto('/research/');
await page.waitForLoadState('networkidle');
-
+
// Inject axe-core for accessibility testing
- await page.addScriptTag({
- url: 'https://unpkg.com/[email protected]/axe.min.js'
+ await page.addScriptTag({
+ url: 'https://unpkg.com/[email protected]/axe.min.js'
});
-
+
// Run accessibility scan
const results = await page.evaluate(() => {
return new Promise((resolve) => {
@@ -287,7 +287,7 @@ test.describe('Accessibility Compliance', () => {
});
});
});
-
+
// Check for violations
if (results.violations.length > 0) {
console.log('Accessibility violations found:');
@@ -298,9 +298,9 @@ test.describe('Accessibility Compliance', () => {
});
});
}
-
+
// Expect no critical violations
- const criticalViolations = results.violations.filter(v =>
+ const criticalViolations = results.violations.filter(v =>
v.impact === 'critical' || v.impact === 'serious'
);
expect(criticalViolations).toHaveLength(0);
@@ -308,7 +308,7 @@ test.describe('Accessibility Compliance', () => {
test('focus should be visible and logical', async ({ page }) => {
await page.goto('/research/');
-
+
// Test that focus is visible on all interactive elements
const interactiveElements = [
'#query',
@@ -318,10 +318,10 @@ test.describe('Accessibility Compliance', () => {
'#notification-toggle',
'#start-research-btn'
];
-
+
for (const selector of interactiveElements) {
await page.locator(selector).focus();
-
+
// Check that focus is visible (outline or box-shadow)
const element = await page.locator(selector);
const styles = await element.evaluate(el => {
@@ -332,13 +332,13 @@ test.describe('Accessibility Compliance', () => {
outlineOffset: computed.outlineOffset
};
});
-
+
// Should have either outline or box-shadow for focus
- const hasFocusStyle = styles.outline !== 'none' ||
+ const hasFocusStyle = styles.outline !== 'none' ||
styles.boxShadow !== 'none' ||
styles.outlineOffset !== '0px';
-
+
expect(hasFocusStyle).toBe(true);
}
});
-});
\ No newline at end of file
+});
diff --git a/tests/accessibility_tests/test_accessibility_backend.py b/tests/accessibility_tests/test_accessibility_backend.py
index 27ad0425f0..e6de605ed2 100644
--- a/tests/accessibility_tests/test_accessibility_backend.py
+++ b/tests/accessibility_tests/test_accessibility_backend.py
@@ -12,235 +12,290 @@ from urllib.parse import urljoin
class TestHTMLAccessibility:
"""Test HTML structure for accessibility compliance"""
-
+
@pytest.fixture
def research_page_html(self, base_url):
"""Fetch the research page HTML"""
- response = requests.get(urljoin(base_url, '/research/'))
+ response = requests.get(urljoin(base_url, "/research/"))
response.raise_for_status()
- return BeautifulSoup(response.content, 'html.parser')
-
+ return BeautifulSoup(response.content, "html.parser")
+
def test_form_has_proper_labels(self, research_page_html):
"""Test that all form inputs have proper labels"""
soup = research_page_html
-
+
# Find all input elements that should have labels
- inputs = soup.find_all(['input', 'textarea', 'select'])
-
+ inputs = soup.find_all(["input", "textarea", "select"])
+
for input_element in inputs:
- input_id = input_element.get('id')
- input_type = input_element.get('type', 'text')
-
+ input_id = input_element.get("id")
+ input_type = input_element.get("type", "text")
+
# Skip hidden inputs and buttons
- if input_type in ['hidden', 'submit', 'button']:
+ if input_type in ["hidden", "submit", "button"]:
continue
-
+
# Check for associated label
if input_id:
- label = soup.find('label', {'for': input_id})
- assert label is not None, f"Input with id '{input_id}' missing associated label"
-
+ label = soup.find("label", {"for": input_id})
+ assert label is not None, (
+ f"Input with id '{input_id}' missing associated label"
+ )
+
def test_radio_button_structure(self, research_page_html):
"""Test that radio buttons are properly structured"""
soup = research_page_html
-
+
# Find radio button group
- radio_inputs = soup.find_all('input', {'name': 'research_mode'})
- assert len(radio_inputs) == 2, "Should have exactly 2 research mode radio buttons"
-
+ radio_inputs = soup.find_all("input", {"name": "research_mode"})
+ assert len(radio_inputs) == 2, (
+ "Should have exactly 2 research mode radio buttons"
+ )
+
# Check that radio buttons have proper IDs and labels
- expected_modes = ['quick', 'detailed']
+ expected_modes = ["quick", "detailed"]
for mode in expected_modes:
- radio = soup.find('input', {'id': f'mode-{mode}'})
+ radio = soup.find("input", {"id": f"mode-{mode}"})
assert radio is not None, f"Missing radio button for {mode} mode"
- assert radio.get('type') == 'radio', f"Input for {mode} mode should be type='radio'"
- assert radio.get('name') == 'research_mode', f"Radio button should have name='research_mode'"
-
+ assert radio.get("type") == "radio", (
+ f"Input for {mode} mode should be type='radio'"
+ )
+ assert radio.get("name") == "research_mode", (
+ "Radio button should have name='research_mode'"
+ )
+
# Check associated label
- label = soup.find('label', {'for': f'mode-{mode}'})
- assert label is not None, f"Missing label for {mode} mode radio button"
- assert 'mode-option' in label.get('class', []), f"Label should have mode-option class"
-
+ label = soup.find("label", {"for": f"mode-{mode}"})
+ assert label is not None, (
+ f"Missing label for {mode} mode radio button"
+ )
+ assert "mode-option" in label.get("class", []), (
+ "Label should have mode-option class"
+ )
+
def test_fieldset_and_legend(self, research_page_html):
"""Test that radio button group has proper fieldset and legend"""
soup = research_page_html
-
- fieldset = soup.find('fieldset')
- assert fieldset is not None, "Radio button group should be wrapped in fieldset"
-
- legend = fieldset.find('legend')
+
+ fieldset = soup.find("fieldset")
+ assert fieldset is not None, (
+ "Radio button group should be wrapped in fieldset"
+ )
+
+ legend = fieldset.find("legend")
assert legend is not None, "Fieldset should have a legend"
- assert 'Research Mode' in legend.get_text(), "Legend should describe the radio button group"
-
+ assert "Research Mode" in legend.get_text(), (
+ "Legend should describe the radio button group"
+ )
+
def test_aria_attributes(self, research_page_html):
"""Test that ARIA attributes are properly set"""
soup = research_page_html
-
+
# Check radiogroup role
- radiogroup = soup.find(attrs={'role': 'radiogroup'})
- assert radiogroup is not None, "Should have element with role='radiogroup'"
-
+ radiogroup = soup.find(attrs={"role": "radiogroup"})
+ assert radiogroup is not None, (
+ "Should have element with role='radiogroup'"
+ )
+
# Check radio labels have proper ARIA attributes
- radio_labels = soup.find_all('label', class_='mode-option')
+ radio_labels = soup.find_all("label", class_="mode-option")
assert len(radio_labels) >= 2, "Should have at least 2 radio labels"
-
+
for label in radio_labels:
- assert label.get('role') == 'radio', "Label should have role='radio'"
- assert 'aria-checked' in label.attrs, "Label should have aria-checked attribute"
- assert 'tabindex' in label.attrs, "Label should have tabindex attribute"
-
+ assert label.get("role") == "radio", (
+ "Label should have role='radio'"
+ )
+ assert "aria-checked" in label.attrs, (
+ "Label should have aria-checked attribute"
+ )
+ assert "tabindex" in label.attrs, (
+ "Label should have tabindex attribute"
+ )
+
# Check that one radio is initially checked
- checked_labels = [l for l in radio_labels if l.get('aria-checked') == 'true']
- assert len(checked_labels) == 1, "Exactly one radio should be initially checked"
-
+ checked_labels = [
+ label
+ for label in radio_labels
+ if label.get("aria-checked") == "true"
+ ]
+ assert len(checked_labels) == 1, (
+ "Exactly one radio should be initially checked"
+ )
+
def test_screen_reader_only_class(self, research_page_html):
"""Test that radio inputs have screen reader only class"""
soup = research_page_html
-
- radio_inputs = soup.find_all('input', {'name': 'research_mode'})
+
+ radio_inputs = soup.find_all("input", {"name": "research_mode"})
for radio in radio_inputs:
- classes = radio.get('class', [])
- assert 'sr-only' in classes, "Radio inputs should have sr-only class"
-
+ classes = radio.get("class", [])
+ assert "sr-only" in classes, (
+ "Radio inputs should have sr-only class"
+ )
+
def test_keyboard_hints_present(self, research_page_html):
"""Test that keyboard hint text is present"""
soup = research_page_html
-
- hint_container = soup.find(class_='keyboard-hint')
+
+ hint_container = soup.find(class_="keyboard-hint")
assert hint_container is not None, "Should have keyboard hint container"
-
- hint_text = hint_container.find(class_='hint-text')
+
+ hint_text = hint_container.find(class_="hint-text")
assert hint_text is not None, "Should have hint text element"
-
+
hint_content = hint_text.get_text()
- assert 'Enter to search' in hint_content, "Should mention Enter key"
- assert 'Shift+Enter for new line' in hint_content, "Should mention Shift+Enter for new line"
-
+ assert "Enter to search" in hint_content, "Should mention Enter key"
+ assert "Shift+Enter for new line" in hint_content, (
+ "Should mention Shift+Enter for new line"
+ )
+
def test_icons_have_aria_hidden(self, research_page_html):
"""Test that decorative icons have aria-hidden attribute"""
soup = research_page_html
-
+
# Find icons in mode options
- mode_icons = soup.find_all(class_='mode-icon')
+ mode_icons = soup.find_all(class_="mode-icon")
for icon_container in mode_icons:
- icon = icon_container.find('i')
+ icon = icon_container.find("i")
if icon:
- assert icon.get('aria-hidden') == 'true', "Decorative icons should have aria-hidden='true'"
-
+ assert icon.get("aria-hidden") == "true", (
+ "Decorative icons should have aria-hidden='true'"
+ )
+
def test_form_structure(self, research_page_html):
"""Test overall form structure and accessibility"""
soup = research_page_html
-
+
# Find the main form
- form = soup.find('form', {'id': 'research-form'})
+ form = soup.find("form", {"id": "research-form"})
assert form is not None, "Should have main research form"
-
+
# Check that form has proper method (should be handled by JS)
# Form should not have action attribute as it's handled by JavaScript
- assert form.get('action') is None, "Form should not have action attribute (handled by JS)"
-
+ assert form.get("action") is None, (
+ "Form should not have action attribute (handled by JS)"
+ )
+
def test_heading_structure(self, research_page_html):
"""Test that headings follow proper hierarchy"""
soup = research_page_html
-
+
# Find all headings
- headings = soup.find_all(re.compile(r'^h[1-6]$'))
-
+ headings = soup.find_all(re.compile(r"^h[1-6]$"))
+
if headings:
# Check that we start with h1 or h2 (allowing for page structure)
first_heading_level = int(headings[0].name[1])
assert first_heading_level <= 2, "First heading should be h1 or h2"
-
+
# Check for logical progression (no skipping levels)
prev_level = first_heading_level
for heading in headings[1:]:
current_level = int(heading.name[1])
# Level can stay same, go up by 1, or go down any amount
if current_level > prev_level:
- assert current_level <= prev_level + 1, f"Heading level jumped from h{prev_level} to h{current_level}"
+ assert current_level <= prev_level + 1, (
+ f"Heading level jumped from h{prev_level} to h{current_level}"
+ )
prev_level = current_level
-
+
def test_semantic_markup(self, research_page_html):
"""Test that semantic HTML elements are used appropriately"""
soup = research_page_html
-
+
# Check for semantic landmarks
- main_content = soup.find(['main', 'div'], class_=re.compile(r'(content|main)'))
+ main_content = soup.find(
+ ["main", "div"], class_=re.compile(r"(content|main)")
+ )
assert main_content is not None, "Should have main content area"
-
+
# Check that buttons are actually button elements
- submit_button = soup.find('button', {'id': 'start-research-btn'})
+ submit_button = soup.find("button", {"id": "start-research-btn"})
assert submit_button is not None, "Submit should be a button element"
- assert submit_button.get('type') == 'submit', "Submit button should have type='submit'"
-
+ assert submit_button.get("type") == "submit", (
+ "Submit button should have type='submit'"
+ )
+
def test_required_fields_marked(self, research_page_html):
"""Test that required fields are properly marked"""
soup = research_page_html
-
+
# The query textarea should be required (if it has required attribute)
- query_field = soup.find('textarea', {'id': 'query'})
+ query_field = soup.find("textarea", {"id": "query"})
assert query_field is not None, "Should have query textarea"
-
+
# If required attribute is present, it should be properly marked
- if query_field.get('required'):
+ if query_field.get("required"):
# Should have aria-required or required attribute
- assert query_field.get('aria-required') == 'true' or query_field.has_attr('required'), \
+ assert query_field.get(
+ "aria-required"
+ ) == "true" or query_field.has_attr("required"), (
"Required fields should be marked with aria-required or required attribute"
-
+ )
+
def test_error_handling_structure(self, research_page_html):
"""Test that error display areas are properly structured"""
soup = research_page_html
-
+
# Check for alert container
- alert_container = soup.find('div', {'id': 'research-alert'})
- assert alert_container is not None, "Should have alert container for error messages"
-
+ alert_container = soup.find("div", {"id": "research-alert"})
+ assert alert_container is not None, (
+ "Should have alert container for error messages"
+ )
+
# Container should have proper ARIA role or be ready for dynamic content
# When alerts are shown, they should have role="alert" or aria-live region
class TestAccessibilityConfiguration:
"""Test accessibility-related configuration and setup"""
-
+
def test_html_lang_attribute(self, base_url):
"""Test that HTML has proper lang attribute"""
- response = requests.get(urljoin(base_url, '/research/'))
+ response = requests.get(urljoin(base_url, "/research/"))
response.raise_for_status()
- soup = BeautifulSoup(response.content, 'html.parser')
-
- html_element = soup.find('html')
+ soup = BeautifulSoup(response.content, "html.parser")
+
+ html_element = soup.find("html")
assert html_element is not None, "Should have html element"
-
- lang = html_element.get('lang')
+
+ lang = html_element.get("lang")
assert lang is not None, "HTML element should have lang attribute"
- assert lang.startswith('en'), "Language should be English (en)"
-
+ assert lang.startswith("en"), "Language should be English (en)"
+
def test_viewport_meta_tag(self, base_url):
"""Test that viewport meta tag is present for mobile accessibility"""
- response = requests.get(urljoin(base_url, '/research/'))
+ response = requests.get(urljoin(base_url, "/research/"))
response.raise_for_status()
- soup = BeautifulSoup(response.content, 'html.parser')
-
- viewport_meta = soup.find('meta', {'name': 'viewport'})
+ soup = BeautifulSoup(response.content, "html.parser")
+
+ viewport_meta = soup.find("meta", {"name": "viewport"})
assert viewport_meta is not None, "Should have viewport meta tag"
-
- content = viewport_meta.get('content', '')
- assert 'width=device-width' in content, "Viewport should include width=device-width"
- assert 'initial-scale=1' in content, "Viewport should include initial-scale=1"
-
+
+ content = viewport_meta.get("content", "")
+ assert "width=device-width" in content, (
+ "Viewport should include width=device-width"
+ )
+ assert "initial-scale=1" in content, (
+ "Viewport should include initial-scale=1"
+ )
+
def test_css_focus_styles(self, base_url):
"""Test that CSS includes focus styles (basic check)"""
# This is a basic test - ideally we'd parse CSS files
# For now, we just check that custom CSS files are loaded
- response = requests.get(urljoin(base_url, '/research/'))
+ response = requests.get(urljoin(base_url, "/research/"))
response.raise_for_status()
- soup = BeautifulSoup(response.content, 'html.parser')
-
- css_links = soup.find_all('link', {'rel': 'stylesheet'})
- css_hrefs = [link.get('href', '') for link in css_links]
-
+ soup = BeautifulSoup(response.content, "html.parser")
+
+ css_links = soup.find_all("link", {"rel": "stylesheet"})
+ css_hrefs = [link.get("href", "") for link in css_links]
+
# Check that our custom CSS file is loaded
- custom_css_loaded = any('custom_dropdown.css' in href for href in css_hrefs)
+ custom_css_loaded = any(
+ "custom_dropdown.css" in href for href in css_hrefs
+ )
assert custom_css_loaded, "Custom dropdown CSS should be loaded"
@@ -249,8 +304,9 @@ def base_url():
"""Base URL for the application"""
# This should be configured based on your test environment
import os
- return os.getenv('TEST_BASE_URL', 'http://localhost:5000')
+
+ return os.getenv("TEST_BASE_URL", "http://localhost:5000")
-if __name__ == '__main__':
- pytest.main([__file__, '-v'])
\ No newline at end of file
+if __name__ == "__main__":
+ pytest.main([__file__, "-v"])