Browse Source

Class Validator replaces SettingValidator

prieto 7 years ago
parent
commit
08ad11624d

+ 0
- 42
lodel/leapi/datahandlers/validator.py View File

@@ -1,42 +0,0 @@
1
-#-*- coding: utf-8 -*-
2
-
3
-import sys
4
-
5
-from lodel.context import LodelContext
6
-LodelContext.expose_modules(globals(), {
7
-    'lodel.exceptions': ['LodelException', 'LodelExceptions',
8
-        'LodelFatalError', 'FieldValidationError'],
9
-    'lodel.validator.validator': ['Validator', 'ValidationError']})
10
-
11
-## @package lodel.DhOptions.validator Lodel2 DhOptions validators/cast module
12
-#
13
-# Validator are registered in the DhOptionValidator class.
14
-# @note to get a list of registered default validators just run
15
-# <pre>$ python scripts/DhOptions_validator.py</pre>
16
-
17
-##@brief Exception class that should be raised when a validation fails
18
-class DhOptionValidationError(ValidationError):
19
-    pass
20
-
21
-##@brief Handles DhOptions validators
22
-#
23
-# Class instance are callable objects that takes a value argument (the value to validate). It raises
24
-# a DhOptionsValidationError if validation fails, else it returns a properly
25
-# casted value.
26
-#@todo implement an IP validator and use it in multisite confspec
27
-class DhOptionValidator(Validator):
28
-
29
-    ##@brief Instanciate a validator
30
-    #@param name str : validator name
31
-    #@param none_is_valid bool : if True None will be validated
32
-    #@param **kwargs : more arguement for the validator
33
-    def __init__(self, name, none_is_valid = False, **kwargs):
34
-        super().__init__(name, none_is_valid = False, **kwargs)
35
-
36
-    ##@brief Call the validator
37
-    # @param value *
38
-    # @return properly casted value
39
-    # @throw DhOptionsValidationError
40
-    def __call__(self, value):
41
-        super().__call__(value)
42
-

+ 6
- 6
lodel/plugin/datasource_plugin.py View File

@@ -3,7 +3,7 @@ LodelContext.expose_modules(globals(), {
3 3
     'lodel.plugin.plugins': ['Plugin'],
4 4
     'lodel.plugin.exceptions': ['PluginError', 'PluginTypeError',
5 5
         'LodelScriptError', 'DatasourcePluginError'],
6
-    'lodel.settings.validator': ['SettingValidator'],
6
+    'lodel.validator.validator': ['Validator'],
7 7
     'lodel.exceptions': ['LodelException', 'LodelExceptions',
8 8
         'LodelFatalError', 'DataNoneValid', 'FieldValidationError']})
9 9
 
@@ -97,7 +97,7 @@ class DatasourcePlugin(Plugin):
97 97
         'section': 'lodel2',
98 98
         'key': 'datasource_connectors',
99 99
         'default': 'dummy_datasource',
