๐Ÿ” Code Extractor

function test_upload_modalities

Maturity: 51

Integration test function that validates FileCloud upload functionality by testing both new file creation and existing file update scenarios.

File:
/tf/active/vicechatdev/SPFCsync/test_upload_modalities.py
Lines:
37 - 228
Complexity:
moderate

Purpose

This test function comprehensively validates FileCloud's file upload capabilities by performing two critical operations: (1) uploading a completely new file to verify creation functionality, and (2) updating an existing file to verify replacement/versioning functionality. It creates test files locally, uploads them to FileCloud, verifies the uploads, and provides detailed console output for debugging. The function is designed for integration testing and validation of FileCloud client operations.

Source Code

def test_upload_modalities():
    """Test both new file upload and file update scenarios"""
    
    print("๐Ÿงช Testing Upload Modalities")
    print("=" * 60)
    
    # Initialize clients
    print("๐Ÿ”— Connecting to FileCloud...")
    fc_client = FileCloudClient(
        server_url=Config.FILECLOUD_SERVER_URL,
        username=Config.FILECLOUD_USERNAME,
        password=Config.FILECLOUD_PASSWORD
    )
    
    # Test file paths in FileCloud - use new test folder structure
    test_base_path = f"{Config.FILECLOUD_BASE_PATH}/TEST_UPLOADS"
    new_file_path = f"{test_base_path}/new_test_file.txt"
    existing_file_path = f"{test_base_path}/existing_test_file.txt"
    
    print(f"๐Ÿ“‚ Test base path: {test_base_path}")
    print(f"๐Ÿ†• New file path: {new_file_path}")
    print(f"๐Ÿ”„ Existing file path: {existing_file_path}")
    
    try:
        # Test folder creation capability
        print(f"\n๐Ÿ“ Testing folder creation: {test_base_path}")
        folder_created = fc_client.create_folder(test_base_path)
        if folder_created:
            print("โœ… Folder creation successful")
        else:
            print("โš ๏ธ Folder creation failed, but continuing (may already exist)")
        
        # Test 1: Upload completely new file
        print(f"\n" + "="*60)
        print("๐Ÿงช TEST 1: Upload New File")
        print("="*60)
        
        # Check if new file already exists (shouldn't)
        print(f"๐Ÿ” Checking if new file exists: {new_file_path}")
        new_file_info = fc_client.get_file_info(new_file_path)
        
        if new_file_info:
            print(f"๐Ÿ—‘๏ธ  Removing existing test file: {new_file_path}")
            fc_client.delete_file(new_file_path)
            new_file_info = fc_client.get_file_info(new_file_path)
        
        if not new_file_info:
            print("โœ… New file doesn't exist - perfect for testing new upload")
            
            # Create test file
            test_content_1 = f"New test file created at {datetime.now(timezone.utc)}\nThis is test content for a NEW file upload."
            local_file_1 = create_test_file(test_content_1, "new_test_file.txt")
            
            print(f"๐Ÿ“„ Created local test file: {local_file_1}")
            print(f"๐Ÿ“ File size: {format_file_size(os.path.getsize(local_file_1))}")
            
            # Read file content and get modification time
            with open(local_file_1, 'rb') as f:
                file_content_1 = f.read()
            
            file_mod_time_1 = datetime.fromtimestamp(os.path.getmtime(local_file_1), tz=timezone.utc)
            
            # Upload new file
            print(f"โฌ†๏ธ  Uploading new file to: {new_file_path}")
            upload_result_1 = fc_client.upload_file(file_content_1, new_file_path, file_mod_time_1)
            
            if upload_result_1:
                print("โœ… NEW FILE UPLOAD: SUCCESS")
                
                # Verify upload
                uploaded_info = fc_client.get_file_info(new_file_path)
                if uploaded_info:
                    print(f"   ๐Ÿ“„ File name: {uploaded_info['name']}")
                    print(f"   ๐Ÿ“ File size: {format_file_size(uploaded_info['size'])}")
                    print(f"   ๐Ÿ“… Modified: {uploaded_info['lastmodified']}")
                else:
                    print("โŒ Error: Could not verify uploaded file")
            else:
                print("โŒ NEW FILE UPLOAD: FAILED")
            
            # Cleanup
            os.unlink(local_file_1)
            os.rmdir(os.path.dirname(local_file_1))
        
        # Test 2: Update existing file
        print(f"\n" + "="*60)
        print("๐Ÿงช TEST 2: Upload New Version (Update)")
        print("="*60)
        
        # First, ensure we have an existing file to update
        existing_file_info = fc_client.get_file_info(existing_file_path)
        
        if not existing_file_info:
            print(f"๐Ÿ“ Creating initial file for update test: {existing_file_path}")
            initial_content = f"Initial file created at {datetime.now(timezone.utc)}\nThis will be updated in the test."
            initial_file = create_test_file(initial_content, "existing_test_file.txt")
            
            # Read initial file content
            with open(initial_file, 'rb') as f:
                initial_file_content = f.read()
            
            initial_mod_time = datetime.fromtimestamp(os.path.getmtime(initial_file), tz=timezone.utc)
            
            upload_initial = fc_client.upload_file(initial_file_content, existing_file_path, initial_mod_time)
            if upload_initial:
                print("โœ… Initial file created successfully")
                existing_file_info = fc_client.get_file_info(existing_file_path)
            else:
                print("โŒ Failed to create initial file")
                return
            
            os.unlink(initial_file)
            os.rmdir(os.path.dirname(initial_file))
        
        if existing_file_info:
            print("โœ… Existing file found - perfect for testing update")
            print(f"   ๐Ÿ“„ Current name: {existing_file_info['name']}")
            print(f"   ๐Ÿ“ Current size: {format_file_size(existing_file_info['size'])}")
            print(f"   ๐Ÿ“… Current modified: {existing_file_info['lastmodified']}")
            
            # Create updated test file
            test_content_2 = f"UPDATED test file at {datetime.now(timezone.utc)}\nThis is NEW content for an EXISTING file.\nPrevious version was replaced."
            local_file_2 = create_test_file(test_content_2, "existing_test_file.txt")
            
            print(f"๐Ÿ“„ Created updated test file: {local_file_2}")
            print(f"๐Ÿ“ New file size: {format_file_size(os.path.getsize(local_file_2))}")
            
            # Read updated file content
            with open(local_file_2, 'rb') as f:
                file_content_2 = f.read()
            
            file_mod_time_2 = datetime.fromtimestamp(os.path.getmtime(local_file_2), tz=timezone.utc)
            
            # Upload updated file (should replace existing)
            print(f"โฌ†๏ธ  Uploading updated file to: {existing_file_path}")
            upload_result_2 = fc_client.upload_file(file_content_2, existing_file_path, file_mod_time_2)
            
            if upload_result_2:
                print("โœ… FILE UPDATE: SUCCESS")
                
                # Verify update
                updated_info = fc_client.get_file_info(existing_file_path)
                if updated_info:
                    print(f"   ๐Ÿ“„ File name: {updated_info['name']}")
                    print(f"   ๐Ÿ“ New size: {format_file_size(updated_info['size'])}")
                    print(f"   ๐Ÿ“… New modified: {updated_info['lastmodified']}")
                    
                    # Compare with previous version
                    if updated_info['size'] != existing_file_info['size']:
                        print("โœ… File size changed - update confirmed")
                    if updated_info['lastmodified'] != existing_file_info['lastmodified']:
                        print("โœ… Modification time changed - update confirmed")
                else:
                    print("โŒ Error: Could not verify updated file")
            else:
                print("โŒ FILE UPDATE: FAILED")
            
            # Cleanup
            os.unlink(local_file_2)
            os.rmdir(os.path.dirname(local_file_2))
        
        # Summary
        print(f"\n" + "="*60)
        print("๐Ÿ“‹ UPLOAD MODALITIES TEST SUMMARY")
        print("="*60)
        
        # Check final state
        final_new_info = fc_client.get_file_info(new_file_path)
        final_existing_info = fc_client.get_file_info(existing_file_path)
        
        print(f"๐Ÿ†• New file test:")
        if final_new_info:
            print(f"   โœ… SUCCESS - File exists: {final_new_info['name']}")
            print(f"      Size: {format_file_size(final_new_info['size'])}")
        else:
            print(f"   โŒ FAILED - New file not found")
        
        print(f"๐Ÿ”„ Update file test:")
        if final_existing_info:
            print(f"   โœ… SUCCESS - File exists: {final_existing_info['name']}")
            print(f"      Size: {format_file_size(final_existing_info['size'])}")
        else:
            print(f"   โŒ FAILED - Updated file not found")
        
        print(f"\n๐Ÿ’ก Both upload modalities tested successfully!")
        print(f"๐Ÿงน Test files remain in: {test_base_path}")
        print(f"   You can manually verify or delete them from FileCloud")
        
    except Exception as e:
        print(f"โŒ Error during upload modality test: {e}")
        import traceback
        traceback.print_exc()

