🔍 Code Extractor

function test_json_serialization

Maturity: 40

A test function that validates JSON serialization and deserialization of workflow data structures containing status, progress, and results information.

File:
/tf/active/vicechatdev/full_smartstat/test_enhanced_progress.py
Lines:
83 - 106
Complexity:
simple

Purpose

This function serves as a unit test to verify that workflow data dictionaries can be successfully serialized to JSON strings and deserialized back to Python objects. It tests the JSON encoding/decoding process with a sample workflow data structure containing nested dictionaries with status information, progress metrics, and final results. The function prints success or failure messages with diagnostic information, making it useful for debugging serialization issues in workflow management systems.

Source Code

def test_json_serialization():
    """Test that workflow data can be JSON serialized"""
    print("\n=== Testing JSON Serialization ===")
    
    try:
        workflow_data = {
            'status': 'completed',
            'progress': 100,
            'final_results': {
                'final_rows': 1000,
                'iterations_used': 1,
                'optimization_achieved': True
            }
        }
        
        json_str = json.dumps(workflow_data)
        parsed_data = json.loads(json_str)
        
        print("✅ JSON serialization working correctly")
        print(f"   JSON length: {len(json_str)} characters")
        print(f"   Parsed status: {parsed_data['status']}")
        
    except Exception as e:
        print(f"❌ JSON serialization failed: {str(e)}")

Return Value

This function does not return any value (implicitly returns None). It performs a test operation and prints results to stdout, including success/failure status, JSON string length, and parsed data verification.

Dependencies

  • json

Required Imports

import json

Usage Example

import json

def test_json_serialization():
    """Test that workflow data can be JSON serialized"""
    print("\n=== Testing JSON Serialization ===")
    
    try:
        workflow_data = {
            'status': 'completed',
            'progress': 100,
            'final_results': {
                'final_rows': 1000,
                'iterations_used': 1,
                'optimization_achieved': True
            }
        }
        
        json_str = json.dumps(workflow_data)
        parsed_data = json.loads(json_str)
        
        print("✅ JSON serialization working correctly")
        print(f"   JSON length: {len(json_str)} characters")
        print(f"   Parsed status: {parsed_data['status']}")
        
    except Exception as e:
        print(f"❌ JSON serialization failed: {str(e)}")

# Run the test
test_json_serialization()

Best Practices

  • This function is designed for testing purposes and should be used in development or CI/CD environments
  • The function prints output directly to stdout rather than using a logging framework, which is acceptable for simple tests but consider using proper logging for production code
  • The test uses a try-except block to catch serialization errors, which is good practice for test functions
  • Consider extending this test to validate the actual content of parsed_data matches the original workflow_data for more thorough testing
  • The function could be enhanced to return a boolean success/failure status for integration with test frameworks like pytest or unittest

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_workflow_progress_structure 66.3% similar

    A test function that validates the structure and behavior of a workflow progress tracking system for SQL query processing, including progress states, step transitions, and completion data.

    From: /tf/active/vicechatdev/full_smartstat/test_enhanced_progress.py
  • function test_enhanced_workflow 63.2% similar

    A comprehensive test function that validates the EnhancedSQLWorkflow system by testing component initialization, request parsing, and data assessment capabilities.

    From: /tf/active/vicechatdev/full_smartstat/test_enhanced_workflow.py
  • function test_result_type_compatibility 58.1% similar

    A test function that verifies result type compatibility between enhanced and standard workflows by comparing their result type strings.

    From: /tf/active/vicechatdev/full_smartstat/test_enhanced_data_loading.py
  • function clean_for_json 53.5% similar

    Recursively traverses and sanitizes Python data structures (dicts, lists, tuples, numpy arrays) to ensure all values are JSON-serializable by converting numpy types, handling NaN/Inf values, and normalizing data types.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/f0b81d95-24d9-418a-8d9f-1b241684e64c/project_1/analysis.py
  • function clean_for_json_v7 52.5% similar

    Recursively traverses and sanitizes data structures (dicts, lists, numpy types) to ensure JSON serialization compatibility by converting numpy types to native Python types and handling NaN/Inf values.

    From: /tf/active/vicechatdev/vice_ai/smartstat_scripts/d1e252f5-950c-4ad7-b425-86b4b02c3c62/analysis_1.py
← Back to Browse