]> Frank Brehm's Git Trees - pixelpark/puppet-tools.git/commitdiff
Adding module dpx_puppettools.config for class DpxPuppetConfig and a test script...
authorFrank Brehm <frank.brehm@pixelpark.com>
Mon, 6 Feb 2023 11:22:32 +0000 (12:22 +0100)
committerFrank Brehm <frank.brehm@pixelpark.com>
Mon, 6 Feb 2023 11:22:32 +0000 (12:22 +0100)
lib/dpx_puppettools/config.py [new file with mode: 0644]
test/test_05_base_app.py [deleted file]
test/test_10_config.py [new file with mode: 0755]
test/test_15_base_app.py [new file with mode: 0755]

diff --git a/lib/dpx_puppettools/config.py b/lib/dpx_puppettools/config.py
new file mode 100644 (file)
index 0000000..513faae
--- /dev/null
@@ -0,0 +1,150 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+"""
+@author: Frank Brehm
+@contact: frank.brehm@pixelpark.com
+@copyright: © 2023 by Frank Brehm, Berlin
+@summary: A module for providing a configuration for different things in this module.
+"""
+from __future__ import absolute_import
+
+# Standard module
+import logging
+import pwd
+import socket
+import os
+import copy
+import re
+
+# Third party modules
+
+from fb_tools.multi_config import MultiConfigError, BaseMultiConfig
+from fb_tools.multi_config import DEFAULT_ENCODING
+
+from fb_tools import MailAddress
+
+# Own modules
+
+from .errors import PuppetToolsError
+
+from .xlate import XLATOR
+
+CONFIG_DIR = 'pixelpark'
+__version__ = '0.1.0'
+LOG = logging.getLogger(__name__)
+VALID_MAIL_METHODS = ('smtp', 'sendmail')
+DEFAULT_DOMAIN = 'pixelpark.com'
+VALID_TIERS = ('prod', 'test', 'dev')
+DEFAULT_TIER = 'prod'
+
+_ = XLATOR.gettext
+
+
+# =============================================================================
+class DpxPuppetConfigError(PuppetToolsError, MultiConfigError):
+    """Base error class for all exceptions happened during
+    evaluation of configuration."""
+
+    pass
+
+
+# =============================================================================
+class DpxPuppetConfig(BaseMultiConfig):
+    """Base class for reading and providing configuration."""
+
+    default_mail_recipients = [
+        'solution@pixelpark.com'
+    ]
+    default_mail_cc = []
+
+    default_reply_to = 'solution@pixelpark.com'
+
+    default_mail_server = 'prd-mail.pixelpark.com'
+    default_smtp_port = 25
+
+    current_user_name = pwd.getpwuid(os.getuid()).pw_name
+    current_user_gecos = pwd.getpwuid(os.getuid()).pw_gecos
+    current_user_gecos = current_user_gecos.strip()
+    current_user_gecos = re.sub(r',+$', '', current_user_gecos)
+    if current_user_gecos == '':
+        current_user_gecos = current_user_name
+
+    default_domain = socket.getfqdn()
+    if default_domain is None:
+        default_domain = DEFAULT_DOMAIN
+    else:
+        default_domain = default_domain.strip()
+        if not MailAddress.re_valid_domain.match(default_domain):
+            default_domain = DEFAULT_DOMAIN
+
+    default_mail_from = MailAddress(user=current_user_name, domain=default_domain)
+    default_mail_from_complete = '{n} <{m}>'.format(n=current_user_gecos, m=default_mail_from)
+
+    valid_mail_methods = VALID_MAIL_METHODS
+    default_mail_method = 'smtp'
+
+    # -------------------------------------------------------------------------
+    def __init__(
+        self, appname=None, verbose=0, version=__version__, base_dir=None,
+            append_appname_to_stems=True, config_dir=CONFIG_DIR, additional_stems=None,
+            additional_cfgdirs=None, encoding=DEFAULT_ENCODING, additional_config_file=None,
+            ensure_privacy=False, use_chardet=True, raise_on_error=True, initialized=False):
+
+        self.mail_recipients = copy.copy(self.default_mail_recipients)
+        self.mail_from = self.default_mail_from_complete
+        self.mail_cc = copy.copy(self.default_mail_cc)
+        self.reply_to = self.default_reply_to
+        self.mail_method = self.default_mail_method
+        self.mail_server = self.default_mail_server
+        self.smtp_port = self.default_smtp_port
+
+        super(DpxPuppetConfig, self).__init__(
+            appname=appname, verbose=verbose, version=version, base_dir=base_dir,
+            append_appname_to_stems=append_appname_to_stems, config_dir=config_dir,
+            additional_stems=additional_stems, additional_cfgdirs=additional_cfgdirs,
+            encoding=encoding, additional_config_file=additional_config_file,
+            ensure_privacy=ensure_privacy, use_chardet=use_chardet,
+            raise_on_error=raise_on_error, initialized=False)
+
+        if initialized:
+            self.initialized = True
+
+    # -------------------------------------------------------------------------
+    def as_dict(self, short=True):
+        """
+        Transforms the elements of the object into a dict
+
+        @param short: don't include local properties in resulting dict.
+        @type short: bool
+
+        @return: structure as dict
+        @rtype:  dict
+        """
+
+        res = super(DpxPuppetConfig, self).as_dict(short=short)
+
+        res['default_mail_recipients'] = self.default_mail_recipients
+        res['default_mail_cc'] = self.default_mail_cc
+        res['default_reply_to'] = self.default_reply_to
+        res['default_mail_server'] = self.default_mail_server
+        res['default_smtp_port'] = self.default_smtp_port
+        res['current_user_name'] = self.current_user_name
+        res['current_user_gecos'] = self.current_user_gecos
+        res['default_mail_from'] = self.default_mail_from
+        res['default_domain'] = self.default_domain
+        res['default_mail_from_complete'] = self.default_mail_from_complete
+        res['default_mail_method'] = self.default_mail_method
+        res['valid_mail_methods'] = self.valid_mail_methods
+
+        return res
+
+
+# =============================================================================
+
+if __name__ == "__main__":
+
+    pass
+
+# =============================================================================
+
+# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4 list
diff --git a/test/test_05_base_app.py b/test/test_05_base_app.py
deleted file mode 100755 (executable)
index 3335a90..0000000
+++ /dev/null
@@ -1,87 +0,0 @@
-#!/usr/bin/env python
-# -*- coding: utf-8 -*-
-'''
-@author: Frank Brehm
-@contact: frank@brehm-online.com
-@copyright: © 2023 Frank Brehm, Digitas Pixelpark GmbH Berlin
-@license: GNU AGPL3
-@summary: test script (and module) for unit tests on base application class
-'''
-
-import os
-import sys
-import logging
-
-try:
-    import unittest2 as unittest
-except ImportError:
-    import unittest
-
-libdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'lib'))
-sys.path.insert(0, libdir)
-
-from general import DpxPuppetToolsTestcase, get_arg_verbose, init_root_logger
-
-LOG = logging.getLogger('test_base_app')
-
-# =============================================================================
-class TestBaseApp(DpxPuppetToolsTestcase):
-
-    # -------------------------------------------------------------------------
-    def setUp(self):
-        pass
-
-    # -------------------------------------------------------------------------
-    def test_import(self):
-
-        LOG.info("Testing import of dpx_puppettools.app ...")
-        import dpx_puppettools.app
-        LOG.debug(
-            "Version of dpx_puppettools.app: " + dpx_puppettools.app.__version__)
-
-    # -------------------------------------------------------------------------
-    def test_init(self):
-
-        LOG.info("Testing init of a BaseDPXPuppetApplication object ...")
-        from dpx_puppettools.app import BaseDPXPuppetApplication
-
-        quiet = False
-        if not self.verbose:
-            quiet = True
-
-        app = BaseDPXPuppetApplication(
-            appname=self.appname, verbose=self.verbose)
-        app.quiet = quiet
-
-        LOG.debug("Drawing lines ...")
-        app.empty_line()
-        app.line(linechar='#', color='CYAN')
-        app.line(width=20)
-
-        LOG.debug("BaseDPXPuppetApplication %%r: %r", app)
-        app.empty_line()
-        LOG.debug("BaseDPXPuppetApplication %%s: %s", str(app))
-
-
-# =============================================================================
-if __name__ == '__main__':
-
-    verbose = get_arg_verbose()
-    if verbose is None:
-        verbose = 0
-    init_root_logger(verbose)
-
-    LOG.info("Starting tests ...")
-
-    suite = unittest.TestSuite()
-
-    suite.addTest(TestBaseApp('test_import', verbose))
-    suite.addTest(TestBaseApp('test_init', verbose))
-
-    runner = unittest.TextTestRunner(verbosity=verbose)
-
-    result = runner.run(suite)
-
-# =============================================================================
-
-# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
diff --git a/test/test_10_config.py b/test/test_10_config.py
new file mode 100755 (executable)
index 0000000..0db551b
--- /dev/null
@@ -0,0 +1,102 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+'''
+@author: Frank Brehm
+@contact: frank.brehm@pixelpark.com
+@copyright: © 2023 by Frank Brehm, Berlin
+@license: GPL3
+@summary: test script (and module) for unit tests on config class
+'''
+
+import os
+import sys
+import logging
+
+from pathlib import Path
+
+try:
+    import unittest2 as unittest
+except ImportError:
+    import unittest
+
+# from babel.dates import LOCALTZ
+
+libdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'lib'))
+sys.path.insert(0, libdir)
+
+from general import DpxPuppetToolsTestcase, get_arg_verbose, init_root_logger
+
+# from fb_tools.common import pp, to_str, is_sequence
+
+LOG = logging.getLogger('test_config')
+
+
+# =============================================================================
+class TestConfig(DpxPuppetToolsTestcase):
+
+    # -------------------------------------------------------------------------
+    def setUp(self):
+
+        self.test_dir = Path(__file__).parent.resolve()
+        self.base_dir = self.test_dir.parent
+        self.test_cfg_dir = self.test_dir / 'test-config'
+        self._appname = 'test_config'
+
+    # -------------------------------------------------------------------------
+    def tearDown(self):
+
+        pass
+
+    # -------------------------------------------------------------------------
+    def test_import(self):
+
+        LOG.info("Testing import of dpx_puppettools.config ...")
+        import dpx_puppettools.config
+        LOG.debug(
+            "Version of dpx_puppettools.config: " + dpx_puppettools.config.__version__)
+
+        LOG.info("Testing import of DpxPuppetConfigError from dpx_puppettools.config ...")
+        from dpx_puppettools.config import DpxPuppetConfigError               # noqa
+
+        LOG.info("Testing import of DpxPuppetConfig from dpx_puppettools.config ...")
+        from dpx_puppettools.config import DpxPuppetConfig                 # noqa
+
+    # -------------------------------------------------------------------------
+    def test_object(self):
+
+        LOG.info("Testing init of a DpxPuppetConfig object.")
+
+        from dpx_puppettools.config import DpxPuppetConfig
+
+        cfg = DpxPuppetConfig(
+            appname=self.appname,
+            config_dir='test', additional_stems='test',
+            verbose=self.verbose,
+        )
+        LOG.debug("DpxPuppetConfig %%r: %r", cfg)
+        LOG.debug("DpxPuppetConfig %%s: %s", str(cfg))
+
+
+# =============================================================================
+if __name__ == '__main__':
+
+    verbose = get_arg_verbose()
+    if verbose is None:
+        verbose = 0
+    init_root_logger(verbose)
+
+    LOG.info("Starting tests ...")
+
+    suite = unittest.TestSuite()
+
+    suite.addTest(TestConfig('test_import', verbose))
+    suite.addTest(TestConfig('test_object', verbose))
+
+    runner = unittest.TextTestRunner(verbosity=verbose)
+
+    result = runner.run(suite)
+
+
+# =============================================================================
+
+# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4
diff --git a/test/test_15_base_app.py b/test/test_15_base_app.py
new file mode 100755 (executable)
index 0000000..3335a90
--- /dev/null
@@ -0,0 +1,87 @@
+#!/usr/bin/env python
+# -*- coding: utf-8 -*-
+'''
+@author: Frank Brehm
+@contact: frank@brehm-online.com
+@copyright: © 2023 Frank Brehm, Digitas Pixelpark GmbH Berlin
+@license: GNU AGPL3
+@summary: test script (and module) for unit tests on base application class
+'''
+
+import os
+import sys
+import logging
+
+try:
+    import unittest2 as unittest
+except ImportError:
+    import unittest
+
+libdir = os.path.abspath(os.path.join(os.path.dirname(__file__), '..', 'lib'))
+sys.path.insert(0, libdir)
+
+from general import DpxPuppetToolsTestcase, get_arg_verbose, init_root_logger
+
+LOG = logging.getLogger('test_base_app')
+
+# =============================================================================
+class TestBaseApp(DpxPuppetToolsTestcase):
+
+    # -------------------------------------------------------------------------
+    def setUp(self):
+        pass
+
+    # -------------------------------------------------------------------------
+    def test_import(self):
+
+        LOG.info("Testing import of dpx_puppettools.app ...")
+        import dpx_puppettools.app
+        LOG.debug(
+            "Version of dpx_puppettools.app: " + dpx_puppettools.app.__version__)
+
+    # -------------------------------------------------------------------------
+    def test_init(self):
+
+        LOG.info("Testing init of a BaseDPXPuppetApplication object ...")
+        from dpx_puppettools.app import BaseDPXPuppetApplication
+
+        quiet = False
+        if not self.verbose:
+            quiet = True
+
+        app = BaseDPXPuppetApplication(
+            appname=self.appname, verbose=self.verbose)
+        app.quiet = quiet
+
+        LOG.debug("Drawing lines ...")
+        app.empty_line()
+        app.line(linechar='#', color='CYAN')
+        app.line(width=20)
+
+        LOG.debug("BaseDPXPuppetApplication %%r: %r", app)
+        app.empty_line()
+        LOG.debug("BaseDPXPuppetApplication %%s: %s", str(app))
+
+
+# =============================================================================
+if __name__ == '__main__':
+
+    verbose = get_arg_verbose()
+    if verbose is None:
+        verbose = 0
+    init_root_logger(verbose)
+
+    LOG.info("Starting tests ...")
+
+    suite = unittest.TestSuite()
+
+    suite.addTest(TestBaseApp('test_import', verbose))
+    suite.addTest(TestBaseApp('test_init', verbose))
+
+    runner = unittest.TextTestRunner(verbosity=verbose)
+
+    result = runner.run(suite)
+
+# =============================================================================
+
+# vim: tabstop=4 expandtab shiftwidth=4 softtabstop=4