]> Frank Brehm's Git Trees - pixelpark/pp-admin-tools.git/commitdiff
Reorganizing export methos of PostfixLogchainInfo.
authorFrank Brehm <frank.brehm@pixelpark.com>
Wed, 20 Mar 2024 15:33:11 +0000 (16:33 +0100)
committerFrank Brehm <frank.brehm@pixelpark.com>
Wed, 20 Mar 2024 15:33:11 +0000 (16:33 +0100)
lib/pp_admintools/postfix_chain.py
test/test_20_postfix_chain.py

index accb56f5669a3b44003591d0883a58fe8bcd4a82..da4d41c7f95616b211a166b2771d515c542ec9f6 100644 (file)
@@ -14,9 +14,10 @@ import datetime
 import ipaddress
 import logging
 import re
+from collections import OrderedDict
 
 # Third party modules
-from fb_tools.common import pp
+from fb_tools.common import pp
 from fb_tools.obj import FbGenericBaseObject
 
 # Own modules
@@ -25,7 +26,7 @@ from .xlate import XLATOR
 _ = XLATOR.gettext
 ngettext = XLATOR.ngettext
 
-__version__ = '0.4.1'
+__version__ = '0.4.2'
 
 LOG = logging.getLogger(__name__)
 
@@ -480,6 +481,15 @@ class PostfixLogchainInfo(FbGenericBaseObject):
         else:
             self._starttls = DataPair.from_str(val)
 
+    # -------------------------------------------------------------------------
+    def __str__(self):
+        """Typecast into a string object.
+
+        @return: structure as string
+        @rtype:  str
+        """
+        return pp(self.as_dict(exportable=True))
+
     # -------------------------------------------------------------------------
     def __repr__(self):
         """Typecast into a string for reproduction."""
@@ -487,38 +497,12 @@ class PostfixLogchainInfo(FbGenericBaseObject):
 
         fields = []
 
-        if self.client_host is not None:
-            fields.append('client_host={!r}'.format(self.client_host))
-        if self.client_addr is not None:
-            fields.append('client_addr={!r}'.format(str(self.client_addr)))
-        if self.start is not None:
-            if isinstance(self.start, datetime.datetime):
-                ts = self.start.isoformat(' ')
-            else:
-                ts = self.start
-            fields.append('start={!r}'.format(ts))
-        if self.end is not None:
-            if isinstance(self.end, datetime.datetime):
-                ts = self.end.isoformat(' ')
-            else:
-                ts = self.end
-            fields.append('end={!r}'.format(ts))
-        if self.message_id is not None:
-            fields.append('message_id={!r}'.format(self.message_id))
-        if self.postfix_id is not None:
-            fields.append('postfix_id={!r}'.format(self.postfix_id))
-        if self.ehlo is not None:
-            fields.append('ehlo={!r}'.format(str(self.ehlo)))
-        if self.starttls is not None:
-            fields.append('starttls={!r}'.format(str(self.starttls)))
-        if self.sent_quit is not None:
-            fields.append('sent_quit={!r}'.format(str(self.sent_quit)))
-        if self.auth is not None:
-            fields.append('auth={!r}'.format(str(self.auth)))
-        if self.commands is not None:
-            fields.append('commands={!r}'.format(str(self.commands)))
-        if self.rcpt is not None:
-            fields.append('rcpt={!r}'.format(str(self.rcpt)))
+        attr_dict = self.as_dict(exportable=True)
+        for attr in attr_dict.keys():
+            value = attr_dict[attr]
+            if value is None:
+                continue
+            fields.append(f'{attr}={value!r}')
 
         if fields:
             out += ', '.join(fields)
@@ -527,7 +511,7 @@ class PostfixLogchainInfo(FbGenericBaseObject):
         return out
 
     # -------------------------------------------------------------------------
-    def as_dict(self, short=True):
+    def as_dict(self, short=True, exportable=False):
         """
         Transform the elements of the object into a dict.
 
@@ -537,21 +521,37 @@ class PostfixLogchainInfo(FbGenericBaseObject):
         @return: structure as dict
         @rtype:  dict
         """
-        res = super(PostfixLogchainInfo, self).as_dict(short=short)
-
-        res['auth'] = self.auth
-        res['client_addr'] = self.client_addr
-        res['client_host'] = self.client_host
-        res['commands'] = self.commands
-        res['duration'] = self.duration
-        res['ehlo'] = self.ehlo
-        res['end'] = self.end
-        res['message_id'] = self.message_id
-        res['postfix_id'] = self.postfix_id
-        res['rcpt'] = self.rcpt
-        res['sent_quit'] = self.sent_quit
-        res['start'] = self.start
-        res['starttls'] = self.starttls
+        if exportable:
+            res = OrderedDict()
+        else:
+            res = super(PostfixLogchainInfo, self).as_dict(short=short)
+
+        atribs = (
+            'client_host', 'client_addr', 'start', 'end', 'message_id', 'postfix_id', 'ehlo',
+            'starttls', 'sent_quit', 'auth', 'commands', 'rcpt')
+        for attrib in atribs:
+            if not hasattr(self, attrib):
+                continue
+            value = getattr(self, attrib, None)
+            if value is None:
+                res[attrib] = None
+                continue
+            if isinstance(value, ipaddress._BaseAddress):
+                res[attrib] = str(value) if exportable else value
+                continue
+            if isinstance(value, datetime.datetime):
+                res[attrib] = value.isoformat(' ') if exportable else value
+                continue
+            if isinstance(value, DataPair):
+                res[attrib] = str(value) if exportable else value
+                continue
+
+            # Catch all
+            res[attrib] = value
+
+        # Non init properties
+        if not exportable:
+            res['duration'] = self.duration
 
         return res
 
index 904d348adc194ec9be966d0da84477be66dab45a..f814c66cdb825581bcb8b37a2794ef4eef19095d 100755 (executable)
@@ -24,9 +24,10 @@ except ImportError:
 libdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'lib'))
 sys.path.insert(0, libdir)
 
-from general import PpAdminToolsTestcase, get_arg_verbose, init_root_logger
-
 # from fb_tools.common import pp, to_str, is_sequence
+from fb_tools.common import pp
+
+from general import PpAdminToolsTestcase, get_arg_verbose, init_root_logger
 
 APPNAME = 'test-postfix-chain'
 LOG = logging.getLogger(APPNAME)
@@ -72,6 +73,7 @@ class TestPostfixChain(PpAdminToolsTestcase):
         chain = PostfixLogchainInfo()
         LOG.debug('PostfixLogchainInfo %r: {!r}'.format(chain))
         LOG.debug('PostfixLogchainInfo %s:\n{}'.format(chain))
+        LOG.debug('PostfixLogchainInfo as_dict():\n{}'.format(pp(chain.as_dict())))
 
     # -------------------------------------------------------------------------
     def test_filled_object(self):
@@ -106,6 +108,7 @@ class TestPostfixChain(PpAdminToolsTestcase):
         )
         LOG.debug('PostfixLogchainInfo %r: {!r}'.format(chain))
         LOG.debug('PostfixLogchainInfo %s:\n{}'.format(chain))
+        LOG.debug('PostfixLogchainInfo as_dict():\n{}'.format(pp(chain.as_dict())))
 
 
 # =============================================================================