function test_upload_modalities
Integration test function that validates FileCloud upload functionality by testing both new file creation and existing file update scenarios.
/tf/active/vicechatdev/SPFCsync/test_upload_modalities.py
37 - 228
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
ossystempfiledatetimetraceback
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
Tags
Similar Components
AI-powered semantic similarity - components with related functionality:
-
function test_filecloud_operations 70.2% similar
-
function test_multiple_file_upload 67.0% similar
-
function test_filecloud_connection 65.1% similar
-
function test_filecloud_integration 63.4% similar
-
function test_acl_functions 60.7% similar