100
-        'validator': SettingValidator(
100
+        'validator': Validator(
101 101
             'custom_list', none_is_valid = False,
102 102
             validator_name = 'plugin', validator_kwargs = {
103 103
                 'ptype': _glob_typename,
@@ -280,13 +280,13 @@ but %s is a %s" % (ds_name, pinstance.__class__.__name__))
280 280
 #CONFSPEC = {
281 281
 #                'lodel2.datasource.mysql.*' : {
282 282
 #                    'host': (   'localhost',
283
-#                                SettingValidator('host')),
283
+#                                Validator('host')),
284 284
 #                    'db_name': (    'lodel',
285
-#                                    SettingValidator('string')),
285
+#                                    Validator('string')),
286 286
 #                    'username': (   None,
287
-#                                    SettingValidator('string')),
287
+#                                    Validator('string')),
288 288
 #                    'password': (   None,
289
-#                                    SettingValidator('string')),
289
+#                                    Validator('string')),
290 290
 #                }
291 291
 #}
292 292
 #</pre>

+ 2
- 2
lodel/plugin/extensions.py View File

@@ -3,7 +3,7 @@ LodelContext.expose_modules(globals(), {
3 3
     'lodel.plugin.plugins': ['Plugin'],
4 4
     'lodel.plugin.exceptions': ['PluginError', 'PluginTypeError',
5 5
         'LodelScriptError', 'DatasourcePluginError'],
6
-    'lodel.settings.validator': ['SettingValidator']})
6
+    'lodel.validator.validator': ['Validator']})
7 7
 
8 8
 _glob_typename = 'extension'
9 9
 
@@ -14,7 +14,7 @@ class Extension(Plugin):
14 14
         'section': 'lodel2',
15 15
         'key': 'extensions',
16 16
         'default': None,
17
-        'validator': SettingValidator(
17
+        'validator': Validator(
18 18
             'custom_list', none_is_valid = True,
19 19
             validator_name = 'plugin', validator_kwargs = {
20 20
                 'ptype': _glob_typename,

+ 2
- 2
lodel/plugin/interface.py View File

@@ -3,7 +3,7 @@ LodelContext.expose_modules(globals(), {
3 3
     'lodel.plugin.plugins': ['Plugin'],
4 4
     'lodel.plugin.exceptions': ['PluginError', 'PluginTypeError',
5 5
         'LodelScriptError', 'DatasourcePluginError'],
6
-    'lodel.settings.validator': ['SettingValidator']})
6
+    'lodel.validator.validator': ['Validator']})
7 7
 
8 8
 _glob_typename = 'ui'
9 9
 
@@ -19,7 +19,7 @@ class InterfacePlugin(Plugin):
19 19
         'section': 'lodel2',
20 20
         'key': 'interface',
21 21
         'default': None,
22
-        'validator': SettingValidator(
22
+        'validator': Validator(
23 23
             'plugin', none_is_valid = True, ptype = _glob_typename)}
24 24
 
25 25
     _type_conf_name = _glob_typename

+ 2
- 2
lodel/plugin/sessionhandler.py View File

@@ -3,7 +3,7 @@ LodelContext.expose_modules(globals(), {
3 3
     'lodel.plugin.plugins': ['Plugin', 'MetaPlugType'],
4 4
     'lodel.plugin.exceptions': ['PluginError', 'PluginTypeError',
5 5
         'LodelScriptError', 'DatasourcePluginError'],
6
-    'lodel.settings.validator': ['SettingValidator']})
6
+    'lodel.validator.validator': ['Validator']})
7 7
 
8 8
 
9 9
 ##@brief SessionHandlerPlugin metaclass designed to implements a wrapper
@@ -53,7 +53,7 @@ class SessionHandlerPlugin(Plugin, metaclass=SessionPluginWrapper):
53 53
         'section': 'lodel2',
54 54
         'key': 'session_handler',
55 55
         'default': None,
56
-        'validator': SettingValidator(
56
+        'validator': Validator(
57 57
             'plugin', none_is_valid=False,ptype = _glob_typename)}
58 58
 
59 59
     _type_conf_name = _glob_typename

+ 1
- 1
lodel/plugins/dummy/__init__.py View File

@@ -1,6 +1,6 @@
1 1
 from lodel.context import LodelContext
2 2
 LodelContext.expose_modules(globals(), {
3
-    'lodel.settings.validator': ['SettingValidator']})
3
+    'lodel.validator.validator': ['Validator']})
4 4
 
5 5
 __plugin_name__ = "dummy"
6 6
 __version__ = '0.0.1' #or __version__ = [0,0,1]

+ 2
- 2
lodel/plugins/dummy/confspec.py View File

@@ -2,11 +2,11 @@
2 2
 
3 3
 from lodel.context import LodelContext
4 4
 LodelContext.expose_modules(globals(), {
5
-    'lodel.settings.validator': ['SettingValidator']})
5
+    'lodel.validator.validator': ['Validator']})
6 6
 
7 7
 CONFSPEC = {
8 8
     'lodel2.section1': {
9 9
         'key1': (   None,
10
-                    SettingValidator('dummy'))
10
+                    Validator('dummy'))
11 11
     }
12 12
 }

+ 2
- 2
lodel/plugins/dummy_datasource/__init__.py View File

@@ -1,6 +1,6 @@
1 1
 from lodel.context import LodelContext
2 2
 LodelContext.expose_modules(globals(), {
3
-    'lodel.settings.validator': ['SettingValidator']})
3
+    'lodel.validator.validator': ['Validator']})
4 4
 from .datasource import DummyDatasource as Datasource
5 5
 
6 6
 __plugin_type__ = 'datasource'
@@ -12,7 +12,7 @@ __plugin_deps__ = []
12 12
 CONFSPEC = {
13 13
     'lodel2.datasource.dummy_datasource.*' : {
14 14
         'dummy': (  None,
15
-                    SettingValidator('dummy'))}
15
+                    Validator('dummy'))}
16 16
 }
17 17
 
18 18
 

+ 1
- 1
lodel/plugins/filesystem_session/__init__.py View File

