Ensure all opened files/sockets are closed in mail_utils
authorChristian Herdtweck <christian.herdtweck@intra2net.com>
Wed, 14 Nov 2018 08:53:08 +0000 (09:53 +0100)
committerChristian Herdtweck <christian.herdtweck@intra2net.com>
Wed, 14 Nov 2018 08:53:08 +0000 (09:53 +0100)
src/mail_utils.py

index 8326b7a..e9a7f16 100644 (file)
@@ -176,16 +176,15 @@ class MailValidator():
         """
         usernames_string = ",".join(usernames)
         log.info("Sending emails to %s", usernames_string)
-        server = smtplib.SMTP('localhost')
-        hostname = socket.gethostname()
-        users = [username + "@" + hostname for username in usernames]
+        with smtplib.SMTP('localhost') as server:
+            hostname = socket.gethostname()
+            users = [username + "@" + hostname for username in usernames]
 
-        for email in emails:
-            log.info("Sending email %s", email)
-            with open(os.path.join(self.source_path, email), 'rb') as f:
-                email_content = f.read()
-            server.sendmail(self.smtp_sender, users, email_content)
-        server.quit()
+            for email in emails:
+                log.info("Sending email %s", email)
+                with open(os.path.join(self.source_path, email), 'rb') as f:
+                    email_content = f.read()
+                server.sendmail(self.smtp_sender, users, email_content)
 
         # Wait till SMTP queue is processed
         arnied_wrapper.wait_for_email_transfer()
@@ -262,10 +261,9 @@ class MailValidator():
         """
         target_paths = self._extract_email_paths(self.target_path, emails, timeout)
         for email_path in target_paths:
-            email_file = open(email_path, "r")
-            verified_email = Parser().parse(email_file, headersonly=True)
-            log.debug("Extracted email headers:\n%s", verified_email)
-            email_file.close()
+            with open(email_path, "r") as email_file:
+                verified_email = Parser().parse(email_file, headersonly=True)
+                log.debug("Extracted email headers:\n%s", verified_email)
 
             log.info("Checking header '%s' in %s", header, email_path)
             if not present_values:
@@ -312,8 +310,8 @@ class MailValidator():
         """
         target_paths = self._extract_email_paths(self.target_path, emails, timeout)
         for email_path in target_paths:
-            email_file = open(email_path, "r")
-            verified_email = Parser().parse(email_file)
+            with open(email_path, "r") as email_file:
+                verified_email = Parser().parse(email_file)
             log.debug("Extracted email content:\n%s", verified_email)
             content = ""
             for part in verified_email.walk():
@@ -325,7 +323,6 @@ class MailValidator():
                         content = content.decode()
                     # NOTE: only one such element is expected
                     break
-            email_file.close()
 
             log.info("Checking content '%s' in %s", content_type, email_path)
             if not present_values:
@@ -375,7 +372,6 @@ class MailValidator():
         """
         text = 'This is an autogenerated email.\n'
 
-        server = smtplib.SMTP('localhost')
         hostname = socket.gethostname()
         user = username + "@" + hostname
 
@@ -441,8 +437,8 @@ class MailValidator():
 
         log.debug("Sending message from %s to %s" %
                       (self.smtp_sender, user))
-        server.sendmail(self.smtp_sender, user, msg.as_string())
-        server.close()
+        with smtplib.SMTP('localhost') as server:
+            server.sendmail(self.smtp_sender, user, msg.as_string())
 
         if isinstance(wait_for_transfer, int):
             arnied_wrapper.wait_for_email_transfer(timeout=wait_for_transfer)
@@ -504,10 +500,10 @@ class MailValidator():
 
     def _default_compare_emails(self, source_email_path, target_email_path, tolerance=1):
         """Use python provided diff functionality to compare target emails with source ones."""
-        source_email_file = open(source_email_path, "r")
-        target_email_file = open(target_email_path, "r")
-        source_email = source_email_file.read()
-        target_email = target_email_file.read()
+        with open(source_email_path, "r") as source_email_file:
+            source_email = source_email_file.read()
+        with open(target_email_path, "r") as target_email_file:
+            target_email = target_email_file.read()
         s = difflib.SequenceMatcher(None, source_email, target_email)
         diffratio = s.ratio()
         log.debug("Target message comparison ratio is %s.", diffratio)