Split exceptions into their own file
authorKarl O. Pinc <kop@karlpinc.com>
Fri, 28 Aug 2020 00:13:31 +0000 (19:13 -0500)
committerKarl O. Pinc <kop@karlpinc.com>
Fri, 28 Aug 2020 00:13:31 +0000 (19:13 -0500)
src/pgwui_server/__init__.py
src/pgwui_server/constants.py [new file with mode: 0644]
src/pgwui_server/exceptions.py [new file with mode: 0644]
tests/test___init__.py

index 3651a2c81836b922f537a03189c627b0bcb3f0b3..378b141aa87b333b412650253414f9d73eeeca9d 100644 (file)
@@ -27,6 +27,8 @@ from pyramid.config import Configurator
 import logging
 import sys
 
+from . import exceptions
+from . import constants
 from pgwui_common import plugin
 
 # Constants
@@ -44,72 +46,11 @@ SETTINGS = set(
      'literal_column_headings',
      ])
 
-# Required length of HMAC value
-HMAC_LEN = 40
-
 
 # Logging
 log = logging.getLogger(__name__)
 
 
-# Exceptions
-class Error(Exception):
-    '''Base error class for module
-    '''
-    pass
-
-
-class AutoconfigureConflict(Error):
-    def __init__(self):
-        super().__init__(
-            'Autoconfigure is True and there is a pyramid.include setting')
-
-
-class BadSettingsAbort(Error):
-    def __init__(self):
-        super().__init__('Aborting due to bad setting(s)')
-
-
-class UnknownSettingKeyError(Error):
-    def __init__(self, key):
-        super().__init__('Unknown PGWUI setting: {}'.format(key))
-
-
-class MissingSettingError(Error):
-    def __init__(self, key):
-        super().__init__('Missing PGWUI setting: {}'.format(key))
-
-
-class NotBooleanSettingError(Error):
-    def __init__(self, key, value):
-        super().__init__(
-            'The "{}" PGWUI setting must be "True" or "False"'
-            .format(key))
-
-
-class BadLiteralColumnHeadingsError(Error):
-    def __init__(self, value):
-        super().__init__(
-            'The "pgwui.literal_column_headings" PGWUI setting must be'
-            '"on", "off", "ask", or not present')
-
-
-class BadHMACError(Error):
-    pass
-
-
-class NoHMACError(BadHMACError):
-    def __init__(self):
-        super().__init__('Missing session.secret configuration')
-
-
-class HMACLengthError(BadHMACError):
-    def __init__(self):
-        super().__init__(
-            'The session.secret value is not {} characters in length'
-            .format(HMAC_LEN))
-
-
 # Functions
 
 def abort_on_bad_setting(errors, key, component_keys):
@@ -118,12 +59,12 @@ def abort_on_bad_setting(errors, key, component_keys):
     if key[:6] == 'pgwui.':
         if (key[6:] not in SETTINGS
                 and key not in component_keys):
-            errors.append(UnknownSettingKeyError(key))
+            errors.append(exceptions.UnknownSettingKeyError(key))
 
 
 def require_setting(errors, setting, settings):
     if setting not in settings:
-        errors.append(MissingSettingError(setting))
+        errors.append(exceptions.MissingSettingError(setting))
 
 
 def boolean_setting(errors, setting, settings):
@@ -131,7 +72,8 @@ def boolean_setting(errors, setting, settings):
         val = literal_eval(settings[setting])
         if (val is not True
                 and val is not False):
-            errors.append(NotBooleanSettingError(setting, settings[setting]))
+            errors.append(exceptions.NotBooleanSettingError(
+                setting, settings[setting]))
 
 
 def validate_setting_values(errors, settings):
@@ -171,11 +113,11 @@ def validate_hmac(errors, settings):
         return
 
     if 'session.secret' not in settings:
-        errors.append(NoHMACError())
+        errors.append(exceptions.NoHMACError())
         return
 
-    if len(settings['session.secret']) != HMAC_LEN:
-        errors.append(HMACLengthError())
+    if len(settings['session.secret']) != constants.HMAC_LEN:
+        errors.append(exceptions.HMACLengthError())
         return
 
 
@@ -186,7 +128,7 @@ def validate_literal_column_headings(errors, settings):
     if value is None:
         return
     if value not in ('on', 'off', 'ask'):
