diff options
| -rw-r--r-- | src/mailman/app/tests/test_subscriptions.py | 5 | ||||
| -rw-r--r-- | src/mailman/bin/docs/master.rst | 9 | ||||
| -rw-r--r-- | src/mailman/commands/cli_withlist.py | 6 | ||||
| -rw-r--r-- | src/mailman/commands/tests/test_control.py | 16 | ||||
| -rw-r--r-- | src/mailman/core/runner.py | 8 | ||||
| -rw-r--r-- | src/mailman/database/tests/test_factory.py | 9 | ||||
| -rw-r--r-- | src/mailman/handlers/mime_delete.py | 6 | ||||
| -rw-r--r-- | src/mailman/handlers/subject_prefix.py | 7 | ||||
| -rw-r--r-- | src/mailman/model/messagestore.py | 7 | ||||
| -rw-r--r-- | src/mailman/rules/implicit_dest.py | 5 | ||||
| -rw-r--r-- | src/mailman/runners/command.py | 5 | ||||
| -rw-r--r-- | src/mailman/runners/incoming.py | 5 | ||||
| -rw-r--r-- | src/mailman/testing/helpers.py | 11 | ||||
| -rw-r--r-- | src/mailman/utilities/filesystem.py | 18 | ||||
| -rw-r--r-- | src/mailman/utilities/interact.py | 5 | ||||
| -rw-r--r-- | src/mailman/utilities/uid.py | 6 |
16 files changed, 46 insertions, 82 deletions
diff --git a/src/mailman/app/tests/test_subscriptions.py b/src/mailman/app/tests/test_subscriptions.py index 1139591de..11512bcfe 100644 --- a/src/mailman/app/tests/test_subscriptions.py +++ b/src/mailman/app/tests/test_subscriptions.py @@ -19,6 +19,7 @@ import unittest +from contextlib import suppress from mailman.app.lifecycle import create_list from mailman.app.subscriptions import SubscriptionWorkflow from mailman.interfaces.bans import IBanManager @@ -57,10 +58,8 @@ class TestSubscriptionWorkflow(unittest.TestCase): # some data associated with it. anne = self._user_manager.create_address(self._anne) workflow = SubscriptionWorkflow(self._mlist, anne) - try: + with suppress(StopIteration): workflow.run_thru('send_confirmation') - except StopIteration: - pass self.assertIsNotNone(workflow.token) pendable = getUtility(IPendings).confirm(workflow.token, expunge=False) self.assertEqual(pendable['list_id'], 'test.example.com') diff --git a/src/mailman/bin/docs/master.rst b/src/mailman/bin/docs/master.rst index 5a3a94da6..c9bd60f13 100644 --- a/src/mailman/bin/docs/master.rst +++ b/src/mailman/bin/docs/master.rst @@ -41,13 +41,8 @@ runner processes. None of the children are running now. >>> import errno + >>> from contextlib import suppress >>> for pid in master.runner_pids: - ... try: + ... with suppress(ProcessLookupError): ... os.kill(pid, 0) ... print('Process did not exit:', pid) - ... except OSError as error: - ... if error.errno == errno.ESRCH: - ... # The child process exited. - ... pass - ... else: - ... raise diff --git a/src/mailman/commands/cli_withlist.py b/src/mailman/commands/cli_withlist.py index 79dc3b966..127308a05 100644 --- a/src/mailman/commands/cli_withlist.py +++ b/src/mailman/commands/cli_withlist.py @@ -20,7 +20,7 @@ import re import sys -from contextlib import ExitStack +from contextlib import ExitStack, suppress from functools import partial from lazr.config import as_boolean from mailman import public @@ -222,10 +222,8 @@ class Withlist: } history_file = Template( history_file_template).safe_substitute(substitutions) - try: + with suppress(FileNotFoundError): readline.read_history_file(history_file) - except FileNotFoundError: - pass resources.callback( readline.write_history_file, history_file) diff --git a/src/mailman/commands/tests/test_control.py b/src/mailman/commands/tests/test_control.py index 26d921cd7..7377c4666 100644 --- a/src/mailman/commands/tests/test_control.py +++ b/src/mailman/commands/tests/test_control.py @@ -56,22 +56,12 @@ def find_master(): until = timedelta(seconds=10) + datetime.now() while datetime.now() < until: time.sleep(0.1) - try: + with suppress(FileNotFoundError, ValueError, ProcessLookupError): with open(config.PID_FILE) as fp: pid = int(fp.read().strip()) os.kill(pid, 0) - except IOError as error: - if error.errno != errno.ENOENT: - raise - except ValueError: - pass - except OSError as error: - if error.errno != errno.ESRCH: - raise - else: - return pid - else: - return None + return pid + return None class FakeArgs: diff --git a/src/mailman/core/runner.py b/src/mailman/core/runner.py index 4c9c59464..d193a1082 100644 --- a/src/mailman/core/runner.py +++ b/src/mailman/core/runner.py @@ -22,6 +22,7 @@ import signal import logging import traceback +from contextlib import suppress from io import StringIO from lazr.config import as_boolean, as_timedelta from mailman import public @@ -112,7 +113,7 @@ class Runner: def run(self): """See `IRunner`.""" # Start the main loop for this runner. - try: + with suppress(KeyboardInterrupt): while True: # Once through the loop that processes all the files in the # queue directory. @@ -126,10 +127,7 @@ class Runner: # pass it the file count so it can decide whether to do more # work now or not. self._snooze(filecnt) - except KeyboardInterrupt: - pass - finally: - self._clean_up() + self._clean_up() def _one_iteration(self): """See `IRunner`.""" diff --git a/src/mailman/database/tests/test_factory.py b/src/mailman/database/tests/test_factory.py index d8593cc76..74b45e43a 100644 --- a/src/mailman/database/tests/test_factory.py +++ b/src/mailman/database/tests/test_factory.py @@ -20,6 +20,7 @@ import unittest import alembic.command +from contextlib import suppress from mailman.config import config from mailman.database.alembic import alembic_cfg from mailman.database.factory import LAST_STORM_SCHEMA_VERSION, SchemaManager @@ -87,12 +88,10 @@ class TestSchemaManager(unittest.TestCase): version = Model.metadata.tables['version'] version.drop(config.db.engine, checkfirst=True) Model.metadata.remove(version) - try: + # If it's nonexistent, PostgreSQL raises a ProgrammingError, while + # SQLite raises an OperationalError. + with suppress(ProgrammingError, OperationalError): Index('ix_user_user_id').drop(bind=config.db.engine) - except (ProgrammingError, OperationalError): - # Nonexistent. PostgreSQL raises a ProgrammingError, while SQLite - # raises an OperationalError. - pass config.db.commit() def test_current_database(self): diff --git a/src/mailman/handlers/mime_delete.py b/src/mailman/handlers/mime_delete.py index 267cb227a..b88c40b0c 100644 --- a/src/mailman/handlers/mime_delete.py +++ b/src/mailman/handlers/mime_delete.py @@ -30,7 +30,7 @@ import logging import tempfile import subprocess -from contextlib import ExitStack +from contextlib import ExitStack, suppress from email.iterators import typed_subpart_iterator from email.mime.message import MIMEMessage from email.mime.text import MIMEText @@ -220,11 +220,9 @@ def collapse_multipart_alternatives(msg): newpayload = [] for subpart in msg.get_payload(): if subpart.get_content_type() == 'multipart/alternative': - try: + with suppress(IndexError): firstalt = subpart.get_payload(0) newpayload.append(firstalt) - except IndexError: - pass else: newpayload.append(subpart) msg.set_payload(newpayload) diff --git a/src/mailman/handlers/subject_prefix.py b/src/mailman/handlers/subject_prefix.py index 8a9da8b42..ff728d92e 100644 --- a/src/mailman/handlers/subject_prefix.py +++ b/src/mailman/handlers/subject_prefix.py @@ -19,7 +19,8 @@ import re -from email.header import Header, make_header, decode_header +from contextlib import suppress +from email.header import Header, decode_header, make_header from mailman import public from mailman.core.i18n import _ from mailman.interfaces.handler import IHandler @@ -163,10 +164,8 @@ class SubjectPrefix: # subject. Also, force new style. prefix_pattern = p.sub(r'\s*\d+\s*', prefix_pattern) # Substitute %d in prefix with post_id - try: + with suppress(TypeError): prefix = prefix % mlist.post_id - except TypeError: - pass for handler in (ascii_header, all_same_charset, mixed_charsets, diff --git a/src/mailman/model/messagestore.py b/src/mailman/model/messagestore.py index b17118330..8949c56c6 100644 --- a/src/mailman/model/messagestore.py +++ b/src/mailman/model/messagestore.py @@ -27,7 +27,7 @@ from mailman.database.transaction import dbconnection from mailman.interfaces.messages import IMessageStore from mailman.model.message import Message from mailman.utilities.email import add_message_hash -from mailman.utilities.filesystem import makedirs +from mailman.utilities.filesystem import makedirs, safe_remove from zope.interface import implementer @@ -123,8 +123,5 @@ class MessageStore: path = os.path.join(config.MESSAGES_DIR, row.path) # It's possible that a race condition caused the file system path # to already be deleted. - try: - os.remove(path) - except FileNotFoundError: - pass + safe_remove(path) store.delete(row) diff --git a/src/mailman/rules/implicit_dest.py b/src/mailman/rules/implicit_dest.py index 621ad3e22..c0e116d1c 100644 --- a/src/mailman/rules/implicit_dest.py +++ b/src/mailman/rules/implicit_dest.py @@ -19,6 +19,7 @@ import re +from contextlib import suppress from email.utils import getaddresses from mailman import public from mailman.core.i18n import _ @@ -83,10 +84,8 @@ class ImplicitDestination: except re.error: # The pattern is a malformed regular expression. Try # matching again with the pattern escaped. - try: + with suppress(re.error): if re.match(escaped, recipient, re.IGNORECASE): return False - except re.error: - pass # Nothing matched. return True diff --git a/src/mailman/runners/command.py b/src/mailman/runners/command.py index 13d52ce75..00f6f416b 100644 --- a/src/mailman/runners/command.py +++ b/src/mailman/runners/command.py @@ -25,6 +25,7 @@ import re import logging +from contextlib import suppress from email.errors import HeaderParseError from email.header import decode_header, make_header from email.iterators import typed_subpart_iterator @@ -224,11 +225,9 @@ class CommandRunner(Runner): # utf-8. reply_body = str(results) for charset in (results.charset, 'us-ascii', 'latin-1'): - try: + with suppress(UnicodeError): reply_body.encode(charset) break - except UnicodeError: - pass else: charset = 'utf-8' reply.set_payload(reply_body, charset=charset) diff --git a/src/mailman/runners/incoming.py b/src/mailman/runners/incoming.py index dd9254194..62b12dab1 100644 --- a/src/mailman/runners/incoming.py +++ b/src/mailman/runners/incoming.py @@ -26,6 +26,7 @@ prepared for delivery. Rejections, discards, and holds are processed immediately. """ +from contextlib import suppress from mailman import public from mailman.core.chains import process from mailman.core.runner import Runner @@ -48,10 +49,8 @@ class IncomingRunner(Runner): user_manager = getUtility(IUserManager) with transaction(): for sender in msg.senders: - try: + with suppress(ExistingAddressError): user_manager.create_address(sender) - except ExistingAddressError: - pass # Process the message through the mailing list's start chain. start_chain = (mlist.owner_chain if msgdata.get('to_owner', False) diff --git a/src/mailman/testing/helpers.py b/src/mailman/testing/helpers.py index 3edd66479..a87dd58ec 100644 --- a/src/mailman/testing/helpers.py +++ b/src/mailman/testing/helpers.py @@ -31,7 +31,7 @@ import datetime import threading from base64 import b64encode -from contextlib import contextmanager +from contextlib import contextmanager, suppress from email import message_from_string from httplib2 import Http from lazr.config import as_timedelta @@ -183,14 +183,11 @@ class TestableMaster(Master): starting_kids = set(self._kids) while starting_kids: for pid in self._kids: - try: + # Ignore the exception which gets raised when the child has + # not yet started. + with suppress(ProcessLookupError): os.kill(pid, 0) starting_kids.remove(pid) - except OSError as error: - if error.errno == errno.ESRCH: - # The child has not yet started. - pass - raise # Keeping a copy of all the started child processes for use by the # testing environment, even after all have exited. self._started_kids = set(self._kids) diff --git a/src/mailman/utilities/filesystem.py b/src/mailman/utilities/filesystem.py index e8935b92c..e89f2abb8 100644 --- a/src/mailman/utilities/filesystem.py +++ b/src/mailman/utilities/filesystem.py @@ -18,8 +18,8 @@ """Filesystem utilities.""" import os -import errno +from contextlib import suppress from mailman import public @@ -54,18 +54,18 @@ def makedirs(path, mode=0o2775): :param mode: The numeric permission mode to use. :type mode: int """ - try: + with suppress(FileExistsError): with umask(0): os.makedirs(path, mode) - except OSError as error: - # Ignore the exceptions if the directory already exists. - if error.errno != errno.EEXIST: - raise # Some systems such as FreeBSD ignore mkdir's mode, so walk the just # created directories and try to set the mode, ignoring any OSErrors that # occur here. for dirpath, dirnames, filenames in os.walk(path): - try: + with suppress(OSError): os.chmod(dirpath, mode) - except OSError: - pass + + +@public +def safe_remove(path): + with suppress(FileNotFoundError): + os.remove(path) diff --git a/src/mailman/utilities/interact.py b/src/mailman/utilities/interact.py index 3cc5dddc6..904d1b579 100644 --- a/src/mailman/utilities/interact.py +++ b/src/mailman/utilities/interact.py @@ -21,6 +21,7 @@ import os import sys import code +from contextlib import suppress from mailman import public @@ -51,10 +52,8 @@ def interact(upframe=True, banner=DEFAULT_BANNER, overrides=None): namespace.update(overrides) interp = code.InteractiveConsole(namespace) # Try to import the readline module, but don't worry if it's unavailable. - try: + with suppress(ImportError): import readline # noqa - except ImportError: # pragma: no cover - pass # Mimic the real interactive interpreter's loading of any $PYTHONSTARTUP # file. Note that if the startup file is not prepared to be exec'd more # than once, this could cause a problem. diff --git a/src/mailman/utilities/uid.py b/src/mailman/utilities/uid.py index cef0ebc87..4389bcd92 100644 --- a/src/mailman/utilities/uid.py +++ b/src/mailman/utilities/uid.py @@ -27,6 +27,7 @@ import uuid import random import hashlib +from contextlib import suppress from flufl.lock import Lock from mailman import public from mailman.config import config @@ -125,11 +126,8 @@ class UIDFactory(_PredictableIDGenerator): """ while True: uid = uuid.uuid4() - try: + with suppress(ValueError): UID.record(uid) - except ValueError: - pass - else: return uid def _next_predictable_id(self): |