@@ -1,6 +1,6 @@
1 1
 from lodel.context import LodelContext
2 2
 LodelContext.expose_modules(globals(), {
3
-    'lodel.settings.validator': ['SettingValidator']})
3
+    'lodel.validator.validator': ['Validator']})
4 4
 
5 5
 __plugin_name__ = 'filesystem_session'
6 6
 __version__ = [0,0,1]

+ 4
- 4
lodel/plugins/filesystem_session/confspec.py View File

@@ -2,12 +2,12 @@
2 2
 
3 3
 from lodel.context import LodelContext
4 4
 LodelContext.expose_modules(globals(), {
5
-    'lodel.settings.validator': ['SettingValidator']})
5
+    'lodel.validator.validator': ['Validator']})
6 6
 
7 7
 CONFSPEC = {
8 8
     'lodel2.sessions':{
9
-        'directory': ('/tmp/', SettingValidator('path')),
10
-        'expiration': (900, SettingValidator('int')),
11
-        'file_template': ('lodel2_%s.sess', SettingValidator('dummy'))
9
+        'directory': ('/tmp/', Validator('path')),
10
+        'expiration': (900, Validator('int')),
11
+        'file_template': ('lodel2_%s.sess', Validator('dummy'))
12 12
     }
13 13
 }

+ 7
- 7
lodel/plugins/mongodb_datasource/confspec.py View File

@@ -2,7 +2,7 @@
2 2
 
3 3
 from lodel.context import LodelContext
4 4
 LodelContext.expose_modules(globals(), {
5
-    'lodel.settings.validator': ['SettingValidator']})
5
+    'lodel.validator.validator': ['Validator']})
6 6
 
7 7
 ##@brief Mongodb datasource plugin confspec
8 8
 #@ingroup plugin_mongodb_datasource
@@ -10,11 +10,11 @@ LodelContext.expose_modules(globals(), {
10 10
 #Describe mongodb plugin configuration. Keys are :
11 11
 CONFSPEC = {
12 12
     'lodel2.datasource.mongodb_datasource.*':{
13
-        'read_only': (False, SettingValidator('bool')),
14
-        'host': ('localhost', SettingValidator('host')),
15
-        'port': (None, SettingValidator('string', none_is_valid = True)),
16
-        'db_name':('lodel', SettingValidator('string')),
17
-        'username': (None, SettingValidator('string')),
18
-        'password': (None, SettingValidator('string'))
13
+        'read_only': (False, Validator('bool')),
14
+        'host': ('localhost', Validator('host')),
15
+        'port': (None, Validator('string', none_is_valid = True)),
16
+        'db_name':('lodel', Validator('string')),
17
+        'username': (None, Validator('string')),
18
+        'password': (None, Validator('string'))
19 19
     }
20 20
 }

+ 3
- 3
lodel/plugins/multisite/__init__.py View File

@@ -1,7 +1,7 @@
1 1
 from lodel.context import LodelContext, ContextError
2 2
 try:
3 3
     LodelContext.expose_modules(globals(), {
4
-        'lodel.settings.validator': ['SettingValidator']})
4
+        'lodel.validator.validator': ['Validator']})
5 5
 
6 6
     __plugin_name__ = "multisite"
7 7
     __version__ = '0.0.1' #or __version__ = [0,0,1]
@@ -13,8 +13,8 @@ try:
13 13
 
14 14
     CONFSPEC = {
15 15
         'lodel2.server': {
16
-            'port': (80,SettingValidator('int')),
17
-            'listen_addr': ('', SettingValidator('string')),
16
+            'port': (80,Validator('int')),
17
+            'listen_addr': ('', Validator('string')),
18 18
         }
19 19
     }
20 20
 

+ 15
- 15
lodel/plugins/multisite/confspecs.py View File

@@ -1,34 +1,34 @@
1 1
 from lodel.context import LodelContext
2 2
 LodelContext.expose_modules(globals(), {
3
-    'lodel.settings.validator': ['SettingValidator']})
3
+    'lodel.validator.validator': ['Validator']})
4 4
 
5 5
 #Define a minimal confspec used by multisite loader
