Skip to content

Commit

Permalink
Fixed typing/style/py36+ errors
Browse files Browse the repository at this point in the history
  • Loading branch information
agronholm committed Nov 21, 2018
1 parent 52625aa commit b97527d
Show file tree
Hide file tree
Showing 7 changed files with 26 additions and 21 deletions.
13 changes: 7 additions & 6 deletions asphalt/mailer/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -73,23 +73,23 @@ def create_message(self, *, subject: str = None, sender: Union[str, Address] = N
"""
assert check_argument_types()
msg = EmailMessage()
msg['Subject'] = subject or self.message_defaults.get('subject')
msg['Subject'] = subject or self.message_defaults.get('subject') # type: ignore

sender = sender or self.message_defaults.get('sender')
if sender:
msg['From'] = sender
msg['From'] = sender # type: ignore

to = to or self.message_defaults.get('to')
if to:
msg['To'] = to
msg['To'] = to # type: ignore

cc = cc or self.message_defaults.get('cc')
if cc:
msg['Cc'] = cc
msg['Cc'] = cc # type: ignore

bcc = bcc or self.message_defaults.get('bcc')
if bcc:
msg['Bcc'] = bcc
msg['Bcc'] = bcc # type: ignore

charset = charset or self.message_defaults.get('charset')
if plain_body is not None and html_body is not None:
Expand Down Expand Up @@ -127,7 +127,8 @@ def add_attachment(cls, msg: EmailMessage, content: bytes, filename: str,
if not maintype or not subtype:
raise ValueError('mimetype must be a string in the "maintype/subtype" format')

msg.add_attachment(content, maintype=maintype, subtype=subtype, filename=filename)
msg.add_attachment(content, maintype=maintype, subtype=subtype, # type: ignore
filename=filename)

@classmethod
async def add_file_attachment(cls, msg: EmailMessage, path: Union[str, Path],
Expand Down
4 changes: 2 additions & 2 deletions asphalt/mailer/component.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
import logging
from typing import Dict, Any
from typing import Dict, Any, List # noqa: F401

from asphalt.core import Component, Context, PluginContainer, merge_config, context_teardown
from async_generator import yield_
Expand Down Expand Up @@ -42,7 +42,7 @@ def __init__(self, mailers: Dict[str, Dict[str, Any]] = None, **default_mailer_a
default_mailer_args.setdefault('context_attr', 'mailer')
mailers['default'] = default_mailer_args

self.mailers = []
self.mailers = [] # type: List[Mailer]
for resource_name, config in mailers.items():
config = merge_config(default_mailer_args, config)
backend = config.pop('backend')
Expand Down
6 changes: 3 additions & 3 deletions asphalt/mailer/mailers/mock.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,5 @@
from email.message import EmailMessage
from typing import Iterable, Union, Dict, Any
from typing import Iterable, Union, Dict, Any, List # noqa: F401

from typeguard import check_argument_types

Expand All @@ -18,10 +18,10 @@ class MockMailer(Mailer):

__slots__ = 'messages'

def __init__(self, *, message_defaults: Dict[str, Any]=None):
def __init__(self, *, message_defaults: Dict[str, Any] = None):
assert check_argument_types()
super().__init__(message_defaults or {})
self.messages = []
self.messages = [] # type: List[EmailMessage]

async def deliver(self, messages: Union[EmailMessage, Iterable[EmailMessage]]):
assert check_argument_types()
Expand Down
3 changes: 1 addition & 2 deletions asphalt/mailer/mailers/smtp.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
import logging
from email.message import EmailMessage
from numbers import Real
from ssl import SSLContext
from typing import Iterable, Union, Dict, Any

Expand Down Expand Up @@ -38,7 +37,7 @@ class SMTPMailer(Mailer):

def __init__(self, *, host: str = 'localhost', port: int = None, tls: bool = None,
tls_context: Union[str, SSLContext] = None,
username: str = None, password: str = None, timeout: Real = 10,
username: str = None, password: str = None, timeout: float = 10,
message_defaults: Dict[str, Any] = None):
assert check_argument_types()
super().__init__(message_defaults or {})
Expand Down
5 changes: 3 additions & 2 deletions asphalt/mailer/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
from email.headerregistry import UniqueAddressHeader # noqa: F401
from email.message import EmailMessage
from typing import List
from typing import List, cast

from typeguard import check_argument_types

Expand All @@ -17,7 +18,7 @@ def get_recipients(message: EmailMessage) -> List[str]:
recipients = []
for header in (message['To'], message['Cc'], message['Bcc']):
if header:
for addr in header.addresses:
for addr in cast(UniqueAddressHeader, header).addresses:
recipients.append(addr.addr_spec)

return recipients
5 changes: 2 additions & 3 deletions tests/mailers/test_sendmail.py
Original file line number Diff line number Diff line change
Expand Up @@ -76,8 +76,7 @@ async def test_deliver_launch_error(mailer, sample_message):
with pytest.raises(DeliveryError) as exc:
await mailer.deliver(sample_message)

assert str(exc.value) == ("error sending mail message: "
"[Errno 2] No such file or directory: '/bogus/no/way/this/exists'")
assert exc.match(r"^error sending mail message: \[Errno 2\] No such file or directory: ")


@pytest.mark.asyncio
Expand All @@ -86,7 +85,7 @@ async def test_deliver_error(mailer, sample_message, fail_script):
with pytest.raises(DeliveryError) as exc:
await mailer.deliver(sample_message)

assert str(exc.value) == 'error sending mail message: This is a test error'
assert exc.match('^error sending mail message: This is a test error')


def test_repr(mailer):
Expand Down
11 changes: 8 additions & 3 deletions tests/mailers/test_smtp.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
import ssl
from asyncio import Task
from base64 import b64decode
from contextlib import suppress
from pathlib import Path
Expand All @@ -13,6 +12,13 @@
from asphalt.mailer.api import DeliveryError
from asphalt.mailer.mailers.smtp import SMTPMailer

try:
from asyncio import all_tasks
except ImportError:
def all_tasks(loop=None):
from asyncio import Task
return {t for t in Task.all_tasks(loop) if not t.done()}


@pytest.fixture
def handler():
Expand Down Expand Up @@ -57,8 +63,7 @@ def smtp_server(event_loop, unused_tcp_port, handler, server_tls_context, tls):
event_loop.run_until_complete(server.wait_closed())

# The server leaves tasks running so cancel them
pending_tasks = [task for task in Task.all_tasks(event_loop) if not task.done()]
for task in pending_tasks:
for task in all_tasks(event_loop):
task.cancel()
with suppress(Exception):
event_loop.run_until_complete(task)
Expand Down

0 comments on commit b97527d

Please sign in to comment.