test_storage_open.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. """resolve_object_key / open_file for local storage."""
  2. import pytest
  3. from app.core.config import get_settings
  4. from app.core import storage
  5. from app.core.storage import StorageError
  6. @pytest.fixture
  7. def local_storage_env(tmp_path, monkeypatch):
  8. monkeypatch.setenv("STORAGE_TYPE", "local")
  9. monkeypatch.setenv("LOCAL_STORAGE_DIR", str(tmp_path))
  10. get_settings.cache_clear()
  11. yield tmp_path
  12. get_settings.cache_clear()
  13. def test_resolve_uploads_url(local_storage_env):
  14. assert storage.resolve_object_key("/uploads/feedback/a.png") == "feedback/a.png"
  15. def test_resolve_rejects_traversal(local_storage_env):
  16. with pytest.raises(StorageError):
  17. storage.resolve_object_key("/uploads/../etc/passwd")
  18. def test_open_local_file(local_storage_env):
  19. stored = storage.upload_file(b"\x89PNG\r\n\x1a\n" + b"x" * 8, "a.png", "feedback")
  20. stream, content_type, filename, inline = storage.open_file(stored["url"])
  21. data = stream.read() if hasattr(stream, "read") else b"".join(stream)
  22. assert data.startswith(b"\x89PNG")
  23. assert "png" in content_type
  24. assert inline is True
  25. assert filename.endswith(".png")
  26. def test_open_rejects_foreign_url(local_storage_env):
  27. with pytest.raises(StorageError):
  28. storage.open_file("https://evil.example/x.png")