6 6
 LODEL2_CONFSPECS = {
7 7
     'lodel2': {
8
-        'debug': (True, SettingValidator('bool'))
8
+        'debug': (True, Validator('bool'))
9 9
     },
10 10
     'lodel2.server': {
11
-        'listen_address': ('127.0.0.1', SettingValidator('dummy')),
12
-        #'listen_address': ('', SettingValidator('ip')), #<-- not implemented
13
-        'listen_port': ( 1337, SettingValidator('int')),
14
-        'uwsgi_workers': (8, SettingValidator('int')),
15
-        'uwsgicmd': ('/usr/bin/uwsgi', SettingValidator('dummy')),
16
-        'virtualenv': (None, SettingValidator('path', none_is_valid = True)),
11
+        'listen_address': ('127.0.0.1', Validator('dummy')),
12
+        #'listen_address': ('', Validator('ip')), #<-- not implemented
13
+        'listen_port': ( 1337, Validator('int')),
14
+        'uwsgi_workers': (8, Validator('int')),
15
+        'uwsgicmd': ('/usr/bin/uwsgi', Validator('dummy')),
16
+        'virtualenv': (None, Validator('path', none_is_valid = True)),
17 17
     },
18 18
     'lodel2.logging.*' : {
19 19
         'level': (  'ERROR',
20
-                    SettingValidator('loglevel')),
20
+                    Validator('loglevel')),
21 21
         'context': (    False,
22
-                        SettingValidator('bool')),
22
+                        Validator('bool')),
23 23
         'filename': (   None,
24
-                        SettingValidator('errfile', none_is_valid = True)),
24
+                        Validator('errfile', none_is_valid = True)),
25 25
         'backupcount': (    10,
26
-                            SettingValidator('int', none_is_valid = False)),
26
+                            Validator('int', none_is_valid = False)),
27 27
         'maxbytes': (   1024*10,
28
-                        SettingValidator('int', none_is_valid = False)),
28
+                        Validator('int', none_is_valid = False)),
29 29
     },
30 30
     'lodel2.datasources.*': {
31
-        'read_only': (False, SettingValidator('bool')),
32
-        'identifier': ( None, SettingValidator('string')),
31
+        'read_only': (False, Validator('bool')),
32
+        'identifier': ( None, Validator('string')),
33 33
     }
34 34
 }

+ 3
- 3
lodel/plugins/ram_sessions/__init__.py View File

@@ -1,6 +1,6 @@
1 1
 from lodel.context import LodelContext
2 2
 LodelContext.expose_modules(globals(), {
3
-    'lodel.settings.validator': ['SettingValidator']})
3
+    'lodel.validator.validator': ['Validator']})
4 4
 
5 5
 __plugin_name__ = 'ram_sessions'
6 6
 __version__ = [0,0,1]
@@ -11,7 +11,7 @@ __fullname__ = "RAM Session Store Plugin"
11 11
 
12 12
 CONFSPEC = {
13 13
     'lodel2.sessions':{
14
-        'expiration': (900, SettingValidator('int')),
15
-        'tokensize': (512, SettingValidator('int')),
14
+        'expiration': (900, Validator('int')),
15
+        'tokensize': (512, Validator('int')),
16 16
     }
17 17
 }

+ 13
- 13
lodel/plugins/webui/confspec.py View File

@@ -1,30 +1,30 @@
1 1
 from lodel.context import LodelContext
2 2
 LodelContext.expose_modules(globals(), {
3
-    'lodel.settings.validator': ['SettingValidator']})
3
+    'lodel.validator.validator': ['Validator']})
4 4
 
5 5
 CONFSPEC = {
6 6
     'lodel2.webui': {
7 7
         'standalone': ( 'False',
8
-                        SettingValidator('string')),
8
+                        Validator('string')),
9 9
         'listen_address': ( '127.0.0.1',
10
-                            SettingValidator('dummy')),
10
+                            Validator('dummy')),
11 11
         'listen_port': (    '9090',
12
-                            SettingValidator('int')),
12
+                            Validator('int')),
13 13
         'static_url': (     'http://127.0.0.1/static/',
14
-                            SettingValidator('regex', pattern =  r'^https?://[^/].*$')),
14
+                            Validator('regex', pattern =  r'^https?://[^/].*$')),
15 15
         'virtualenv': (None,
16
-                       SettingValidator('path', none_is_valid=True)),
17
-        'uwsgicmd': ('/usr/bin/uwsgi', SettingValidator('dummy')),
18
-        'cookie_secret_key': ('ConfigureYourOwnCookieSecretKey', SettingValidator('dummy')),
19
-        'cookie_session_id': ('lodel', SettingValidator('dummy')),
20
-        'uwsgi_workers': (2, SettingValidator('int'))
16
+                       Validator('path', none_is_valid=True)),
17
+        'uwsgicmd': ('/usr/bin/uwsgi', Validator('dummy')),
18
+        'cookie_secret_key': ('ConfigureYourOwnCookieSecretKey', Validator('dummy')),
19
+        'cookie_session_id': ('lodel', Validator('dummy')),
20
+        'uwsgi_workers': (2, Validator('int'))
21 21
     },
