simple-text-analyzer / test /test_file_upload_handler.py
egumasa's picture
emuTAALES
e7279e4
#!/usr/bin/env python3
"""
Test the FileUploadHandler functionality
"""
import os
import sys
from io import BytesIO
# Add parent directory to path
sys.path.append(os.path.dirname(__file__))
from web_app.utils import FileUploadHandler
def test_tmp_directory():
"""Test /tmp directory accessibility"""
print("Testing /tmp directory...")
if os.path.exists("/tmp"):
print("βœ… /tmp exists")
print(f" - Writable: {os.access('/tmp', os.W_OK)}")
print(f" - Readable: {os.access('/tmp', os.R_OK)}")
# Test write
try:
test_file = "/tmp/test_write.txt"
with open(test_file, 'w') as f:
f.write("test")
os.remove(test_file)
print(" - Write test: βœ… Success")
except Exception as e:
print(f" - Write test: ❌ Failed - {e}")
else:
print("❌ /tmp directory does not exist!")
def test_file_upload_handler():
"""Test FileUploadHandler with mock uploaded file"""
print("\nTesting FileUploadHandler...")
# Create mock uploaded file
content = b"word\tfreq\trank\nthe\t69868\t1\nof\t36426\t2\nand\t28891\t3"
mock_file = BytesIO(content)
mock_file.name = "test_data.tsv"
mock_file.type = "text/tab-separated-values"
mock_file.size = len(content)
# Add getbuffer method
mock_file.getbuffer = lambda: content
print(f"Mock file created: {mock_file.name} ({len(content)} bytes)")
# Test save to temp
print("\n1. Testing save_to_temp...")
temp_path = FileUploadHandler.save_to_temp(mock_file, prefix="test")
if temp_path:
print(f"βœ… Saved to: {temp_path}")
print(f" - File exists: {os.path.exists(temp_path)}")
print(f" - File size: {os.path.getsize(temp_path)} bytes")
else:
print("❌ Failed to save to temp")
return
# Test read from temp
print("\n2. Testing read_from_temp...")
read_content = FileUploadHandler.read_from_temp(temp_path)
if read_content:
print(f"βœ… Read content: {len(read_content)} bytes")
print(f" - Content matches: {read_content == content}")
print(f" - First line: {read_content.decode('utf-8').split('\\n')[0]}")
else:
print("❌ Failed to read from temp")
# Test get_file_content
print("\n3. Testing get_file_content...")
mock_file.seek(0) # Reset position
text_content = FileUploadHandler.get_file_content(mock_file, as_text=True)
if text_content:
print(f"βœ… Got text content: {len(text_content)} chars")
print(f" - First line: {text_content.split('\\n')[0]}")
else:
print("❌ Failed to get file content")
# Test cleanup
print("\n4. Testing cleanup_temp_file...")
FileUploadHandler.cleanup_temp_file(temp_path)
exists_after = os.path.exists(temp_path)
print(f"βœ… Cleanup: File removed = {not exists_after}")
# Test file size validation
print("\n5. Testing validate_file_size...")
mock_file.size = 100 * 1024 * 1024 # 100 MB
valid = FileUploadHandler.validate_file_size(mock_file, max_size_mb=300)
print(f"βœ… 100MB file validation: {valid}")
mock_file.size = 400 * 1024 * 1024 # 400 MB
valid = FileUploadHandler.validate_file_size(mock_file, max_size_mb=300)
print(f"βœ… 400MB file validation: {valid} (should be False)")
def test_with_actual_file():
"""Test with an actual file from the data directory"""
print("\n\nTesting with actual file...")
test_files = [
"data/word_freq.txt",
"data/COCA_5000.txt",
"data/jpn_word_freq.txt"
]
for file_path in test_files:
if os.path.exists(file_path):
print(f"\nTesting with {file_path}...")
# Read file content
with open(file_path, 'rb') as f:
content = f.read()
# Create mock uploaded file
mock_file = BytesIO(content)
mock_file.name = os.path.basename(file_path)
mock_file.type = "text/tab-separated-values"
mock_file.size = len(content)
mock_file.getbuffer = lambda: content
print(f" - File size: {len(content):,} bytes")
# Test the upload handler
temp_path = FileUploadHandler.save_to_temp(mock_file, prefix="actual")
if temp_path:
print(f" - βœ… Saved to temp: {temp_path}")
# Read back
read_content = FileUploadHandler.read_from_temp(temp_path)
if read_content:
print(f" - βœ… Read back: {len(read_content):,} bytes")
print(f" - βœ… Content matches: {read_content == content}")
# Cleanup
FileUploadHandler.cleanup_temp_file(temp_path)
print(f" - βœ… Cleaned up")
break # Test just one file
else:
print(f" - File not found: {file_path}")
if __name__ == "__main__":
print("=" * 60)
print("FileUploadHandler Test Suite")
print("=" * 60)
test_tmp_directory()
test_file_upload_handler()
test_with_actual_file()
print("\n" + "=" * 60)
print("Test completed!")