Spaces:
Running
on
Zero
Running
on
Zero
File size: 21,000 Bytes
7bdb8f6 |
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 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 |
"""Comprehensive tests for settings CSV upload functionality.
This module tests edge cases and error scenarios for the settings upload feature,
including:
- read_settings event handler behavior
- CSV format edge cases (empty, malformed, encoding issues)
- File object edge cases
- Error recovery scenarios
"""
import tempfile
from pathlib import Path
from unittest.mock import Mock, patch, MagicMock
import pandas as pd
import pytest
class TestReadSettingsHandler:
"""Test the read_settings event handler directly."""
def test_read_settings_with_none_returns_none(self):
"""Test read_settings handler logic returns None when file is None."""
# Test the handler logic directly
# Simulate the read_settings function from app.py
def read_settings(file):
if file is None:
return None
from mosaic.ui.utils import load_settings
df = load_settings(file.name if hasattr(file, "name") else file)
return df # In actual app, returns gr.Dataframe(df, visible=True)
result = read_settings(None)
assert result is None
def test_read_settings_with_file_object_with_name(self):
"""Test read_settings handles file object with .name attribute."""
from mosaic.ui.utils import load_settings
# Create temporary CSV
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
f.write("slide1.svs,Primary,Male,Unknown\n")
f.flush()
temp_path = f.name
try:
# Create mock file object with .name attribute
mock_file = Mock()
mock_file.name = temp_path
# Simulate read_settings handler
def read_settings(file):
if file is None:
return None
df = load_settings(file.name if hasattr(file, "name") else file)
return df
result = read_settings(mock_file)
# Verify DataFrame was loaded
assert isinstance(result, pd.DataFrame)
assert len(result) == 1
assert result["Slide"].iloc[0] == "slide1.svs"
finally:
Path(temp_path).unlink(missing_ok=True)
def test_read_settings_with_file_path_string(self):
"""Test read_settings handles direct file path string."""
from mosaic.ui.utils import load_settings
# Create temporary CSV
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
f.write("slide1.svs,Primary,Male,Unknown\n")
f.flush()
temp_path = f.name
try:
# Simulate read_settings handler with direct path
def read_settings(file):
if file is None:
return None
df = load_settings(file.name if hasattr(file, "name") else file)
return df
result = read_settings(temp_path)
# Verify DataFrame was loaded
assert isinstance(result, pd.DataFrame)
assert len(result) == 1
assert result["Slide"].iloc[0] == "slide1.svs"
finally:
Path(temp_path).unlink(missing_ok=True)
def test_read_settings_with_file_object_without_name_attribute(self):
"""Test read_settings handles file-like object without .name attribute."""
from mosaic.ui.utils import load_settings
# Create temporary CSV
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
f.write("slide1.svs,Primary,Male,Unknown\n")
f.flush()
temp_path = f.name
try:
# Simulate read_settings handler (file without .name falls back to using file directly)
def read_settings(file):
if file is None:
return None
df = load_settings(file.name if hasattr(file, "name") else file)
return df
# When file doesn't have .name, the function uses the file object directly
# In practice, Gradio always provides .name, but test the fallback
result = read_settings(temp_path)
assert isinstance(result, pd.DataFrame)
assert len(result) == 1
finally:
Path(temp_path).unlink(missing_ok=True)
class TestCsvFormatEdgeCases:
"""Test CSV format edge cases and error handling."""
def test_load_settings_empty_csv_file(self):
"""Test loading completely empty CSV file."""
from mosaic.ui.utils import load_settings
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
# Write nothing - completely empty file
f.flush()
temp_path = f.name
try:
# Empty CSV should raise an error
with pytest.raises(Exception): # Could be pd.errors.EmptyDataError or ValueError
load_settings(temp_path)
finally:
Path(temp_path).unlink(missing_ok=True)
def test_load_settings_headers_only_csv(self):
"""Test CSV with only headers but no data rows."""
from mosaic.ui.utils import load_settings
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
# No data rows
f.flush()
temp_path = f.name
try:
df = load_settings(temp_path)
# Should return empty DataFrame with correct columns
assert isinstance(df, pd.DataFrame)
assert len(df) == 0
assert "Slide" in df.columns
assert "Site Type" in df.columns
finally:
Path(temp_path).unlink(missing_ok=True)
def test_load_settings_csv_with_extra_columns(self):
"""Test CSV with extra unknown columns (should be filtered)."""
from mosaic.ui.utils import load_settings, SETTINGS_COLUMNS
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype,ExtraColumn1,ExtraColumn2\n")
f.write("slide1.svs,Primary,Male,Unknown,extra_value1,extra_value2\n")
f.flush()
temp_path = f.name
try:
df = load_settings(temp_path)
# Extra columns should be filtered out
assert "ExtraColumn1" not in df.columns
assert "ExtraColumn2" not in df.columns
# Only SETTINGS_COLUMNS should remain
assert list(df.columns) == SETTINGS_COLUMNS
finally:
Path(temp_path).unlink(missing_ok=True)
def test_load_settings_csv_with_special_characters(self):
"""Test CSV with special characters in values."""
from mosaic.ui.utils import load_settings
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
# Special characters in slide name
f.write("slide-1_test@2024.svs,Primary,Unknown\n")
f.flush()
temp_path = f.name
try:
df = load_settings(temp_path)
# Should handle special characters correctly
assert isinstance(df, pd.DataFrame)
assert len(df) == 1
assert df["Slide"].iloc[0] == "slide-1_test@2024.svs"
finally:
Path(temp_path).unlink(missing_ok=True)
def test_load_settings_csv_with_quotes_in_values(self):
"""Test CSV with quoted values."""
from mosaic.ui.utils import load_settings
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
# Value with comma inside quotes
f.write('"slide1,with,commas.svs",Primary,Unknown\n')
f.flush()
temp_path = f.name
try:
df = load_settings(temp_path)
# Should parse quoted values correctly
assert isinstance(df, pd.DataFrame)
assert len(df) == 1
assert df["Slide"].iloc[0] == "slide1,with,commas.svs"
finally:
Path(temp_path).unlink(missing_ok=True)
def test_load_settings_csv_with_missing_values(self):
"""Test CSV with missing/empty values in optional columns."""
from mosaic.ui.utils import load_settings
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype,IHC Subtype,Segmentation Config\n")
# Empty values for optional columns
f.write("slide1.svs,Primary,Male,Unknown,,\n")
f.flush()
temp_path = f.name
try:
df = load_settings(temp_path)
# Should load CSV with empty values preserved
assert isinstance(df, pd.DataFrame)
assert len(df) == 1
# Empty strings should be preserved (validation will handle defaults later)
assert df["Segmentation Config"].iloc[0] == ""
assert df["IHC Subtype"].iloc[0] == ""
finally:
Path(temp_path).unlink(missing_ok=True)
def test_load_settings_csv_with_whitespace(self):
"""Test CSV with extra whitespace around values."""
from mosaic.ui.utils import load_settings
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
# Values with leading/trailing whitespace
f.write(" slide1.svs , Primary , Male , Unknown \n")
f.flush()
temp_path = f.name
try:
df = load_settings(temp_path)
# pandas should handle whitespace
assert isinstance(df, pd.DataFrame)
assert len(df) == 1
# Check if whitespace is preserved or stripped (depends on pandas behavior)
slide_value = df["Slide"].iloc[0]
assert "slide1.svs" in slide_value
finally:
Path(temp_path).unlink(missing_ok=True)
def test_load_settings_csv_with_different_line_endings(self):
"""Test CSV with different line ending styles (CRLF, LF)."""
from mosaic.ui.utils import load_settings
# Test with CRLF (Windows style)
with tempfile.NamedTemporaryFile(mode="wb", suffix=".csv", delete=False) as f:
f.write(b"Slide,Site Type,Sex,Cancer Subtype\r\n")
f.write(b"slide1.svs,Primary,Male,Unknown\r\n")
f.flush()
temp_path = f.name
try:
df = load_settings(temp_path)
assert isinstance(df, pd.DataFrame)
assert len(df) == 1
assert df["Slide"].iloc[0] == "slide1.svs"
finally:
Path(temp_path).unlink(missing_ok=True)
def test_load_settings_csv_with_tab_delimiter_fails(self):
"""Test that TSV (tab-delimited) file raises error."""
from mosaic.ui.utils import load_settings
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
# Use tabs instead of commas
f.write("Slide\tSite Type\tCancer Subtype\n")
f.write("slide1.svs\tPrimary\tUnknown\n")
f.flush()
temp_path = f.name
try:
# Should fail because columns won't be parsed correctly
with pytest.raises(ValueError, match="Missing required column"):
load_settings(temp_path)
finally:
Path(temp_path).unlink(missing_ok=True)
def test_load_settings_large_csv(self):
"""Test loading CSV with many rows (performance test)."""
from mosaic.ui.utils import load_settings
num_rows = 1000
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
for i in range(num_rows):
f.write(f"slide{i}.svs,Primary,Male,Unknown\n")
f.flush()
temp_path = f.name
try:
df = load_settings(temp_path)
# Should handle large CSV without issues
assert isinstance(df, pd.DataFrame)
assert len(df) == num_rows
finally:
Path(temp_path).unlink(missing_ok=True)
class TestEncodingEdgeCases:
"""Test CSV encoding edge cases."""
def test_load_settings_utf8_csv(self):
"""Test loading UTF-8 encoded CSV (should work)."""
from mosaic.ui.utils import load_settings
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
f.write("slide1.svs,Primary,Male,Unknown\n")
f.flush()
temp_path = f.name
try:
df = load_settings(temp_path)
assert isinstance(df, pd.DataFrame)
assert len(df) == 1
finally:
Path(temp_path).unlink(missing_ok=True)
def test_load_settings_csv_with_unicode_characters(self):
"""Test CSV with Unicode characters in values."""
from mosaic.ui.utils import load_settings
with tempfile.NamedTemporaryFile(mode="w", encoding="utf-8", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
# Unicode characters in slide name
f.write("slide_café_™_测试.svs,Primary,Unknown\n")
f.flush()
temp_path = f.name
try:
df = load_settings(temp_path)
# Should handle Unicode correctly
assert isinstance(df, pd.DataFrame)
assert len(df) == 1
assert "café" in df["Slide"].iloc[0]
finally:
Path(temp_path).unlink(missing_ok=True)
class TestErrorRecoveryScenarios:
"""Test error recovery and user experience flows."""
def test_consecutive_csv_uploads(self):
"""Test uploading multiple CSVs consecutively."""
from mosaic.ui.utils import load_settings
# First CSV
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
f.write("slide1.svs,Primary,Male,Unknown\n")
f.flush()
temp_path1 = f.name
# Second CSV (different data)
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
f.write("slide2.svs,Metastatic,Female,LUAD\n")
f.write("slide3.svs,Primary,Male,BRCA\n")
f.flush()
temp_path2 = f.name
try:
# Load first CSV
df1 = load_settings(temp_path1)
assert len(df1) == 1
assert df1["Slide"].iloc[0] == "slide1.svs"
# Load second CSV (should completely replace)
df2 = load_settings(temp_path2)
assert len(df2) == 2
assert df2["Slide"].iloc[0] == "slide2.svs"
assert df2["Slide"].iloc[1] == "slide3.svs"
# Should be independent DataFrames
assert len(df1) == 1 # df1 unchanged
finally:
Path(temp_path1).unlink(missing_ok=True)
Path(temp_path2).unlink(missing_ok=True)
def test_load_settings_after_failed_upload(self):
"""Test successful load after a failed upload attempt."""
from mosaic.ui.utils import load_settings
# First attempt: invalid CSV (missing required columns)
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("InvalidColumn\n")
f.write("value\n")
f.flush()
invalid_path = f.name
# Second attempt: valid CSV
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
f.write("slide1.svs,Primary,Male,Unknown\n")
f.flush()
valid_path = f.name
try:
# First load should fail
with pytest.raises(ValueError, match="Missing required column"):
load_settings(invalid_path)
# Second load should succeed
df = load_settings(valid_path)
assert isinstance(df, pd.DataFrame)
assert len(df) == 1
assert df["Slide"].iloc[0] == "slide1.svs"
finally:
Path(invalid_path).unlink(missing_ok=True)
Path(valid_path).unlink(missing_ok=True)
def test_load_settings_with_file_permission_error(self):
"""Test behavior when file cannot be read due to permissions."""
from mosaic.ui.utils import load_settings
import os
if os.name == 'nt':
# Skip on Windows due to different permission model
pytest.skip("Permission test not applicable on Windows")
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
f.write("slide1.svs,Primary,Male,Unknown\n")
f.flush()
temp_path = f.name
try:
# Remove read permissions
os.chmod(temp_path, 0o000)
# Should raise permission error
with pytest.raises(PermissionError):
load_settings(temp_path)
finally:
# Restore permissions for cleanup
os.chmod(temp_path, 0o644)
Path(temp_path).unlink(missing_ok=True)
def test_load_settings_nonexistent_file(self):
"""Test loading from non-existent file path."""
from mosaic.ui.utils import load_settings
nonexistent_path = "/tmp/this_file_does_not_exist_12345.csv"
# Should raise FileNotFoundError
with pytest.raises(FileNotFoundError):
load_settings(nonexistent_path)
class TestValidationWithUpload:
"""Test validation integration with CSV upload."""
def test_csv_upload_triggers_validation(self, mock_cancer_subtype_maps):
"""Test that uploaded CSV is automatically validated."""
from mosaic.ui.utils import load_settings, validate_settings
cancer_subtype_name_map, reversed_map, cancer_subtypes = mock_cancer_subtype_maps
# Create CSV with invalid values
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype,Segmentation Config\n")
f.write("slide1.svs,InvalidSite,Male,InvalidSubtype,InvalidConfig\n")
f.flush()
temp_path = f.name
try:
# Load and validate
df = load_settings(temp_path)
validated_df = validate_settings(
df, cancer_subtype_name_map, cancer_subtypes, reversed_map
)
# Should apply defaults for invalid values
assert validated_df["Site Type"].iloc[0] == "Primary"
assert validated_df["Cancer Subtype"].iloc[0] == "Unknown"
assert validated_df["Segmentation Config"].iloc[0] == "Biopsy"
finally:
Path(temp_path).unlink(missing_ok=True)
def test_csv_upload_with_partial_invalid_data(self, mock_cancer_subtype_maps):
"""Test CSV with mix of valid and invalid rows."""
from mosaic.ui.utils import load_settings, validate_settings
cancer_subtype_name_map, reversed_map, cancer_subtypes = mock_cancer_subtype_maps
with tempfile.NamedTemporaryFile(mode="w", suffix=".csv", delete=False) as f:
f.write("Slide,Site Type,Sex,Cancer Subtype\n")
f.write("slide1.svs,Primary,Male,Unknown\n") # Valid
f.write("slide2.svs,InvalidSite,Female,InvalidSubtype\n") # Invalid
f.write("slide3.svs,Metastatic,Male,LUAD\n") # Valid
f.flush()
temp_path = f.name
try:
df = load_settings(temp_path)
validated_df = validate_settings(
df, cancer_subtype_name_map, cancer_subtypes, reversed_map
)
# All rows should be present
assert len(validated_df) == 3
# Valid rows unchanged
assert validated_df.iloc[0]["Site Type"] == "Primary"
assert validated_df.iloc[2]["Site Type"] == "Metastatic"
# Invalid row corrected with defaults
assert validated_df.iloc[1]["Site Type"] == "Primary"
assert validated_df.iloc[1]["Cancer Subtype"] == "Unknown"
finally:
Path(temp_path).unlink(missing_ok=True)
|