test_image.py 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. # PIL is only available in python 3.8+
  2. import numpy as np
  3. import PIL
  4. import pytest
  5. from PIL.Image import Image as Img
  6. import reflex as rx
  7. from reflex.components.next.image import Image # type: ignore
  8. from reflex.utils.serializers import serialize, serialize_image
  9. @pytest.fixture
  10. def pil_image() -> Img:
  11. """Get an image.
  12. Returns:
  13. A random PIL image.
  14. """
  15. imarray = np.random.rand(100, 100, 3) * 255
  16. return PIL.Image.fromarray(imarray.astype("uint8")).convert("RGBA") # type: ignore
  17. def test_serialize_image(pil_image: Img):
  18. """Test that serializing an image works.
  19. Args:
  20. pil_image: The image to serialize.
  21. """
  22. data = serialize(pil_image)
  23. assert isinstance(data, str)
  24. assert data == serialize_image(pil_image)
  25. assert data.startswith("data:image/png;base64,")
  26. def test_set_src_str():
  27. """Test that setting the src works."""
  28. image = rx.image(src="pic2.jpeg")
  29. assert str(image.src) == "{`pic2.jpeg`}" # type: ignore
  30. def test_set_src_img(pil_image: Img):
  31. """Test that setting the src works.
  32. Args:
  33. pil_image: The image to serialize.
  34. """
  35. image = Image.create(src=pil_image)
  36. assert str(image.src._var_name) == serialize_image(pil_image) # type: ignore
  37. def test_render(pil_image: Img):
  38. """Test that rendering an image works.
  39. Args:
  40. pil_image: The image to serialize.
  41. """
  42. image = Image.create(src=pil_image)
  43. assert image.src._var_is_string # type: ignore