Return Value

This function does not return any value (implicitly returns None). It performs side effects including console output, file system operations, and FileCloud API interactions. Success or failure is communicated through printed messages and exception handling.

Dependencies

  • os
  • sys
  • tempfile
  • datetime
  • traceback

Required Imports

import os
import sys
import tempfile
from datetime import datetime, timezone
from config import Config
from sharepoint_graph_client import SharePointGraphClient
from filecloud_client import FileCloudClient
import traceback

Usage Example

# Ensure config.py has required FileCloud settings:
# FILECLOUD_SERVER_URL = 'https://your-filecloud.com'
# FILECLOUD_USERNAME = 'your_username'
# FILECLOUD_PASSWORD = 'your_password'
# FILECLOUD_BASE_PATH = '/path/to/base'

# Ensure helper functions are defined:
def create_test_file(content, filename):
    temp_dir = tempfile.mkdtemp()
    file_path = os.path.join(temp_dir, filename)
    with open(file_path, 'w') as f:
        f.write(content)
    return file_path

def format_file_size(size_bytes):
    for unit in ['B', 'KB', 'MB', 'GB']:
        if size_bytes < 1024.0:
            return f"{size_bytes:.2f} {unit}"
        size_bytes /= 1024.0
    return f"{size_bytes:.2f} TB"

