test_image.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  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) == 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 not image.src.is_string # type: ignore
  45. image._render()
  46. assert image.src.is_string # type: ignore
  47. except ImportError:
  48. def test_pillow_import():
  49. """Make sure the Python version is less than 3.8."""
  50. import sys
  51. assert sys.version_info < (3, 8)