test_inline_media.py 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283
  1. import base64
  2. from redmail import EmailSender
  3. import re
  4. from pathlib import Path
  5. from io import BytesIO
  6. import pytest
  7. # Importing Pandas from utils (is None if missing package)
  8. from redmail.email.utils import pd
  9. from resources import get_mpl_fig, get_pil_image
  10. from convert import remove_extra_lines, payloads_to_dict
  11. def compare_image_mime(mime_part, mime_part_html, orig_image:bytes, type_="image/png"):
  12. assert type_ == mime_part.get_content_type()
  13. image_bytes = mime_part.get_content()
  14. assert orig_image == image_bytes
  15. # Check the HTML mime has the image
  16. image_info = dict(mime_part.items())
  17. cid_parts = image_info['Content-ID'][1:-1].split(".")
  18. cid = "{}.{}.=\n{}.{domain}".format(*cid_parts[:3], domain='.'.join(cid_parts[3:]))
  19. cid = image_info['Content-ID'][1:-1]
  20. mime_part_html_cleaned = mime_part_html.get_payload().replace("=\n", "")
  21. assert f'<img src=3D"cid:{cid}">' in mime_part_html_cleaned or f'<img src="cid:{cid}">' in mime_part_html_cleaned
  22. @pytest.mark.parametrize(
  23. "get_image_obj", [
  24. pytest.param(lambda x: str(x), id="Path (str)"),
  25. pytest.param(lambda x: Path(str(x)), id="Path (pathlib)"),
  26. pytest.param(lambda x: open(str(x), 'rb').read(), id="Bytes (bytes)"),
  27. pytest.param(lambda x: BytesIO(open(str(x), 'rb').read()), id="Bytes (BytesIO)"),
  28. pytest.param(lambda x: {"maintype": "image", "subtype": "png", "content": open(str(x), 'rb').read()}, id="Dict specs"),
  29. ]
  30. )
  31. def test_with_image_file(get_image_obj, dummy_png):
  32. with open(str(dummy_png), "rb") as f:
  33. dummy_bytes = f.read()
  34. image_obj = get_image_obj(dummy_png)
  35. sender = EmailSender(host=None, port=1234)
  36. msg = sender.get_message(
  37. sender="me@gmail.com",
  38. receivers="you@gmail.com",
  39. subject="Some news",
  40. html='<h1>Hi,</h1> Nice to meet you. Look at this: {{ my_image }}',
  41. body_images={"my_image": image_obj}
  42. )
  43. assert "multipart/mixed" == msg.get_content_type()
  44. alternative = msg.get_payload()[0]
  45. related = alternative.get_payload()[0]
  46. mime_html, mime_image = related.get_payload()
  47. compare_image_mime(mime_image, mime_html, orig_image=dummy_bytes)
  48. # Test receivers etc.
  49. headers = dict(msg.items())
  50. assert {
  51. 'from': 'me@gmail.com',
  52. 'subject': 'Some news',
  53. 'to': 'you@gmail.com',
  54. #'MIME-Version': '1.0',
  55. 'Content-Type': 'multipart/mixed'
  56. } == headers
  57. def test_with_image_dict_jpeg():
  58. img_data = '/9j/4AAQSkZJRgABAQEAYABgAAD/2wBDAAIBAQIBAQICAgICAgICAwUDAwMDAwYEBAMFBwYHBwcGBwcICQsJCAgKCAcHCg0KCgsMDAwMBwkODw0MDgsMDAz/2wBDAQICAgMDAwYDAwYMCAcIDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAwMDAz/wAARCAABAAEDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/9oADAMBAAIRAxEAPwD5rooor8DP9oD/2Q=='
  59. img_bytes = base64.b64decode(img_data)
  60. sender = EmailSender(host=None, port=1234)
  61. msg = sender.get_message(
  62. sender="me@gmail.com",
  63. receivers="you@gmail.com",
  64. subject="Some news",
  65. html='<h1>Hi,</h1> Nice to meet you. Look at this: {{ my_image }}',
  66. body_images={
  67. 'my_image': {
  68. "content": img_bytes,
  69. 'subtype': 'jpg'
  70. }
  71. }
  72. )
  73. # Validate structure
  74. structure = payloads_to_dict(msg)
  75. assert structure == {
  76. "multipart/mixed": {
  77. "multipart/alternative": {
  78. "multipart/related": {
  79. "text/html": structure["multipart/mixed"]["multipart/alternative"]["multipart/related"]["text/html"],
  80. "image/jpg": structure["multipart/mixed"]["multipart/alternative"]["multipart/related"]["image/jpg"],
  81. }
  82. }
  83. }
  84. }
  85. assert "multipart/mixed" == msg.get_content_type()
  86. alternative = msg.get_payload()[0]
  87. related = alternative.get_payload()[0]
  88. mime_html, mime_image = related.get_payload()
  89. compare_image_mime(mime_image, mime_html, orig_image=img_bytes, type_="image/jpg")
  90. # Test receivers etc.
  91. headers = dict(msg.items())
  92. assert {
  93. 'from': 'me@gmail.com',
  94. 'subject': 'Some news',
  95. 'to': 'you@gmail.com',
  96. #'MIME-Version': '1.0',
  97. 'Content-Type': 'multipart/mixed'
  98. } == headers
  99. @pytest.mark.parametrize(
  100. "get_image_obj", [
  101. pytest.param(get_mpl_fig, id="Matplotlib figure"),
  102. pytest.param(get_pil_image, id="PIL image"),
  103. ]
  104. )
  105. def test_with_image_obj(get_image_obj):
  106. image_obj, image_bytes = get_image_obj()
  107. sender = EmailSender(host=None, port=1234)
  108. msg = sender.get_message(
  109. sender="me@gmail.com",
  110. receivers="you@gmail.com",
  111. subject="Some news",
  112. html='<h1>Hi,</h1> Nice to meet you. Look at this: <img src="{{ my_image }}">',
  113. body_images={"my_image": image_obj}
  114. )
  115. assert "multipart/mixed" == msg.get_content_type()
  116. alternative = msg.get_payload()[0]
  117. related = alternative.get_payload()[0]
  118. mime_html, mime_image = related.get_payload()
  119. compare_image_mime(mime_image, mime_html, orig_image=image_bytes)
  120. # Test receivers etc.
  121. headers = dict(msg.items())
  122. assert {
  123. 'from': 'me@gmail.com',
  124. 'subject': 'Some news',
  125. 'to': 'you@gmail.com',
  126. #'MIME-Version': '1.0',
  127. 'Content-Type': 'multipart/mixed'
  128. } == headers
  129. def test_with_image_error():
  130. sender = EmailSender(host=None, port=1234)
  131. with pytest.raises(ValueError):
  132. msg = sender.get_message(
  133. sender="me@gmail.com",
  134. receivers="you@gmail.com",
  135. subject="Some news",
  136. html='<h1>Hi,</h1> Nice to meet you. Look at this: <img src="{{ my_image }}">',
  137. body_images={"my_image": "this is invalid"}
  138. )
  139. invalid_type_obj = type("TempClass", (), {})()
  140. with pytest.raises(TypeError):
  141. msg = sender.get_message(
  142. sender="me@gmail.com",
  143. receivers="you@gmail.com",
  144. subject="Some news",
  145. html='<h1>Hi,</h1> Nice to meet you. Look at this: <img src="{{ my_image }}">',
  146. body_images={"my_image": invalid_type_obj}
  147. )
  148. with pytest.raises(KeyError):
  149. msg = sender.get_message(
  150. sender="me@gmail.com",
  151. receivers="you@gmail.com",
  152. subject="Some news",
  153. html='<h1>Hi,</h1> Nice to meet you. Look at this:>',
  154. body_images={"my_image": {}}
  155. )
  156. @pytest.mark.parametrize(
  157. "get_df,", [
  158. pytest.param(
  159. lambda: pd.DataFrame(
  160. [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
  161. columns=pd.Index(["first", "second", "third"]),
  162. ),
  163. id="Simple dataframe"
  164. ),
  165. pytest.param(
  166. lambda: pd.DataFrame(
  167. [[1], [2], [3]],
  168. columns=pd.Index(["first"]),
  169. ),
  170. id="Single column datafram"
  171. ),
  172. pytest.param(
  173. lambda: pd.DataFrame(
  174. [[1, 2, 3], [4, 5, 6], [7, 8, 9]],
  175. columns=pd.Index(["first", "second", "third"]),
  176. index=pd.Index(["a", "b", "c"], name="category")
  177. ),
  178. id="Simple dataframe with index"
  179. ),
  180. pytest.param(
  181. lambda: pd.DataFrame(
  182. [[1, 2, 3, "a"], [4, 5, 6, "b"], [7, 8, 9, "c"], [10, 11, 12, "d"]],
  183. columns=pd.MultiIndex.from_tuples([("parent a", "child a"), ("parent a", "child b"), ("parent b", "child a"), ("parent c", "child a")], names=["lvl 1", "lvl 2"]),
  184. index=pd.MultiIndex.from_tuples([("row a", "sub a"), ("row a", "sub b"), ("row b", "sub a"), ("row c", "sub a")], names=["cat 1", "cat 2"]),
  185. ),
  186. id="Complex dataframe"
  187. ),
  188. pytest.param(
  189. lambda: pd.DataFrame(
  190. [[1, 2], [4, 5]],
  191. columns=pd.MultiIndex.from_tuples([("col a", "child b", "subchild a"), ("col a", "child b", "subchild a")]),
  192. index=pd.MultiIndex.from_tuples([("row a", "child b", "subchild a"), ("row a", "child b", "subchild a")]),
  193. ),
  194. id="Multiindex end with spanned"
  195. ),
  196. pytest.param(
  197. lambda: pd.DataFrame(
  198. [],
  199. columns=pd.Index(["first", "second", "third"]),
  200. ),
  201. id="Empty datafram"
  202. ),
  203. ]
  204. )
  205. def test_with_html_table_no_error(get_df, tmpdir):
  206. pytest.importorskip("pandas")
  207. df = get_df()
  208. sender = EmailSender(host=None, port=1234)
  209. msg = sender.get_message(
  210. sender="me@gmail.com",
  211. receivers="you@gmail.com",
  212. subject="Some news",
  213. html='The table {{my_table}}',
  214. body_tables={"my_table": df}
  215. )
  216. assert "multipart/mixed" == msg.get_content_type()
  217. alternative = msg.get_payload()[0]
  218. mime_html = alternative.get_payload()[0]
  219. #mime_text = msg.get_payload()[0]
  220. html = remove_extra_lines(mime_html.get_payload()).replace("=20", "").replace('"3D', "")
  221. #tmpdir.join("email.html").write(html)
  222. # TODO: Test the HTML is as required
  223. assert html
  224. def test_embed_tables_pandas_missing():
  225. sender = EmailSender(host=None, port=1234)
  226. from redmail.email import body
  227. pd_mdl = body.pd # This may be already None if env does not have Pandas
  228. try:
  229. # src uses this to reference Pandas (if missing --> None)
  230. body.pd = None
  231. with pytest.raises(ImportError):
  232. msg = sender.get_message(
  233. sender="me@gmail.com",
  234. receivers="you@gmail.com",
  235. subject="Some news",
  236. html='The table {{my_table}}',
  237. body_tables={"my_table": [{"col1": 1, "col2": "a"}, {"col1": 2, "col2": "b"}]}
  238. )
  239. finally:
  240. body.pd = pd_mdl