Test attaching a file against different mimetypes and make sure that a file will be attached and sent in some form even if a mismatched mimetype is specified.
(self)
| 978 | self.assertEqual(attachment.filename, "une pièce jointe.pdf") |
| 979 | |
| 980 | def test_attach_file(self): |
| 981 | """ |
| 982 | Test attaching a file against different mimetypes and make sure that |
| 983 | a file will be attached and sent in some form even if a mismatched |
| 984 | mimetype is specified. |
| 985 | """ |
| 986 | files = ( |
| 987 | # filename, actual mimetype |
| 988 | ("file.txt", "text/plain"), |
| 989 | ("file.png", "image/png"), |
| 990 | ("file_txt", None), |
| 991 | ("file_png", None), |
| 992 | ("file_txt.png", "image/png"), |
| 993 | ("file_png.txt", "text/plain"), |
| 994 | ("file.eml", "message/rfc822"), |
| 995 | ) |
| 996 | test_mimetypes = ["text/plain", "image/png", None] |
| 997 | |
| 998 | for basename, real_mimetype in files: |
| 999 | for mimetype in test_mimetypes: |
| 1000 | with self.subTest( |
| 1001 | basename=basename, real_mimetype=real_mimetype, mimetype=mimetype |
| 1002 | ): |
| 1003 | self.assertEqual(mimetypes.guess_type(basename)[0], real_mimetype) |
| 1004 | expected_mimetype = ( |
| 1005 | mimetype or real_mimetype or "application/octet-stream" |
| 1006 | ) |
| 1007 | file_path = Path(__file__).parent / "attachments" / basename |
| 1008 | expected_content = file_path.read_bytes() |
| 1009 | if expected_mimetype.startswith("text/"): |
| 1010 | try: |
| 1011 | expected_content = expected_content.decode() |
| 1012 | except UnicodeDecodeError: |
| 1013 | expected_mimetype = "application/octet-stream" |
| 1014 | |
| 1015 | email = EmailMessage() |
| 1016 | email.attach_file(file_path, mimetype=mimetype) |
| 1017 | |
| 1018 | # Check EmailMessage.attachments. |
| 1019 | self.assertEqual(len(email.attachments), 1) |
| 1020 | self.assertEqual(email.attachments[0].filename, basename) |
| 1021 | self.assertEqual(email.attachments[0].mimetype, expected_mimetype) |
| 1022 | self.assertEqual(email.attachments[0].content, expected_content) |
| 1023 | |
| 1024 | # Check attachments in the generated message. |
| 1025 | # (The actual content is not checked as variations in |
| 1026 | # platform line endings and rfc822 refolding complicate the |
| 1027 | # logic.) |
| 1028 | attachments = self.get_decoded_attachments(email) |
| 1029 | self.assertEqual(len(attachments), 1) |
| 1030 | actual = attachments[0] |
| 1031 | self.assertEqual(actual.filename, basename) |
| 1032 | self.assertEqual(actual.mimetype, expected_mimetype) |
| 1033 | |
| 1034 | def test_attach_text_as_bytes(self): |
| 1035 | """ |
nothing calls this directly
no test coverage detected