test_image.py 1.8 KB

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