šŸ” Code Extractor

function test_placeholder_parsing

Maturity: 44

A unit test function that validates the placeholder parsing functionality of the HybridResponseHandler class by testing its ability to extract and parse graphic placeholders from formatted text.

File:
/tf/active/vicechatdev/e-ink-llm/test_hybrid_mode.py
Lines:
87 - 117
Complexity:
simple

Purpose

This test function verifies that the HybridResponseHandler can correctly identify and parse graphic placeholders embedded in text using the format [GRAPHIC:type:description:json_config]. It tests the _parse_hybrid_response method's ability to extract multiple placeholders with different graphic types (chart, diagram) and their associated metadata, ensuring the parsing logic works as expected for hybrid text-graphic content generation.

Source Code

def test_placeholder_parsing():
    """Test placeholder parsing functionality"""
    print("\nšŸ“ Testing placeholder parsing...")
    
    try:
        from hybrid_response_handler import HybridResponseHandler
        
        handler = HybridResponseHandler(api_key="test")
        
        sample_text = """
        Here is some text with graphics:
        [GRAPHIC:chart:Test Chart:{"type":"bar","data":[1,2,3],"labels":["A","B","C"]}]
        More text here.
        [GRAPHIC:diagram:Test Flow:{"steps":["Start","End"],"style":"flowchart"}]
        """
        
        hybrid_response = handler._parse_hybrid_response(sample_text, {})
        
        if len(hybrid_response.placeholders) == 2:
            print(f"āœ… Parsed {len(hybrid_response.placeholders)} placeholders correctly")
            for placeholder in hybrid_response.placeholders:
                print(f"   • {placeholder.graphic_type}: {placeholder.description}")
        else:
            print(f"āŒ Expected 2 placeholders, found {len(hybrid_response.placeholders)}")
            return False
            
    except Exception as e:
        print(f"āŒ Placeholder parsing failed: {e}")
        return False
    
    return True

Return Value

Returns a boolean value: True if the test passes (2 placeholders are successfully parsed from the sample text), False if the test fails (wrong number of placeholders parsed or an exception occurs). The function also prints test results to stdout with emoji indicators for visual feedback.

Dependencies

  • matplotlib
  • numpy
  • networkx
  • hybrid_response_handler
  • graphics_generator
  • hybrid_pdf_generator

Required Imports

import matplotlib.pyplot as plt
import numpy as np
import networkx as nx
from graphics_generator import GraphicsGenerator
from graphics_generator import GraphicSpec
from graphics_generator import GraphicType
from hybrid_response_handler import HybridResponseHandler
from hybrid_pdf_generator import HybridPDFGenerator

Conditional/Optional Imports

These imports are only needed under specific conditions:

from hybrid_response_handler import HybridResponseHandler

Condition: imported inside try block during test execution

Required (conditional)

Usage Example

# Run the test function directly
result = test_placeholder_parsing()
if result:
    print("Test passed successfully")
else:
    print("Test failed")

# Or as part of a test suite
if __name__ == '__main__':
    test_results = []
    test_results.append(test_placeholder_parsing())
    print(f"\nTests passed: {sum(test_results)}/{len(test_results)}")

Best Practices

  • This is a test function and should be run in a testing environment, not in production code
  • The function uses a dummy API key ('test') which is appropriate for testing but won't work for actual API calls
  • The test expects exactly 2 placeholders in the sample text - modifying the sample text requires updating the assertion
  • The function prints results to stdout for visibility during test execution
  • Error handling is implemented with try-except to catch and report parsing failures gracefully
  • The test validates both the count and structure of parsed placeholders
  • Sample text uses the specific format [GRAPHIC:type:description:json_config] which must match the parser's expected format

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function demo_placeholder_parsing 84.5% similar

    Demonstrates the parsing of graphics placeholders embedded in text by extracting and displaying placeholder metadata including type, description, ID, and parameters.

    From: /tf/active/vicechatdev/e-ink-llm/demo_hybrid_mode.py
  • function demo_hybrid_response 63.2% similar

    Demonstrates end-to-end hybrid response processing by converting an LLM response containing text and graphics placeholders into a formatted PDF document.

    From: /tf/active/vicechatdev/e-ink-llm/demo_hybrid_mode.py
  • function test_markdown_processing 61.3% similar

    A test function that validates markdown processing capabilities by testing content parsing, element extraction, and HTML conversion functionality.

    From: /tf/active/vicechatdev/vice_ai/test_markdown.py
  • function test_template_with_data 59.7% similar

    Tests a template file by replacing placeholders with test data and validates that all required placeholders have been filled, excluding known conditional placeholders.

    From: /tf/active/vicechatdev/test_comprehensive_templates.py
  • class HybridResponseHandler 59.4% similar

    Orchestrates the complete workflow for generating hybrid PDF documents that combine LLM text responses with dynamically generated graphics (charts, diagrams, illustrations).

    From: /tf/active/vicechatdev/e-ink-llm/hybrid_response_handler.py
← Back to Browse