🔍 Code Extractor

function test_template_with_data

Maturity: 45

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

File:
/tf/active/vicechatdev/test_comprehensive_templates.py
Lines:
10 - 43
Complexity:
moderate

Purpose

This function is designed for template validation in testing scenarios. It reads a template file, performs simple placeholder replacement using provided test data, and checks for any remaining unfilled placeholders. It intelligently filters out Jinja2 conditionals and known acceptable placeholders that may be optional, reporting success or failure with detailed feedback about any missing data.

Source Code

def test_template_with_data(template_path, test_data, template_name):
    """Test a template with given data and check for unfilled placeholders."""
    try:
        with open(template_path, 'r', encoding='utf-8') as f:
            template_content = f.read()
        
        # Simple placeholder replacement
        rendered_content = template_content
        for key, value in test_data.items():
            placeholder = f"{{{{ {key} }}}}"
            rendered_content = rendered_content.replace(placeholder, str(value))
        
        # Check for any remaining unreplaced placeholders
        remaining_placeholders = re.findall(r'{{[^}]*}}', rendered_content)
        
        # Filter out Jinja2 conditionals and known acceptable placeholders
        actual_unfilled = []
        for placeholder in remaining_placeholders:
            # Skip Jinja2 conditionals like {% if %}, {% endif %}, etc.
            if not placeholder.startswith('{{%') and not placeholder.endswith('%}}'):
                # Skip known conditional placeholders that might not be provided
                if placeholder not in ['{{ step }}', '{{ instructions }}', '{{ comment_location }}', '{{ review_uid }}']:
                    actual_unfilled.append(placeholder)
        
        if actual_unfilled:
            print(f"❌ {template_name}: Unfilled placeholders: {actual_unfilled}")
            return False
        else:
            print(f"✅ {template_name}: All core placeholders filled correctly")
            return True
            
    except Exception as e:
        print(f"❌ {template_name}: Error testing template: {e}")
        return False

Parameters

Name Type Default Kind
template_path - - positional_or_keyword
test_data - - positional_or_keyword
template_name - - positional_or_keyword

Parameter Details

template_path: String path to the template file to be tested. Must be a valid file path with read permissions. The file should contain placeholders in the format '{{ placeholder_name }}'.

test_data: Dictionary containing key-value pairs where keys are placeholder names (without braces) and values are the data to replace them with. Values will be converted to strings during replacement.

template_name: String identifier for the template being tested, used in console output messages to identify which template is being validated. This is for logging/reporting purposes only.

Return Value

Returns a boolean value: True if all core placeholders were successfully filled (or only acceptable optional placeholders remain), False if there are unfilled required placeholders or if an error occurred during processing. The function also prints status messages to console with ✅ for success or ❌ for failure.

Dependencies

  • re
  • os

Required Imports

import re

Usage Example

import re

# Create a test template file
with open('test_template.txt', 'w', encoding='utf-8') as f:
    f.write('Hello {{ name }}, your age is {{ age }}. {{ step }}')

# Define test data
test_data = {
    'name': 'John Doe',
    'age': 30
}

# Test the template
result = test_template_with_data(
    template_path='test_template.txt',
    test_data=test_data,
    template_name='greeting_template'
)

if result:
    print('Template validation passed')
else:
    print('Template validation failed')

Best Practices

  • Ensure template files are UTF-8 encoded to avoid encoding errors
  • The function uses simple string replacement, not full Jinja2 rendering, so complex Jinja2 syntax may not be properly handled
  • Known acceptable placeholders (step, instructions, comment_location, review_uid) are hardcoded and will not trigger validation failures
  • Provide comprehensive test_data dictionaries to catch all required placeholders during testing
  • Use descriptive template_name values for easier debugging when multiple templates are tested
  • The function prints to console, so consider redirecting output if running in automated test suites
  • Handle the boolean return value to integrate with test frameworks or CI/CD pipelines

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function render_template 64.6% similar

    Renders a template string by replacing placeholders with data values and processing conditional blocks (if/endif tags).

    From: /tf/active/vicechatdev/CDocs/utils/notifications.py
  • function main_v29 60.3% similar

    A test function that validates email template rendering by testing multiple HTML email templates with sample data structures for document review and approval workflows.

    From: /tf/active/vicechatdev/test_comprehensive_templates.py
  • function test_fixes 54.8% similar

    A comprehensive test function that validates email template rendering and CDocs application link presence in a document management system's email notification templates.

    From: /tf/active/vicechatdev/test_comprehensive_fixes.py
  • function generate_document_from_template 48.9% similar

    Generates a document from a template by populating it with provided data, returning the document content as bytes or None if generation fails.

    From: /tf/active/vicechatdev/CDocs/utils/document_processor.py
  • function create_test_file 48.5% similar

    Creates a temporary text file with predefined multi-chapter test content for testing document extraction and processing functionality.

    From: /tf/active/vicechatdev/vice_ai/test_extraction_debug.py
← Back to Browse