22 22
     'lodel2.webui.sessions': {
23 23
         'directory': (  '/tmp',
24
-                        SettingValidator('path')),
24
+                        Validator('path')),
25 25
         'expiration': ( 900,
26
-                        SettingValidator('int')),
26
+                        Validator('int')),
27 27
         'file_template': (  'lodel2_%s.sess',
28
-                            SettingValidator('dummy')),
28
+                            Validator('dummy')),
29 29
     }
30 30
 }

+ 1
- 1
lodel/settings/settings.py View File

@@ -13,7 +13,7 @@ from lodel.context import LodelContext
13 13
 LodelContext.expose_modules(globals(),{
14 14
     'lodel.logger': 'logger',
15 15
     'lodel.settings.utils': ['SettingsError', 'SettingsErrors'],
16
-    'lodel.settings.validator': ['SettingValidator', 'LODEL2_CONF_SPECS',
16
+    'lodel.validator.validator': ['Validator', 'LODEL2_CONF_SPECS',
17 17
         'confspec_append'],
18 18
     'lodel.settings.settings_loader':['SettingsLoader']})
19 19
     

+ 1
- 1
lodel/settings/settings_loader.py View File

@@ -9,7 +9,7 @@ from lodel.context import LodelContext
9 9
 LodelContext.expose_modules(globals(), {
10 10
     'lodel.logger': 'logger',
11 11
     'lodel.settings.utils': ['SettingsError', 'SettingsErrors'],
12
-    'lodel.settings.validator': ['SettingValidationError']})
12
+    'lodel.validator.validator': ['ValidationError']})
13 13
 
14 14
 ##@brief Merges and loads configuration files
15 15
 class SettingsLoader(object):

+ 0
- 166
lodel/settings/validator.py View File

@@ -1,169 +1,3 @@
1 1
 #-*- coding: utf-8 -*-
2 2
 
3
-import sys
4
-import os.path
5
-import re
6
-import socket
7
-import inspect
8
-import copy
9 3
 