# Run the test
test_upload_modalities()

# Expected output:
# - Console output showing test progress
# - Two test files created in FileCloud under TEST_UPLOADS folder
# - Verification of both new file upload and file update operations

Best Practices

  • This is a test function that creates files in FileCloud - ensure you have proper cleanup procedures or use a test environment
  • The function leaves test files in FileCloud after execution for manual verification - implement cleanup if needed
  • Requires valid FileCloud credentials and proper network connectivity to function
  • Uses UTC timezone for all timestamp operations to ensure consistency
  • Creates temporary local files during testing - these are cleaned up automatically
  • Test folder path is hardcoded as TEST_UPLOADS under the base path - modify if needed for your environment
  • Exception handling prints full stack traces for debugging - consider logging to files in production
  • The function performs destructive operations (delete_file) - ensure test paths don't overlap with production data
  • File modification times are preserved during upload for accurate versioning
  • Consider running this test in isolation or as part of a test suite with proper setup/teardown

Similar Components

AI-powered semantic similarity - components with related functionality:

  • function test_filecloud_operations 70.1% similar

    Tests FileCloud basic operations by creating a test folder to verify connectivity and authentication with a FileCloud server.

    From: /tf/active/vicechatdev/SPFCsync/test_connections.py
  • function test_multiple_file_upload 67.0% similar

    A test function that validates multiple file upload functionality to a Flask application endpoint by sending a transcript file and multiple previous report files.

    From: /tf/active/vicechatdev/leexi/test_flask_upload.py
  • function test_filecloud_connection 66.4% similar

    Tests the connection to a FileCloud server by establishing a client connection and performing a document search operation to verify functionality.

    From: /tf/active/vicechatdev/contract_validity_analyzer/test_implementation.py
  • function test_filecloud_connection_v1 65.4% similar

    Tests the connection to a FileCloud server by attempting to instantiate a FileCloudClient with credentials from configuration.

    From: /tf/active/vicechatdev/SPFCsync/test_connections.py
  • function test_filecloud_integration 63.3% similar

    Integration test function that verifies the SharePoint Graph API client works correctly with FileCloud synchronization service by creating a sync service instance and testing document retrieval.

    From: /tf/active/vicechatdev/SPFCsync/test_graph_client.py
โ† Back to Browse