Skip to content

Commit

Permalink
Cleanup: use pathlib.Path in attach_image_file, test utils
Browse files Browse the repository at this point in the history
  • Loading branch information
medmunds committed Sep 11, 2020
1 parent 088d3c8 commit 109f484
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 10 deletions.
8 changes: 4 additions & 4 deletions anymail/message.py
Original file line number Diff line number Diff line change
@@ -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

Expand Down Expand Up @@ -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)


Expand Down
13 changes: 7 additions & 6 deletions tests/utils.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
# Anymail test utils
import os
import re
import sys
import uuid
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

Expand All @@ -28,22 +28,23 @@ 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"


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):
Expand Down

0 comments on commit 109f484

Please sign in to comment.