🔍 Code Extractor

class ValidationResult

Maturity: 47

A container class for storing and managing validation results, including errors, warnings, and field-specific issues.

File:
/tf/active/vicechatdev/invoice_extraction/validators/base_validator.py
Lines:
9 - 60
Complexity:
simple

Purpose

ValidationResult provides a structured way to collect and report validation outcomes. It tracks whether validation passed, accumulates error messages and warnings, and maintains a mapping of field-specific issues. The class is designed to be used in validation workflows where multiple checks need to be performed and their results aggregated before determining overall validity.

Source Code

class ValidationResult:
    """
    Container for validation results with issues and warnings.
    """
    
    def __init__(self):
        self.is_valid = True
        self.issues = []
        self.warnings = []
        self.field_issues = {}
    
    def add_issue(self, field: str, message: str, severity: str = 'error') -> None:
        """
        Add a validation issue.
        
        Args:
            field: The field with the validation issue
            message: Description of the issue
            severity: 'error' or 'warning'
        """
        if severity == 'error':
            self.is_valid = False
            self.issues.append(f"{field}: {message}")
            self.field_issues[field] = message
        else:
            self.warnings.append(f"{field}: {message}")
            
    def __str__(self) -> str:
        """String representation of validation results."""
        result = []
        if not self.is_valid:
            result.append("INVALID: The following issues were found:")
            for issue in self.issues:
                result.append(f"- {issue}")
        else:
            result.append("VALID: No critical issues found.")
            
        if self.warnings:
            result.append("\nWarnings:")
            for warning in self.warnings:
                result.append(f"- {warning}")
                
        return "\n".join(result)
    
    def as_dict(self) -> Dict[str, Any]:
        """Convert validation result to a dictionary."""
        return {
            'is_valid': self.is_valid,
            'issues': self.issues,
            'warnings': self.warnings,
            'field_issues': self.field_issues
        }

Parameters

Name Type Default Kind
bases - -

Parameter Details

__init__: No parameters required. Initializes an empty ValidationResult with is_valid=True, empty lists for issues and warnings, and an empty dictionary for field_issues.

Return Value

Instantiation returns a ValidationResult object. The add_issue method returns None (modifies state in-place). The __str__ method returns a formatted string representation of validation results. The as_dict method returns a dictionary with keys 'is_valid' (bool), 'issues' (list), 'warnings' (list), and 'field_issues' (dict).

Class Interface

Methods

__init__(self) -> None

Purpose: Initialize a new ValidationResult with default empty state

Returns: None - initializes instance attributes

add_issue(self, field: str, message: str, severity: str = 'error') -> None

Purpose: Add a validation issue or warning to the result

Parameters:

  • field: The name of the field that has the validation issue
  • message: A descriptive message explaining the validation problem
  • severity: Either 'error' (fails validation, default) or 'warning' (does not fail validation)

Returns: None - modifies instance state by adding to issues/warnings lists and field_issues dict, and potentially setting is_valid to False

__str__(self) -> str

Purpose: Generate a human-readable string representation of the validation results

Returns: A formatted multi-line string showing validation status, issues, and warnings

as_dict(self) -> Dict[str, Any]

Purpose: Convert the validation result to a dictionary for serialization or structured access

Returns: Dictionary with keys 'is_valid' (bool), 'issues' (list of strings), 'warnings' (list of strings), and 'field_issues' (dict mapping field names to error messages)

Attributes

Name Type Description Scope
is_valid bool Indicates whether validation passed (True) or failed (False). Set to False when any error-severity issue is added. instance
issues List[str] List of error messages in the format 'field: message'. Only contains error-severity issues. instance
warnings List[str] List of warning messages in the format 'field: message'. Contains only warning-severity issues that don't fail validation. instance
field_issues Dict[str, str] Dictionary mapping field names to their error messages. Only contains error-severity issues, not warnings. instance

Dependencies

  • typing

Required Imports

from typing import Dict
from typing import Any

Usage Example

# Create a validation result object
result = ValidationResult()

# Add validation issues
result.add_issue('email', 'Invalid email format', severity='error')
result.add_issue('age', 'Age should be positive', severity='error')
result.add_issue('phone', 'Phone number format is unusual', severity='warning')

# Check if validation passed
if result.is_valid:
    print('Validation passed')
else:
    print('Validation failed')

# Print formatted results
print(result)

# Get results as dictionary
result_dict = result.as_dict()
print(f"Valid: {result_dict['is_valid']}")
print(f"Issues: {result_dict['issues']}")
print(f"Warnings: {result_dict['warnings']}")
print(f"Field issues: {result_dict['field_issues']}")

Best Practices

  • Create a new ValidationResult instance for each validation operation to avoid state pollution
  • Use severity='error' for critical issues that should fail validation, and severity='warning' for non-critical issues
  • The is_valid flag is automatically set to False when any error-level issue is added
  • Access field_issues dictionary to get specific error messages for individual fields
  • Use as_dict() method when you need to serialize validation results (e.g., for JSON responses)
  • The __str__ method provides human-readable output suitable for logging or display
  • Once is_valid is set to False by an error, it cannot be reset to True without creating a new instance
  • Warnings do not affect the is_valid status

Similar Components

AI-powered semantic similarity - components with related functionality:

  • class TestValidationResult 72.4% similar

    A unittest.TestCase class that provides comprehensive test coverage for the ValidationResult class, testing initialization, issue addition, string representation, and dictionary conversion.

    From: /tf/active/vicechatdev/invoice_extraction/tests/test_validators.py
  • class EditingWorkflowResult 56.9% similar

    A dataclass that encapsulates the results from an editing workflow process, including detected annotations, confidence scores, recommendations, and optional rewritten content.

    From: /tf/active/vicechatdev/e-ink-llm/editing_workflow.py
  • class AnalysisResult 53.1% similar

    A dataclass that encapsulates the results from statistical analysis operations, including metadata, file paths, and timestamps.

    From: /tf/active/vicechatdev/vice_ai/smartstat_models.py
  • class AnalysisResult_v1 53.1% similar

    A dataclass that encapsulates the results from statistical analysis operations, including metadata, file paths, and timestamps.

    From: /tf/active/vicechatdev/vice_ai/models.py
  • class IterationResult 52.4% similar

    A dataclass that encapsulates the complete results of a single iteration in a two-pass process, including table selection, SQL generation, and execution outcomes.

    From: /tf/active/vicechatdev/full_smartstat/two_pass_sql_workflow.py
← Back to Browse