From faa68333a9036b5a1db45b73e792e6db62ac9830 Mon Sep 17 00:00:00 2001 From: Kili Date: Tue, 10 Mar 2026 16:22:39 +0100 Subject: [PATCH] Avoid extra mailbox fetch in batch/test mode and add regression test (#691) Co-authored-by: Sean Whalen <44679+seanthegeek@users.noreply.github.com> --- parsedmarc/__init__.py | 15 +++++++++------ tests.py | 39 +++++++++++++++++++++++++++++++++++++++ 2 files changed, 48 insertions(+), 6 deletions(-) diff --git a/parsedmarc/__init__.py b/parsedmarc/__init__.py index 94fe60b..2188f91 100644 --- a/parsedmarc/__init__.py +++ b/parsedmarc/__init__.py @@ -2141,14 +2141,17 @@ def get_dmarc_reports_from_mailbox( "smtp_tls_reports": smtp_tls_reports, } - if current_time: - total_messages = len( - connection.fetch_messages(reports_folder, since=current_time) - ) + if not test and not batch_size: + if current_time: + total_messages = len( + connection.fetch_messages(reports_folder, since=current_time) + ) + else: + total_messages = len(connection.fetch_messages(reports_folder)) else: - total_messages = len(connection.fetch_messages(reports_folder)) + total_messages = 0 - if not test and not batch_size and total_messages > 0: + if total_messages > 0: # Process emails that came in during the last run results = get_dmarc_reports_from_mailbox( connection=connection, diff --git a/tests.py b/tests.py index 88826d9..d9595d9 100755 --- a/tests.py +++ b/tests.py @@ -1314,6 +1314,45 @@ since = 2d self.assertEqual(system_exit.exception.code, 1) self.assertEqual(mock_watch_inbox.call_args.kwargs.get("since"), "2d") + +class _DummyMailboxConnection: + def __init__(self): + self.fetch_calls = [] + + def create_folder(self, folder_name): + return None + + def fetch_messages(self, reports_folder, **kwargs): + self.fetch_calls.append({"reports_folder": reports_folder, **kwargs}) + return [] + + def fetch_message(self, message_id, **kwargs): + return "" + + def delete_message(self, message_id): + return None + + def move_message(self, message_id, folder_name): + return None + + def keepalive(self): + return None + + def watch(self, check_callback, check_timeout): + return None + + +class TestMailboxPerformance(unittest.TestCase): + def testBatchModeAvoidsExtraFullFetch(self): + connection = _DummyMailboxConnection() + parsedmarc.get_dmarc_reports_from_mailbox( + connection=connection, + reports_folder="INBOX", + test=True, + batch_size=10, + create_folders=False, + ) + self.assertEqual(len(connection.fetch_calls), 1) @patch("parsedmarc.cli.get_dmarc_reports_from_mailbox") @patch("parsedmarc.cli.MSGraphConnection") def testCliPassesMsGraphCertificateAuthSettings(