10
-from lodel.context import LodelContext
11
-LodelContext.expose_modules(globals(), {
12
-    'lodel.exceptions': ['LodelException', 'LodelExceptions',
13
-        'LodelFatalError', 'FieldValidationError'],
14
-    'lodel.validator.validator': ['Validator', 'ValidationError']})
15
-
16
-## @package lodel.settings.validator Lodel2 settings validators/cast module
17
-#
18
-# Validator are registered in the SettingValidator class.
19
-# @note to get a list of registered default validators just run
20
-# <pre>$ python scripts/settings_validator.py</pre>
21
-
22
-##@brief Exception class that should be raised when a validation fails
23
-class SettingValidationError(ValidationError):
24
-    pass
25
-
26
-##@brief Handles settings validators
27
-#
28
-# Class instance are callable objects that takes a value argument (the value to validate). It raises
29
-# a SettingsValidationError if validation fails, else it returns a properly
30
-# casted value.
31
-#@todo implement an IP validator and use it in multisite confspec
32
-class SettingValidator(Validator):
33
-
34
-    ##@brief Instanciate a validator
35
-    #@param name str : validator name
36
-    #@param none_is_valid bool : if True None will be validated
37
-    #@param **kwargs : more arguement for the validator
38
-    def __init__(self, name, none_is_valid = False, **kwargs):
39
-        super().__init__(name, none_is_valid = False, **kwargs)
40
-
41
-    ##@brief Call the validator
42
-    # @param value *
43
-    # @return properly casted value
44
-    # @throw SettingsValidationError
45
-    def __call__(self, value):
46
-        super().__call__(value)
47
-
48
-##@brief Validator for Editorial model component
49
-#
50
-# Designed to validate a conf that indicate a class.field in an EM
51
-#@todo modified the hardcoded dyncode import (it's a warning)
52
-def emfield_val(value):
53
-    LodelContext.expose_modules(globals(), {
54
-        'lodel.plugin.hooks': ['LodelHook']})
55
-    spl = value.split('.')
56
-    if len(spl) != 2:
57
-        msg = "Expected a value in the form CLASSNAME.FIELDNAME but got : %s"
58
-        raise SettingsValidationError(msg % value)
59
-    value = tuple(spl)
60
-    #Late validation hook
61
-    @LodelHook('lodel2_dyncode_bootstraped')
62
-    def emfield_conf_check(hookname, caller, payload):
63
-        import leapi_dyncode as dyncode # <-- dirty & quick
64
-        classnames = { cls.__name__.lower():cls for cls in dyncode.dynclasses}
65
-        if value[0].lower() not in classnames:
66
-            msg = "Following dynamic class do not exists in current EM : %s"
67
-            raise SettingsValidationError(msg % value[0])
68
-        ccls = classnames[value[0].lower()]
69
-        if value[1].lower() not in ccls.fieldnames(True):
70
-            msg = "Following field not found in class %s : %s"
71
-            raise SettingsValidationError(msg % value)
72
-    return value
73
-
74
-##@brief Validator for plugin name & optionnaly type
75
-#
76
-#Able to check that the value is a plugin and if it is of a specific type
77
-def plugin_validator(value, ptype = None):
78
-    LodelContext.expose_modules(globals(), {
79
-        'lodel.plugin.hooks': ['LodelHook']})
80
-    value = copy.copy(value)
81
-    @LodelHook('lodel2_dyncode_bootstraped')
82
-    def plugin_type_checker(hookname, caller, payload):
83
-        LodelContext.expose_modules(globals(), {
84
-            'lodel.plugin.plugins': ['Plugin'],
85
-            'lodel.plugin.exceptions': ['PluginError']})
86
-        if value is None:
87
-            return
88
-        try:
89
-            plugin = Plugin.get(value)
90
-        except PluginError:
91
-            msg = "No plugin named %s found"
92
-            msg %= value
93
-            raise SettingsValidationError(msg)
94
-        if plugin._type_conf_name.lower() != ptype.lower():
95
-            msg = "A plugin of type '%s' was expected but found a plugin \
96
-named  '%s' that is a '%s' plugin"
97
-            msg %= (ptype, value, plugin._type_conf_name)
98
-            raise SettingsValidationError(msg)
99
-    return value
100
-
101
-
102
-
103
-SettingValidator.register_validator(
104
-    'plugin',
105
-    plugin_validator,
106
-    'plugin name & type validator')
107
-
108
-SettingValidator.register_validator(
109
-    'emfield',
110
-    emfield_val,
111
-    'EmField name validator')
112
-
113
-#
114
-#   Lodel 2 configuration specification
115
-#
116
-
117
-##@brief Append a piece of confspec
118
-#@note orig is modified during the process
119
-#@param orig dict : the confspec to update
120
-#@param section str : section name
121
-#@param key str
122
-#@param validator SettingValidator : the validator to use to check this configuration key's value
123
-#@param default
124
-#@return new confspec
125
-def confspec_append(orig, section, key, validator, default):
126
-    if section not in orig:
127
-        orig[section] = dict()
128
-    if key not in orig[section]:
129
-        orig[section][key] = (default, validator)
130
-    return orig
131
-
132
-##@brief Global specifications for lodel2 settings
133
-LODEL2_CONF_SPECS = {
134
-    'lodel2': {
135
-        'debug': (  True,
136
-                    SettingValidator('bool')),
137
-        'sitename': (   'noname',
138
-                        SettingValidator('strip')),
139
-        'runtest': (    False,
140
-                        SettingValidator('bool')),
141
-    },
142
-    'lodel2.logging.*' : {
143
-        'level': (  'ERROR',
144
-                    SettingValidator('loglevel')),
145
-        'context': (    False,
146
-                        SettingValidator('bool')),
147
-        'filename': (   "-",
148
-                        SettingValidator('errfile', none_is_valid = False)),
149
-        'backupcount': (    5,
150
-                            SettingValidator('int', none_is_valid = False)),
151
-        'maxbytes': (   1024*10,
152
-                        SettingValidator('int', none_is_valid = False)),
153
-    },
154
-    'lodel2.editorialmodel': {
155
-        'emfile': ( 'em.pickle', SettingValidator('strip')),
156
-        'emtranslator': ( 'picklefile', SettingValidator('strip')),
157
-        'dyncode': ( 'leapi_dyncode.py', SettingValidator('strip')),
158
-        'groups': ( '', SettingValidator('list')),
159
-        'editormode': ( False, SettingValidator('bool')),
160
-    },
161
-    'lodel2.datasources.*': {
162
-        'read_only': (False, SettingValidator('bool')),
163
-        'identifier': ( None, SettingValidator('string')),
164
-    },
165
-    'lodel2.auth': {
166
-        'login_classfield': ('user.login', SettingValidator('emfield')),
167
-        'pass_classfield': ('user.password', SettingValidator('emfield')),
168
-    },
169
-}