-        errors.append(BadLiteralColumnHeadingsError(value))
+        errors.append(exceptions.BadLiteralColumnHeadingsError(value))
 
 
 def parse_assignments(lines):
@@ -227,7 +169,7 @@ def exit_reporting_errors(errors):
     '''Report errors and exit
     '''
     tagged = [(logging.ERROR, error) for error in errors]
-    tagged.append((logging.CRITICAL, BadSettingsAbort()))
+    tagged.append((logging.CRITICAL, exceptions.BadSettingsAbort()))
 
     for (level, error) in tagged:
         log.log(level, error)
@@ -264,7 +206,7 @@ def autoconfigurable_components(settings, components):
         return []
 
     if 'pyramid.include' in settings:
-        log.info(AutoconfigureConflict())
+        log.info(exceptions.AutoconfigureConflict())
 
     return components
 
diff --git a/src/pgwui_server/constants.py b/src/pgwui_server/constants.py
new file mode 100644 (file)
index 0000000..737e3fd
--- /dev/null
@@ -0,0 +1,27 @@
+# Copyright (C) 2020 The Meme Factory, Inc.  http://www.karlpinc.com/
+
+# This file is part of PGWUI_Server.
+#
+# This program is free software: you can redistribute it and/or
+# modify it under the terms of the GNU Affero General Public License
+# as published by the Free Software Foundation, either version 3 of
+# the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public
+# License along with this program.  If not, see
+# <http://www.gnu.org/licenses/>.
+#
+
+# Karl O. Pinc <kop@karlpinc.com>
+
+'''Constants shared by multiple modules
+'''
+
+
+# Required length of HMAC value
+HMAC_LEN = 40
diff --git a/src/pgwui_server/exceptions.py b/src/pgwui_server/exceptions.py
new file mode 100644 (file)
index 0000000..6b45cd9
--- /dev/null
@@ -0,0 +1,82 @@
+# Copyright (C) 2018, 2019 The Meme Factory, Inc.  http://www.karlpinc.com/
+
+# This file is part of PGWUI_Server.
+#
+# This program is free software: you can redistribute it and/or
+# modify it under the terms of the GNU Affero General Public License
+# as published by the Free Software Foundation, either version 3 of
+# the License, or (at your option) any later version.
+#
+# This program is distributed in the hope that it will be useful, but
+# WITHOUT ANY WARRANTY; without even the implied warranty of
+# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+# Affero General Public License for more details.
+#
+# You should have received a copy of the GNU Affero General Public
+# License along with this program.  If not, see
+# <http://www.gnu.org/licenses/>.
+#
+
+# Karl O. Pinc <kop@karlpinc.com>
+
+'''Exceptions for PGWUI_Server
+'''
+
+from . import constants
+
+
+class Error(Exception):
+    '''Base error class for module
+    '''
+    pass
+
+
+class AutoconfigureConflict(Error):
+    def __init__(self):
+        super().__init__(
+            'Autoconfigure is True and there is a pyramid.include setting')
+
+
+class BadSettingsAbort(Error):
+    def __init__(self):
+        super().__init__('Aborting due to bad setting(s)')
+
+
+class UnknownSettingKeyError(Error):
+    def __init__(self, key):
+        super().__init__('Unknown PGWUI setting: {}'.format(key))
+
+
+class MissingSettingError(Error):
+    def __init__(self, key):
+        super().__init__('Missing PGWUI setting: {}'.format(key))
+
+
+class NotBooleanSettingError(Error):
+    def __init__(self, key, value):
+        super().__init__(
+            'The "{}" PGWUI setting must be "True" or "False"'
+            .format(key))
+
+
+class BadLiteralColumnHeadingsError(Error):
+    def __init__(self, value):
+        super().__init__(
+            'The "pgwui.literal_column_headings" PGWUI setting must be'
+            '"on", "off", "ask", or not present')
+
+
+class BadHMACError(Error):
+    pass
+
+
+class NoHMACError(BadHMACError):
+    def __init__(self):
+        super().__init__('Missing session.secret configuration')
+
+
+class HMACLengthError(BadHMACError):
+    def __init__(self):
+        super().__init__(
+            'The session.secret value is not {} characters in length'
+            .format(constants.HMAC_LEN))
index a350099f252538f210e622ac739ea124bec43a92..8c8f0020226edc07a07c916e4c30358f40187aff 100644 (file)
@@ -30,6 +30,8 @@ import pgwui_common.plugin
 # Use as a regular module, not a plugin, so lint checks work
 from pgwui_testing import testing
 
