Spaces:
Running
Running
File size: 12,347 Bytes
d66ab65 |
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 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 |
"""
Unit tests for FileService
"""
import pytest
import os
import tempfile
from unittest.mock import Mock, patch, mock_open
from werkzeug.datastructures import FileStorage
from io import BytesIO
from app.services.file_service import FileService
class TestFileService:
"""Test cases for FileService."""
def setup_method(self):
"""Set up test fixtures."""
self.service = FileService()
def test_is_allowed_file_valid_extensions(self):
"""Test allowed file extension checking."""
# Valid extensions
assert self.service.is_allowed_file('test.txt') is True
assert self.service.is_allowed_file('document.md') is True
assert self.service.is_allowed_file('script.py') is True
assert self.service.is_allowed_file('code.js') is True
assert self.service.is_allowed_file('data.json') is True
assert self.service.is_allowed_file('styles.css') is True
assert self.service.is_allowed_file('page.html') is True
assert self.service.is_allowed_file('data.csv') is True
assert self.service.is_allowed_file('app.log') is True
def test_is_allowed_file_invalid_extensions(self):
"""Test invalid file extensions."""
# Invalid extensions
assert self.service.is_allowed_file('virus.exe') is False
assert self.service.is_allowed_file('archive.zip') is False
assert self.service.is_allowed_file('image.jpg') is False
assert self.service.is_allowed_file('document.pdf') is False
assert self.service.is_allowed_file('data.xlsx') is False
def test_is_allowed_file_edge_cases(self):
"""Test edge cases for file extension checking."""
# Empty filename
assert self.service.is_allowed_file('') is False
assert self.service.is_allowed_file(None) is False
# No extension
assert self.service.is_allowed_file('filename') is False
# Multiple dots
assert self.service.is_allowed_file('file.backup.txt') is True
# Case sensitivity
assert self.service.is_allowed_file('FILE.TXT') is True
assert self.service.is_allowed_file('Document.MD') is True
def test_generate_secure_filename_basic(self):
"""Test basic secure filename generation."""
filename = self.service.generate_secure_filename('test.txt')
assert filename.endswith('_test.txt')
assert len(filename) > len('test.txt') # Should have UUID prefix
# Should be different each time
filename2 = self.service.generate_secure_filename('test.txt')
assert filename != filename2
def test_generate_secure_filename_special_characters(self):
"""Test secure filename with special characters."""
# Test filename with spaces and special chars
filename = self.service.generate_secure_filename('my file name.txt')
assert 'my_file_name.txt' in filename
# Test with path separators (should be removed)
filename = self.service.generate_secure_filename('../../../etc/passwd')
assert '..' not in filename
assert '/' not in filename
assert '\\' not in filename
def test_generate_secure_filename_empty_input(self):
"""Test secure filename generation with empty input."""
filename = self.service.generate_secure_filename('')
assert filename.endswith('.txt')
assert len(filename) > 4 # Should have UUID
filename = self.service.generate_secure_filename(None)
assert filename.endswith('.txt')
assert len(filename) > 4
@patch('os.makedirs')
def test_save_uploaded_file_basic(self, mock_makedirs, temp_file):
"""Test basic file upload saving."""
# Create a mock uploaded file
file_content = b"Hello world!"
uploaded_file = FileStorage(
stream=BytesIO(file_content),
filename='test.txt',
content_type='text/plain'
)
upload_folder = '/tmp/test_uploads'
with patch('builtins.open', mock_open()) as mock_file:
file_path = self.service.save_uploaded_file(uploaded_file, upload_folder)
# Check that directory creation was attempted
mock_makedirs.assert_called_once_with(upload_folder, exist_ok=True)
# Check that file path has correct structure
assert file_path.startswith(upload_folder)
assert file_path.endswith('_test.txt')
def test_cleanup_file_existing(self, temp_file):
"""Test cleanup of existing file."""
# Verify file exists
assert os.path.exists(temp_file)
# Cleanup
self.service.cleanup_file(temp_file)
# Verify file is deleted
assert not os.path.exists(temp_file)
def test_cleanup_file_nonexistent(self):
"""Test cleanup of non-existent file (should not raise error)."""
# Should not raise an exception
self.service.cleanup_file('/path/that/does/not/exist.txt')
@patch('app.services.file_service.tokenizer_service')
@patch('app.services.file_service.stats_service')
def test_process_file_for_tokenization_basic(self, mock_stats, mock_tokenizer, temp_file):
"""Test basic file processing for tokenization."""
# Mock tokenizer service
mock_tokenizer_obj = Mock()
mock_tokenizer_obj.tokenize.return_value = ['Hello', ' world', '!']
mock_tokenizer.load_tokenizer.return_value = (mock_tokenizer_obj, {}, None)
# Mock stats service
mock_stats.get_token_stats.return_value = {
'basic_stats': {'total_tokens': 3},
'length_stats': {'avg_length': '2.0'}
}
mock_stats.format_tokens_for_display.return_value = [
{'display': 'Hello', 'original': 'Hello', 'token_id': 1, 'colors': {}, 'newline': False}
]
result = self.service.process_file_for_tokenization(
file_path=temp_file,
model_id_or_name='gpt2',
preview_char_limit=1000,
max_display_tokens=100,
chunk_size=1024
)
assert isinstance(result, dict)
assert 'tokens' in result
assert 'stats' in result
assert 'display_limit_reached' in result
assert 'total_tokens' in result
assert 'preview_only' in result
assert 'tokenizer_info' in result
@patch('app.services.file_service.tokenizer_service')
def test_process_file_tokenizer_error(self, mock_tokenizer, temp_file):
"""Test file processing with tokenizer error."""
# Mock tokenizer service to return error
mock_tokenizer.load_tokenizer.return_value = (None, {}, "Tokenizer error")
with pytest.raises(Exception) as excinfo:
self.service.process_file_for_tokenization(
file_path=temp_file,
model_id_or_name='invalid-model',
preview_char_limit=1000,
max_display_tokens=100
)
assert "Tokenizer error" in str(excinfo.value)
@patch('app.services.file_service.tokenizer_service')
@patch('app.services.file_service.stats_service')
def test_process_text_for_tokenization_basic(self, mock_stats, mock_tokenizer):
"""Test basic text processing for tokenization."""
# Mock tokenizer service
mock_tokenizer_obj = Mock()
mock_tokenizer_obj.tokenize.return_value = ['Hello', ' world']
mock_tokenizer.load_tokenizer.return_value = (mock_tokenizer_obj, {'vocab_size': 1000}, None)
# Mock stats service
mock_stats.get_token_stats.return_value = {
'basic_stats': {'total_tokens': 2},
'length_stats': {'avg_length': '3.0'}
}
mock_stats.format_tokens_for_display.return_value = [
{'display': 'Hello', 'original': 'Hello', 'token_id': 1, 'colors': {}, 'newline': False},
{'display': ' world', 'original': ' world', 'token_id': 2, 'colors': {}, 'newline': False}
]
result = self.service.process_text_for_tokenization(
text="Hello world",
model_id_or_name='gpt2',
max_display_tokens=100
)
assert isinstance(result, dict)
assert 'tokens' in result
assert 'stats' in result
assert result['display_limit_reached'] is False
assert result['total_tokens'] == 2
assert result['tokenizer_info']['vocab_size'] == 1000
@patch('app.services.file_service.tokenizer_service')
@patch('app.services.file_service.stats_service')
def test_process_text_display_limit(self, mock_stats, mock_tokenizer):
"""Test text processing with display limit."""
# Create a large number of tokens
tokens = [f'token{i}' for i in range(200)]
# Mock tokenizer service
mock_tokenizer_obj = Mock()
mock_tokenizer_obj.tokenize.return_value = tokens
mock_tokenizer.load_tokenizer.return_value = (mock_tokenizer_obj, {}, None)
# Mock stats service
mock_stats.get_token_stats.return_value = {
'basic_stats': {'total_tokens': 200},
'length_stats': {'avg_length': '6.0'}
}
mock_stats.format_tokens_for_display.return_value = []
result = self.service.process_text_for_tokenization(
text="Long text",
model_id_or_name='gpt2',
max_display_tokens=100 # Limit lower than token count
)
assert result['display_limit_reached'] is True
assert result['total_tokens'] == 200
@patch('app.services.file_service.tokenizer_service')
def test_process_text_tokenizer_error(self, mock_tokenizer):
"""Test text processing with tokenizer error."""
# Mock tokenizer service to return error
mock_tokenizer.load_tokenizer.return_value = (None, {}, "Model not found")
with pytest.raises(Exception) as excinfo:
self.service.process_text_for_tokenization(
text="Hello world",
model_id_or_name='invalid-model'
)
assert "Model not found" in str(excinfo.value)
@patch('app.services.file_service.tokenizer_service')
@patch('app.services.file_service.stats_service')
def test_process_text_preview_mode(self, mock_stats, mock_tokenizer):
"""Test text processing in preview mode."""
long_text = "A" * 10000 # Long text
# Mock tokenizer service
mock_tokenizer_obj = Mock()
mock_tokenizer_obj.tokenize.return_value = ['A'] * 5000 # Many tokens
mock_tokenizer.load_tokenizer.return_value = (mock_tokenizer_obj, {}, None)
# Mock stats service
mock_stats.get_token_stats.return_value = {
'basic_stats': {'total_tokens': 5000},
'length_stats': {'avg_length': '1.0'}
}
mock_stats.format_tokens_for_display.return_value = []
result = self.service.process_text_for_tokenization(
text=long_text,
model_id_or_name='gpt2',
is_preview=True,
preview_char_limit=100
)
assert result['preview_only'] is True
def test_allowed_extensions_constant(self):
"""Test that ALLOWED_EXTENSIONS contains expected extensions."""
extensions = self.service.ALLOWED_EXTENSIONS
assert isinstance(extensions, set)
# Check for required extensions
required_extensions = {'.txt', '.md', '.py', '.js', '.json', '.html', '.css', '.csv', '.log'}
assert required_extensions.issubset(extensions)
# All extensions should start with dot
for ext in extensions:
assert ext.startswith('.')
assert len(ext) > 1 |