+ 121
- 0
lodel/validator/validator.py View File

@@ -341,3 +341,124 @@ Validator.create_re_validator(
341 341
     r'^https?://[^\./]+.[^\./]+/?.*$',
342 342
     'http_url',
343 343
     'Url validator')
344
+##@brief Validator for Editorial model component
345
+#
346
+# Designed to validate a conf that indicate a class.field in an EM
347
+#@todo modified the hardcoded dyncode import (it's a warning)
348
+def emfield_val(value):
349
+    LodelContext.expose_modules(globals(), {
350
+        'lodel.plugin.hooks': ['LodelHook']})
351
+    spl = value.split('.')
352
+    if len(spl) != 2:
353
+        msg = "Expected a value in the form CLASSNAME.FIELDNAME but got : %s"
354
+        raise SettingsValidationError(msg % value)
355
+    value = tuple(spl)
356
+    #Late validation hook
357
+    @LodelHook('lodel2_dyncode_bootstraped')
358
+    def emfield_conf_check(hookname, caller, payload):
359
+        import leapi_dyncode as dyncode # <-- dirty & quick
360
+        classnames = { cls.__name__.lower():cls for cls in dyncode.dynclasses}
361
+        if value[0].lower() not in classnames:
362
+            msg = "Following dynamic class do not exists in current EM : %s"
363
+            raise SettingsValidationError(msg % value[0])
364
+        ccls = classnames[value[0].lower()]
365
+        if value[1].lower() not in ccls.fieldnames(True):
366
+            msg = "Following field not found in class %s : %s"
367
+            raise SettingsValidationError(msg % value)
368
+    return value
369
+
370
+##@brief Validator for plugin name & optionnaly type
371
+#
372
+#Able to check that the value is a plugin and if it is of a specific type
373
+def plugin_validator(value, ptype = None):
374
+    LodelContext.expose_modules(globals(), {
375
+        'lodel.plugin.hooks': ['LodelHook']})
376
+    value = copy.copy(value)
377
+    @LodelHook('lodel2_dyncode_bootstraped')
378
+    def plugin_type_checker(hookname, caller, payload):
379
+        LodelContext.expose_modules(globals(), {
380
+            'lodel.plugin.plugins': ['Plugin'],
381
+            'lodel.plugin.exceptions': ['PluginError']})
382
+        if value is None:
383
+            return
384
+        try:
385
+            plugin = Plugin.get(value)
386
+        except PluginError:
387
+            msg = "No plugin named %s found"
388
+            msg %= value
389
+            raise ValidationError(msg)
390
+        if plugin._type_conf_name.lower() != ptype.lower():
391
+            msg = "A plugin of type '%s' was expected but found a plugin \
392
+named  '%s' that is a '%s' plugin"
393
+            msg %= (ptype, value, plugin._type_conf_name)
394
+            raise ValidationError(msg)
395
+    return value
396
+
397
+
398
+Validator.register_validator(
399
+    'plugin',
400
+    plugin_validator,
401
+    'plugin name & type validator')
402
+
403
+Validator.register_validator(
404
+    'emfield',
405
+    emfield_val,
406
+    'EmField name validator')
407
+
408
+#
409
+#   Lodel 2 configuration specification
410
+#
411
+
412
+##@brief Append a piece of confspec
413
+#@note orig is modified during the process
414
+#@param orig dict : the confspec to update
415
+#@param section str : section name
416
+#@param key str
417
+#@param validator Validator : the validator to use to check this configuration key's value
418
+#@param default
419
+#@return new confspec
420
+def confspec_append(orig, section, key, validator, default):
421
+    if section not in orig:
422
+        orig[section] = dict()
423
+    if key not in orig[section]:
424
+        orig[section][key] = (default, validator)
425
+    return orig
426
+
427
+##@brief Global specifications for lodel2 settings
428
+LODEL2_CONF_SPECS = {
429
+    'lodel2': {
430
+        'debug': (  True,
431
+                    Validator('bool')),
432
+        'sitename': (   'noname',
433
+                        Validator('strip')),
434
+        'runtest': (    False,
435
+                        Validator('bool')),
436
+    },
437
+    'lodel2.logging.*' : {
438
+        'level': (  'ERROR',
439
+                    Validator('loglevel')),
440
+        'context': (    False,
441
+                        Validator('bool')),
442
+        'filename': (   "-",
443
+                        Validator('errfile', none_is_valid = False)),
444
+        'backupcount': (    5,
445
+                            Validator('int', none_is_valid = False)),
446
+        'maxbytes': (   1024*10,
447
+                        Validator('int', none_is_valid = False)),
448
+    },
449
+    'lodel2.editorialmodel': {
450
+        'emfile': ( 'em.pickle', Validator('strip')),
451
+        'emtranslator': ( 'picklefile', Validator('strip')),
452
+        'dyncode': ( 'leapi_dyncode.py', Validator('strip')),
453
+        'groups': ( '', Validator('list')),
454
+        'editormode': ( False, Validator('bool')),
455
+    },
456
+    'lodel2.datasources.*': {
457
+        'read_only': (False, Validator('bool')),
458
+        'identifier': ( None, Validator('string')),
459
+    },
460
+    'lodel2.auth': {
461
+        'login_classfield': ('user.login', Validator('emfield')),
462
+        'pass_classfield': ('user.password', Validator('emfield')),
463
+    },
464
+}

