File size: 5,356 Bytes
eab1374
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
#!/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!")