test_image.py 1.9 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. import numpy as np
  2. import PIL
  3. import pytest
  4. from PIL.Image import Image as Img
  5. import reflex as rx
  6. from reflex.components.next.image import Image
  7. from reflex.utils.serializers import serialize, serialize_image
  8. from reflex.vars.sequence import StringVar
  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") # pyright: ignore [reportAttributeAccessIssue]
  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. # when using next/image, we explicitly create a _var_is_str Var
  30. assert str(image.src) in ( # pyright: ignore [reportAttributeAccessIssue]
  31. '"pic2.jpeg"',
  32. "'pic2.jpeg'",
  33. "`pic2.jpeg`",
  34. )
  35. # For plain rx.el.img, an explicit var is not created, so the quoting happens later
  36. # assert str(image.src) == "pic2.jpeg" #noqa: ERA001
  37. def test_set_src_img(pil_image: Img):
  38. """Test that setting the src works.
  39. Args:
  40. pil_image: The image to serialize.
  41. """
  42. image = Image.create(src=pil_image)
  43. assert str(image.src._js_expr) == '"' + serialize_image(pil_image) + '"' # pyright: ignore [reportAttributeAccessIssue]
  44. def test_render(pil_image: Img):
  45. """Test that rendering an image works.
  46. Args:
  47. pil_image: The image to serialize.
  48. """
  49. image = Image.create(src=pil_image)
  50. assert isinstance(image.src, StringVar) # pyright: ignore [reportAttributeAccessIssue]