+ 2
- 2
scripts/settings_validator.py View File

@@ -2,5 +2,5 @@
2 2
 import sys
3 3
 import os, os.path
4 4
 sys.path.append(os.path.dirname(os.getcwd()+'/..'))
5
-from lodel.settings.validator import SettingValidator
6
-print(SettingValidator.validators_list_str())
5
+from lodel.validator.validator import Validator
6
+print(Validator.validators_list_str())

+ 14
- 14
tests/settings/test_validator.py View File

@@ -5,52 +5,52 @@ from unittest import mock
5 5
 from unittest.mock import patch
6 6
 
7 7
 from lodel.exceptions import *
8
-from lodel.settings.validator import *
8
+from lodel.validator.validator import *
9 9
 
10
-class SettingValidatorTestCase(unittest.TestCase):
10
+class ValidatorTestCase(unittest.TestCase):
11 11
     
12 12
     def test_init_basic(self):
13 13
         """ Testing the SettingsValidator class instanciation"""
14
-        valid = SettingValidator('string')
14
+        valid = Validator('string')
15 15
         #trying to call it
16 16
         valid('test')
17 17
 
18 18
     def test_init_badname(self):
19
-        """ Testing SettingValidator instanciation with non existing validator
19
+        """ Testing Validator instanciation with non existing validator
20 20
             name"""
21 21
         with self.assertRaises(LodelFatalError):
22
-            SettingValidator('qklfhsdufgsdyfugigsdfsdlcknsdp')
22
+            Validator('qklfhsdufgsdyfugigsdfsdlcknsdp')
23 23
 
24 24
     def test_noneswitch(self):
25 25
         """ Testing the none_is_valid switch given at validator instanciation
26 26
         """
27
-        none_invalid = SettingValidator('int')
28
-        none_valid = SettingValidator('int', none_is_valid = True)
27
+        none_invalid = Validator('int')
28
+        none_valid = Validator('int', none_is_valid = True)
29 29
 
30 30
         none_valid(None)
31
-        with self.assertRaises(SettingsValidationError):
31
+        with self.assertRaises(ValidationError):
32 32
             none_invalid(None)
33 33
 
34 34
     def test_validator_registration(self):
35
-        """ Testing the register_validator method of SettingValidator """
35
+        """ Testing the register_validator method of Validator """
36 36
         mockfun = mock.MagicMock()
37 37
         vname = 'lfkjdshfkuhsdygsuuyfsduyf'
38 38
         testval = 'foo'
39
-        SettingValidator.register_validator(vname, mockfun, 'test validator')
39
+        Validator.register_validator(vname, mockfun, 'test validator')
40 40
         #Using registered validator
41
-        valid = SettingValidator(vname)
41
+        valid = Validator(vname)
42 42
         valid(testval)
43 43
         mockfun.assert_called_once_with(testval)
44 44
 
45 45
     def test_validator_optargs_forwarding(self):
46
-        """ Testing the ability for SettingValidator to forward optional
46
+        """ Testing the ability for Validator to forward optional
47 47
             arguments """
48 48
         mockfun = mock.MagicMock()
49 49
         vname = 'lkjdsfhsdiufhisduguig'
50 50
         testval = 'azertyuiop'
51
-        SettingValidator.register_validator(vname, mockfun, 'test validator')
51
+        Validator.register_validator(vname, mockfun, 'test validator')
52 52
         #Using registered validator with more arguments
53
-        valid = SettingValidator(vname,
53
+        valid = Validator(vname,
54 54
             arga = 'a', argb = 42, argc = '1337')
55 55
         valid(testval)
56 56
         mockfun.assert_called_once_with(

Loading…
Cancel
Save