+import pgwui_server.constants as constants
+import pgwui_server.exceptions as ex
 import pgwui_server.__init__ as pgwui_server_init
 
 
@@ -86,7 +88,7 @@ def test_abort_on_bad_setting_bad():
     pgwui_server_init.abort_on_bad_setting(errors, 'pgwui.foo', [])
 
     assert errors
-    assert isinstance(errors[0], pgwui_server_init.UnknownSettingKeyError)
+    assert isinstance(errors[0], ex.UnknownSettingKeyError)
 
 
 def test_abort_on_bad_setting_good():
@@ -118,7 +120,7 @@ def test_require_setting_missing():
     pgwui_server_init.require_setting(errors, 'key', {})
 
     assert errors
-    assert isinstance(errors[0], pgwui_server_init.MissingSettingError)
+    assert isinstance(errors[0], ex.MissingSettingError)
 
 
 def test_require_setting_present():
@@ -165,7 +167,7 @@ def test_boolean_setting_notboolean():
     pgwui_server_init.boolean_setting(errors, 'key', {'key': '0'})
 
     assert errors
-    assert isinstance(errors[0], pgwui_server_init.NotBooleanSettingError)
+    assert isinstance(errors[0], ex.NotBooleanSettingError)
 
 
 mock_boolean_setting = testing.make_mock_fixture(
@@ -228,7 +230,7 @@ def test_validate_hmac_success(mock_do_validate_hmac):
     mock_do_validate_hmac.return_value = True
     errors = []
     pgwui_server_init.validate_hmac(
-        errors, {'session.secret': 'x' * pgwui_server_init.HMAC_LEN})
+        errors, {'session.secret': 'x' * constants.HMAC_LEN})
 
     assert errors == []
 
@@ -240,7 +242,7 @@ def test_validate_hmac_missing(mock_do_validate_hmac):
     pgwui_server_init.validate_hmac(errors, {})
 
     assert errors
-    assert isinstance(errors[0], pgwui_server_init.NoHMACError)
+    assert isinstance(errors[0], ex.NoHMACError)
 
 
 def test_validate_hmac_length(mock_do_validate_hmac):
@@ -250,7 +252,7 @@ def test_validate_hmac_length(mock_do_validate_hmac):
     pgwui_server_init.validate_hmac(errors, {'session.secret': ''})
 
     assert errors
-    assert isinstance(errors[0], pgwui_server_init.HMACLengthError)
+    assert isinstance(errors[0], ex.HMACLengthError)
 
 
 mock_validate_hmac = testing.make_mock_fixture(
@@ -302,7 +304,7 @@ def test_validate_literal_column_headings_bad():
 
     assert errors
     assert isinstance(
-        errors[0], pgwui_server_init.BadLiteralColumnHeadingsError)
+        errors[0], ex.BadLiteralColumnHeadingsError)
 
 
 mock_validate_literal_column_headings = testing.make_mock_fixture(
@@ -607,17 +609,17 @@ def test_main_integrated():
 
 def test_unknownsettingkeyerror():
     '''Takes an argument'''
-    assert isinstance(pgwui_server_init.UnknownSettingKeyError('key'),
-                      pgwui_server_init.Error)
+    assert isinstance(ex.UnknownSettingKeyError('key'),
+                      ex.Error)
 
 
 def test_missingsettingerror():
     '''Takes an argument'''
-    assert isinstance(pgwui_server_init.MissingSettingError('key'),
-                      pgwui_server_init.Error)
+    assert isinstance(ex.MissingSettingError('key'),
+                      ex.Error)
 
 
 def test_notbooleansettingerror():
     '''Takes two arguments'''
-    assert isinstance(pgwui_server_init.NotBooleanSettingError('key', 'val'),
-                      pgwui_server_init.Error)
+    assert isinstance(ex.NotBooleanSettingError('key', 'val'),
+                      ex.Error)