🔍 Code Extractor

function test_template_with_data

Maturity: 45

Tests a template file by replacing placeholders with provided 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's particularly useful for validating Jinja2-style templates while intelligently filtering out conditional statements and known optional placeholders. The function provides clear console feedback with checkmarks or X marks indicating success or failure.

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 representing the file system path to the template file to be tested. Must be a valid path to a readable text file with UTF-8 encoding. Example: 'templates/email_template.html'

test_data: Dictionary containing key-value pairs where keys are placeholder names (without curly braces) and values are the data to replace those placeholders. Keys should match placeholder names in the template. Example: {'user_name': 'John', 'email': 'john@example.com'}

template_name: String identifier for the template being tested, used in console output messages for identification purposes. This is a human-readable name for logging. Example: 'Email Notification Template'

Return Value

Returns a boolean value: True if all core placeholders were successfully filled and no unexpected unfilled placeholders remain (excluding known conditional placeholders like '{{ step }}', '{{ instructions }}', '{{ comment_location }}', '{{ review_uid }}'). Returns False if there are unfilled placeholders or if an exception occurs during template processing. Also prints status messages to console with emoji indicators (✅ for success, ❌ for failure).

Dependencies

  • re
  • os

Required Imports

import re

Usage Example

import re

# Define test data
test_data = {
    'user_name': 'Alice Smith',
    'project_name': 'Data Pipeline',
    'date': '2024-01-15'
}

# Test the template
template_path = 'templates/notification.txt'
template_name = 'User Notification Template'

result = test_template_with_data(
    template_path=template_path,
    test_data=test_data,
    template_name=template_name
)

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

Best Practices

  • Ensure the template file exists and is readable before calling this function
  • Use consistent placeholder naming conventions matching the format '{{ placeholder_name }}' with spaces around the placeholder name
  • Provide all required placeholders in test_data dictionary to avoid false negatives
  • Be aware that this function uses simple string replacement, not full Jinja2 rendering, so complex template logic won't be evaluated
  • The function skips validation for known conditional placeholders: 'step', 'instructions', 'comment_location', and 'review_uid' - adjust this list if your templates use different optional placeholders
  • Consider wrapping calls to this function in a test suite for automated template validation
  • The function prints to console directly, so redirect stdout if you need to capture output programmatically

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function main_v4 63.1% 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 55.7% 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 test_web_ui 45.5% similar

    Integration test function that validates a Flask web UI for meeting minutes generation by testing file upload, generation, and regeneration endpoints with sample transcript and PowerPoint files.

    From: /tf/active/vicechatdev/leexi/test_ui.py
  • function check_fixes 44.3% similar

    A diagnostic function that prints a comprehensive summary report of email notification fixes implemented in a CDocs system, verifying template files and documenting debugging enhancements.

    From: /tf/active/vicechatdev/fix_summary.py
  • function create_test_file 43.3% similar

    Creates a temporary test file with specified content and filename in a temporary directory.

    From: /tf/active/vicechatdev/SPFCsync/test_upload_modalities.py
← Back to Browse