From 109f484317dd63e5d56b64b7d06f5d297458c2d1 Mon Sep 17 00:00:00 2001 From: medmunds Date: Fri, 11 Sep 2020 13:27:50 -0700 Subject: [PATCH] Cleanup: use pathlib.Path in attach_image_file, test utils --- anymail/message.py | 8 ++++---- tests/utils.py | 13 +++++++------ 2 files changed, 11 insertions(+), 10 deletions(-) diff --git a/anymail/message.py b/anymail/message.py index a19d6b7..bf0ad16 100644 --- a/anymail/message.py +++ b/anymail/message.py @@ -1,6 +1,6 @@ from email.mime.image import MIMEImage from email.utils import unquote -import os +from pathlib import Path from django.core.mail import EmailMessage, EmailMultiAlternatives, make_msgid @@ -51,9 +51,9 @@ class AnymailMessage(AnymailMessageMixin, EmailMultiAlternatives): def attach_inline_image_file(message, path, subtype=None, idstring="img", domain=None): """Add inline image from file path to an EmailMessage, and return its content id""" - filename = os.path.basename(path) - with open(path, 'rb') as f: - content = f.read() + pathobj = Path(path) + filename = pathobj.name + content = pathobj.read_bytes() return attach_inline_image(message, content, filename, subtype, idstring, domain) diff --git a/tests/utils.py b/tests/utils.py index 6e81180..eb282e6 100644 --- a/tests/utils.py +++ b/tests/utils.py @@ -1,5 +1,4 @@ # Anymail test utils -import os import re import sys import uuid @@ -7,6 +6,7 @@ import warnings from base64 import b64decode from contextlib import contextmanager from io import StringIO +from pathlib import Path from unittest import TestCase from unittest.util import safe_repr @@ -28,7 +28,7 @@ def rfc822_unfold(text): # Sample files for testing (in ./test_files subdir) # -TEST_FILES_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'test_files') +TEST_FILES_DIR = Path(__file__).parent.joinpath("test_files").resolve() SAMPLE_IMAGE_FILENAME = "sample_image.png" SAMPLE_EMAIL_FILENAME = "sample_email.txt" @@ -36,14 +36,15 @@ SAMPLE_EMAIL_FILENAME = "sample_email.txt" def test_file_path(filename): """Returns path to a test file""" - return os.path.join(TEST_FILES_DIR, filename) + # Must convert to a plain str while we support Python 3.5, + # because django.core.mail uses os.path functions that don't + # accept pathlib.Path until Python 3.6. + return str(TEST_FILES_DIR.joinpath(filename)) def test_file_content(filename): """Returns contents (bytes) of a test file""" - path = test_file_path(filename) - with open(path, "rb") as f: - return f.read() + return TEST_FILES_DIR.joinpath(filename).read_bytes() def sample_image_path(filename=SAMPLE_IMAGE_FILENAME):