test_assets.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. import shutil
  2. from pathlib import Path
  3. from typing import Generator
  4. import pytest
  5. import reflex as rx
  6. import reflex.constants as constants
  7. def test_shared_asset() -> None:
  8. """Test shared assets."""
  9. # The asset function copies a file to the app's external assets directory.
  10. asset = rx.asset(path="custom_script.js", shared=True, subfolder="subfolder")
  11. assert asset == "/external/test_assets/subfolder/custom_script.js"
  12. result_file = Path(
  13. Path.cwd(), "assets/external/test_assets/subfolder/custom_script.js"
  14. )
  15. assert result_file.exists()
  16. # Running a second time should not raise an error.
  17. asset = rx.asset(path="custom_script.js", shared=True, subfolder="subfolder")
  18. # Test the asset function without a subfolder.
  19. asset = rx.asset(path="custom_script.js", shared=True)
  20. assert asset == "/external/test_assets/custom_script.js"
  21. result_file = Path(Path.cwd(), "assets/external/test_assets/custom_script.js")
  22. assert result_file.exists()
  23. # clean up
  24. shutil.rmtree(Path.cwd() / "assets/external")
  25. with pytest.raises(FileNotFoundError):
  26. asset = rx.asset("non_existent_file.js")
  27. # Nothing is done to assets when file does not exist.
  28. assert not Path(Path.cwd() / "assets/external").exists()
  29. @pytest.mark.parametrize(
  30. "path,shared",
  31. [
  32. pytest.param("non_existing_file", True),
  33. pytest.param("non_existing_file", False),
  34. ],
  35. )
  36. def test_invalid_assets(path: str, shared: bool) -> None:
  37. """Test that asset raises an error when the file does not exist.
  38. Args:
  39. path: The path to the asset.
  40. shared: Whether the asset should be shared.
  41. """
  42. with pytest.raises(FileNotFoundError):
  43. _ = rx.asset(path, shared=shared)
  44. @pytest.fixture
  45. def custom_script_in_asset_dir() -> Generator[Path, None, None]:
  46. """Create a custom_script.js file in the app's assets directory.
  47. Yields:
  48. The path to the custom_script.js file.
  49. """
  50. asset_dir = Path.cwd() / constants.Dirs.APP_ASSETS
  51. asset_dir.mkdir(exist_ok=True)
  52. path = asset_dir / "custom_script.js"
  53. path.touch()
  54. yield path
  55. path.unlink()
  56. def test_local_asset(custom_script_in_asset_dir: Path) -> None:
  57. """Test that no error is raised if shared is set and both files exist.
  58. Args:
  59. custom_script_in_asset_dir: Fixture that creates a custom_script.js file in the app's assets directory.
  60. """
  61. asset = rx.asset("custom_script.js", shared=False)
  62. assert asset == "/custom_script.js"