#!/usr/bin/env python import difflib import email.parser import mailbox import sys f1, f2 = sys.argv[1:3] expected = email.parser.Parser().parse(open(f1)) mbox = mailbox.mbox(f2, create=False) msg = mbox[0] diff = False for h, val in expected.items(): if h not in msg: print("Header missing: %r" % h) diff = True continue if expected[h] == '*': continue if msg[h] != val: print("Header %r differs: %r != %r" % (h, val, msg[h])) diff = True def flexible_eq(expected, got): """Compare two strings, supporting wildcards. This functions compares two strings, but supports wildcards on the expected string. The following characters have special meaning: - ? matches any character. - * matches anything until the end of the line. Returns True if equal (considering wildcards), False otherwise. """ posG = 0 for c in expected: if posG >= len(got): return False if c == '?': posG += 1 continue if c == '*': while got[posG] != '\n': posG += 1 continue continue if c != got[posG]: return False posG += 1 return True if not flexible_eq(expected.get_payload(), msg.get_payload()): diff = True if expected.is_multipart() != msg.is_multipart(): print("Multipart differs, expected %s, got %s" % ( expected.is_multipart(), msg.is_multipart())) elif not msg.is_multipart(): exp = expected.get_payload().splitlines() got = msg.get_payload().splitlines() print("Payload differs:") for l in difflib.ndiff(exp, got): print(l) sys.exit(0 if not diff else 1)