Browse Source

After autopep8

prieto 8 years ago
parent
commit
a0b46aa787
2 changed files with 175 additions and 170 deletions
  1. 163
    160
      lodel/leapi/leobject.py
  2. 12
    10
      nocontext_tests.py

+ 163
- 160
lodel/leapi/leobject.py View File

11
     'lodel.settings': 'Settings',
11
     'lodel.settings': 'Settings',
12
     'lodel.settings.utils': 'SettingsError',
12
     'lodel.settings.utils': 'SettingsError',
13
     'lodel.leapi.query': ['LeInsertQuery', 'LeUpdateQuery', 'LeDeleteQuery',
13
     'lodel.leapi.query': ['LeInsertQuery', 'LeUpdateQuery', 'LeDeleteQuery',
14
-        'LeGetQuery'],
14
+                          'LeGetQuery'],
15
     'lodel.leapi.exceptions': ['LeApiError', 'LeApiErrors',
15
     'lodel.leapi.exceptions': ['LeApiError', 'LeApiErrors',
16
-        'LeApiDataCheckError', 'LeApiDataCheckErrors', 'LeApiQueryError',
17
-        'LeApiQueryErrors'],
16
+                               'LeApiDataCheckError', 'LeApiDataCheckErrors', 'LeApiQueryError',
17
+                               'LeApiQueryErrors'],
18
     'lodel.plugin.exceptions': ['PluginError', 'PluginTypeError',
18
     'lodel.plugin.exceptions': ['PluginError', 'PluginTypeError',
19
-        'LodelScriptError', 'DatasourcePluginError'],
19
+                                'LodelScriptError', 'DatasourcePluginError'],
20
     'lodel.exceptions': ['LodelFatalError'],
20
     'lodel.exceptions': ['LodelFatalError'],
21
     'lodel.plugin.hooks': ['LodelHook'],
21
     'lodel.plugin.hooks': ['LodelHook'],
22
     'lodel.plugin': ['Plugin', 'DatasourcePlugin'],
22
     'lodel.plugin': ['Plugin', 'DatasourcePlugin'],
23
     'lodel.leapi.datahandlers.base_classes': ['DatasConstructor', 'Reference']})
23
     'lodel.leapi.datahandlers.base_classes': ['DatasConstructor', 'Reference']})
24
 
24
 
25
-##@brief Stores the name of the field present in each LeObject that indicates
26
-#the name of LeObject subclass represented by this object
25
+# @brief Stores the name of the field present in each LeObject that indicates
26
+# the name of LeObject subclass represented by this object
27
 CLASS_ID_FIELDNAME = "classname"
27
 CLASS_ID_FIELDNAME = "classname"
28
 
28
 
29
-##@brief Wrapper class for LeObject getter & setter
29
+# @brief Wrapper class for LeObject getter & setter
30
 #
30
 #
31
-# This class intend to provide easy & friendly access to LeObject fields values 
31
+# This class intend to provide easy & friendly access to LeObject fields values
32
 # without name collision problems
32
 # without name collision problems
33
 # @note Wrapped methods are : LeObject.data() & LeObject.set_data()
33
 # @note Wrapped methods are : LeObject.data() & LeObject.set_data()
34
+
35
+
34
 class LeObjectValues(object):
36
 class LeObjectValues(object):
35
-    
36
-    ##@brief Construct a new LeObjectValues
37
+
38
+    # @brief Construct a new LeObjectValues
37
     # @param fieldnames_callback method
39
     # @param fieldnames_callback method
38
     # @param set_callback method : The LeObject.set_datas() method of corresponding LeObject class
40
     # @param set_callback method : The LeObject.set_datas() method of corresponding LeObject class
39
     # @param get_callback method : The LeObject.get_datas() method of corresponding LeObject class
41
     # @param get_callback method : The LeObject.get_datas() method of corresponding LeObject class
40
     def __init__(self, fieldnames_callback, set_callback, get_callback):
42
     def __init__(self, fieldnames_callback, set_callback, get_callback):
41
         self._setter = set_callback
43
         self._setter = set_callback
42
         self._getter = get_callback
44
         self._getter = get_callback
43
-    
44
-    ##@brief Provide read access to datas values
45
+
46
+    # @brief Provide read access to datas values
45
     # @note Read access should be provided for all fields
47
     # @note Read access should be provided for all fields
46
     # @param fname str : Field name
48
     # @param fname str : Field name
47
     def __getattribute__(self, fname):
49
     def __getattribute__(self, fname):
48
         getter = super().__getattribute__('_getter')
50
         getter = super().__getattribute__('_getter')
49
         return getter(fname)
51
         return getter(fname)
50
-    
51
-    ##@brief Provide write access to datas values
52
+
53
+    # @brief Provide write access to datas values
52
     # @note Write acces shouldn't be provided for internal or immutable fields
54
     # @note Write acces shouldn't be provided for internal or immutable fields
53
     # @param fname str : Field name
55
     # @param fname str : Field name
54
     # @param fval * : the field value
56
     # @param fval * : the field value
55
     def __setattribute__(self, fname, fval):
57
     def __setattribute__(self, fname, fval):
56
         setter = super().__getattribute__('_setter')
58
         setter = super().__getattribute__('_setter')
57
         return setter(fname, fval)
59
         return setter(fname, fval)
58
-        
60
+
59
 
61
 
60
 class LeObject(object):
62
 class LeObject(object):
61
- 
62
-    ##@brief boolean that tells if an object is abtract or not
63
+
64
+    # @brief boolean that tells if an object is abtract or not
63
     _abstract = None
65
     _abstract = None
64
-    ##@brief A dict that stores DataHandler instances indexed by field name
66
+    # @brief A dict that stores DataHandler instances indexed by field name
65
     _fields = None
67
     _fields = None
66
-    ##@brief A tuple of fieldname (or a uniq fieldname) representing uid
67
-    _uid = None 
68
-    ##@brief Read only datasource ( see @ref lodel2_datasources )
68
+    # @brief A tuple of fieldname (or a uniq fieldname) representing uid
69
+    _uid = None
70
+    # @brief Read only datasource ( see @ref lodel2_datasources )
69
     _ro_datasource = None
71
     _ro_datasource = None
70
-    ##@brief Read & write datasource ( see @ref lodel2_datasources )
72
+    # @brief Read & write datasource ( see @ref lodel2_datasources )
71
     _rw_datasource = None
73
     _rw_datasource = None
72
-    ##@brief Store the list of child classes
74
+    # @brief Store the list of child classes
73
     _child_classes = None
75
     _child_classes = None
74
-    ##@brief Name of the datasource plugin
76
+    # @brief Name of the datasource plugin
75
     _datasource_name = None
77
     _datasource_name = None
76
 
78
 
77
     def __new__(cls, **kwargs):
79
     def __new__(cls, **kwargs):
78
-        
80
+
79
         self = object.__new__(cls)
81
         self = object.__new__(cls)
80
-        ##@brief A dict that stores fieldvalues indexed by fieldname
81
-        self.__datas = { fname:None for fname in self._fields }
82
-        ##@brief Store a list of initianilized fields when instanciation not complete else store True
82
+        # @brief A dict that stores fieldvalues indexed by fieldname
83
+        self.__datas = {fname: None for fname in self._fields}
84
+        # @brief Store a list of initianilized fields when instanciation not complete else store True
83
         self.__initialized = list()
85
         self.__initialized = list()
84
-        ##@brief Datas accessor. Instance of @ref LeObjectValues
86
+        # @brief Datas accessor. Instance of @ref LeObjectValues
85
         self.d = LeObjectValues(self.fieldnames, self.set_data, self.data)
87
         self.d = LeObjectValues(self.fieldnames, self.set_data, self.data)
86
         for fieldname, fieldval in kwargs.items():
88
         for fieldname, fieldval in kwargs.items():
87
             self.__datas[fieldname] = fieldval
89
             self.__datas[fieldname] = fieldval
90
         self.__set_initialized()
92
         self.__set_initialized()
91
         return self
93
         return self
92
 
94
 
93
-    ##@brief Construct an object representing an Editorial component
95
+    # @brief Construct an object representing an Editorial component
94
     # @note Can be considered as EmClass instance
96
     # @note Can be considered as EmClass instance
95
     def __init__(self, **kwargs):
97
     def __init__(self, **kwargs):
96
         if self._abstract:
98
         if self._abstract:
97
-            raise NotImplementedError("%s is abstract, you cannot instanciate it." % self.__class__.__name__ )
99
+            raise NotImplementedError(
100
+                "%s is abstract, you cannot instanciate it." % self.__class__.__name__)
98
 
101
 
99
         # Checks that uid is given
102
         # Checks that uid is given
100
         for uid_name in self._uid:
103
         for uid_name in self._uid:
105
             self.__initialized.append(uid_name)
108
             self.__initialized.append(uid_name)
106
 
109
 
107
         # Processing given fields
110
         # Processing given fields
108
-        allowed_fieldnames = self.fieldnames(include_ro = False)
111
+        allowed_fieldnames = self.fieldnames(include_ro=False)
109
         err_list = dict()
112
         err_list = dict()
110
         for fieldname, fieldval in kwargs.items():
113
         for fieldname, fieldval in kwargs.items():
111
             if fieldname not in allowed_fieldnames:
114
             if fieldname not in allowed_fieldnames:
119
                 self.__datas[fieldname] = fieldval
122
                 self.__datas[fieldname] = fieldval
120
                 self.__initialized.append(fieldname)
123
                 self.__initialized.append(fieldname)
121
         if len(err_list) > 0:
124
         if len(err_list) > 0:
122
-            raise LeApiErrors(msg = "Unable to __init__ %s" % self.__class__,
123
-                exceptions = err_list)
125
+            raise LeApiErrors(msg="Unable to __init__ %s" % self.__class__,
126
+                              exceptions=err_list)
124
         self.__set_initialized()
127
         self.__set_initialized()
125
-    
128
+
126
     #-----------------------------------#
129
     #-----------------------------------#
127
     #   Fields datas handling methods   #
130
     #   Fields datas handling methods   #
128
     #-----------------------------------#
131
     #-----------------------------------#
129
 
132
 
130
-    ##@brief Property method True if LeObject is initialized else False
133
+    # @brief Property method True if LeObject is initialized else False
131
     @property
134
     @property
132
     def initialized(self):
135
     def initialized(self):
133
         return self.__is_initialized
136
         return self.__is_initialized
134
-    
135
-    ##@return The uid field name
137
+
138
+    # @return The uid field name
136
     @classmethod
139
     @classmethod
137
     def uid_fieldname(cls):
140
     def uid_fieldname(cls):
138
         return cls._uid
141
         return cls._uid
139
 
142
 
140
-    ##@brief Return a list of fieldnames
143
+    # @brief Return a list of fieldnames
141
     # @param include_ro bool : if True include read only field names
144
     # @param include_ro bool : if True include read only field names
142
     # @return a list of str
145
     # @return a list of str
143
     @classmethod
146
     @classmethod
144
-    def fieldnames(cls, include_ro = False):
147
+    def fieldnames(cls, include_ro=False):
145
         if not include_ro:
148
         if not include_ro:
146
-            return [ fname for fname in cls._fields if not cls._fields[fname].is_internal() ]
149
+            return [fname for fname in cls._fields if not cls._fields[fname].is_internal()]
147
         else:
150
         else:
148
             return list(cls._fields.keys())
151
             return list(cls._fields.keys())
149
- 
152
+
150
     @classmethod
153
     @classmethod
151
     def name2objname(cls, name):
154
     def name2objname(cls, name):
152
         return name.title()
155
         return name.title()
153
-    
154
-    ##@brief Return the datahandler asssociated with a LeObject field
156
+
157
+    # @brief Return the datahandler asssociated with a LeObject field
155
     # @param fieldname str : The fieldname
158
     # @param fieldname str : The fieldname
156
     # @return A data handler instance
159
     # @return A data handler instance
157
     #@todo update class of exception raised
160
     #@todo update class of exception raised
160
         if not fieldname in cls._fields:
163
         if not fieldname in cls._fields:
161
             raise NameError("No field named '%s' in %s" % (fieldname, cls.__name__))
164
             raise NameError("No field named '%s' in %s" % (fieldname, cls.__name__))
162
         return cls._fields[fieldname]
165
         return cls._fields[fieldname]
163
-    
164
-    ##@brief Getter for references datahandlers
166
+
167
+    # @brief Getter for references datahandlers
165
     #@param with_backref bool : if true return only references with back_references
168
     #@param with_backref bool : if true return only references with back_references
166
     #@return <code>{'fieldname': datahandler, ...}</code>
169
     #@return <code>{'fieldname': datahandler, ...}</code>
167
     @classmethod
170
     @classmethod
168
-    def reference_handlers(cls, with_backref = True):
169
-        return {    fname: fdh 
170
-                    for fname, fdh in cls.fields(True).items()
171
-                    if fdh.is_reference() and \
172
-                        (not with_backref or fdh.back_reference is not None)}
173
-    
174
-    ##@brief Return a LeObject child class from a name
171
+    def reference_handlers(cls, with_backref=True):
172
+        return {fname: fdh
173
+                for fname, fdh in cls.fields(True).items()
174
+                if fdh.is_reference() and
175
+                (not with_backref or fdh.back_reference is not None)}
176
+
177
+    # @brief Return a LeObject child class from a name
175
     # @warning This method has to be called from dynamically generated LeObjects
178
     # @warning This method has to be called from dynamically generated LeObjects
176
     # @param leobject_name str : LeObject name
179
     # @param leobject_name str : LeObject name
177
     # @return A LeObject child class
180
     # @return A LeObject child class
183
         mod = importlib.import_module(cls.__module__)
186
         mod = importlib.import_module(cls.__module__)
184
         try:
187
         try:
185
             return getattr(mod, leobject_name)
188
             return getattr(mod, leobject_name)
186
-        except (AttributeError, TypeError) :
189
+        except (AttributeError, TypeError):
187
             raise LeApiError("No LeObject named '%s'" % leobject_name)
190
             raise LeApiError("No LeObject named '%s'" % leobject_name)
188
-    
191
+
189
     @classmethod
192
     @classmethod
190
     def is_abstract(cls):
193
     def is_abstract(cls):
191
         return cls._abstract
194
         return cls._abstract
192
-    
193
-    ##@brief Field data handler getter
195
+
196
+    # @brief Field data handler getter
194
     #@param fieldname str : The field name
197
     #@param fieldname str : The field name
195
     #@return A datahandler instance
198
     #@return A datahandler instance
196
     #@throw NameError if the field doesn't exist
199
     #@throw NameError if the field doesn't exist
199
         try:
202
         try:
200
             return cls._fields[fieldname]
203
             return cls._fields[fieldname]
201
         except KeyError:
204
         except KeyError:
202
-            raise NameError("No field named '%s' in %s" % ( fieldname,
203
-                                                            cls.__name__))
204
-    ##@return A dict with fieldname as key and datahandler as instance
205
+            raise NameError("No field named '%s' in %s" % (fieldname,
206
+                                                           cls.__name__))
207
+    # @return A dict with fieldname as key and datahandler as instance
208
+
205
     @classmethod
209
     @classmethod
206
-    def fields(cls, include_ro = False):
210
+    def fields(cls, include_ro=False):
207
         if include_ro:
211
         if include_ro:
208
             return copy.copy(cls._fields)
212
             return copy.copy(cls._fields)
209
         else:
213
         else:
210
-            return {fname:cls._fields[fname] for fname in cls._fields if not cls._fields[fname].is_internal()}
211
-    
212
-    ##@brief Return the list of parents classes
214
+            return {fname: cls._fields[fname] for fname in cls._fields\
215
+                    if not cls._fields[fname].is_internal()}
216
+
217
+    # @brief Return the list of parents classes
213
     #
218
     #
214
     #@note the first item of the list is the current class, the second is it's
219
     #@note the first item of the list is the current class, the second is it's
215
-    #parent etc...
220
+    # parent etc...
216
     #@param cls
221
     #@param cls
217
     #@warning multiple inheritance broken by this method
222
     #@warning multiple inheritance broken by this method
218
     #@return a list of LeObject child classes
223
     #@return a list of LeObject child classes
222
         res = [cls]
227
         res = [cls]
223
         cur = cls
228
         cur = cls
224
         while True:
229
         while True:
225
-            cur = cur.__bases__[0] # Multiple inheritance broken HERE
230
+            cur = cur.__bases__[0]  # Multiple inheritance broken HERE
226
             if cur in (LeObject, object):
231
             if cur in (LeObject, object):
227
                 break
232
                 break
228
             else:
233
             else:
229
                 res.append(cur)
234
                 res.append(cur)
230
         return res
235
         return res
231
-    
232
-    ##@brief Return a tuple a child classes
236
+
237
+    # @brief Return a tuple a child classes
233
     #@return a tuple of child classes
238
     #@return a tuple of child classes
234
     @classmethod
239
     @classmethod
235
     def child_classes(cls):
240
     def child_classes(cls):
236
         return copy.copy(cls._child_classes)
241
         return copy.copy(cls._child_classes)
237
-        
238
 
242
 
239
-    ##@brief Return the parent class that is the "source" of uid
243
+    # @brief Return the parent class that is the "source" of uid
240
     #
244
     #
241
-    #The method goal is to return the parent class that defines UID.
245
+    # The method goal is to return the parent class that defines UID.
242
     #@return a LeObject child class or false if no UID defined
246
     #@return a LeObject child class or false if no UID defined
243
     @classmethod
247
     @classmethod
244
     def uid_source(cls):
248
     def uid_source(cls):
246
             return False
250
             return False
247
         hierarch = cls.hierarch()
251
         hierarch = cls.hierarch()
248
         prev = hierarch[0]
252
         prev = hierarch[0]
249
-        uid_handlers = set( cls._fields[name] for name in cls._uid )
253
+        uid_handlers = set(cls._fields[name] for name in cls._uid)
250
         for pcls in cls.hierarch()[1:]:
254
         for pcls in cls.hierarch()[1:]:
251
             puid_handlers = set(cls._fields[name] for name in pcls._uid)
255
             puid_handlers = set(cls._fields[name] for name in pcls._uid)
252
             if set(pcls._uid) != set(prev._uid) \
256
             if set(pcls._uid) != set(prev._uid) \
253
-                or puid_handlers != uid_handlers:
257
+                    or puid_handlers != uid_handlers:
254
                 break
258
                 break
255
             prev = pcls
259
             prev = pcls
256
         return prev
260
         return prev
257
-    
258
-    ##@brief Initialise both datasources (ro and rw)
261
+
262
+    # @brief Initialise both datasources (ro and rw)
259
     #
263
     #
260
-    #This method is used once at dyncode load to replace the datasource string
261
-    #by a datasource instance to avoid doing this operation for each query
264
+    # This method is used once at dyncode load to replace the datasource string
265
+    # by a datasource instance to avoid doing this operation for each query
262
     #@see LeObject::_init_datasource()
266
     #@see LeObject::_init_datasource()
263
     @classmethod
267
     @classmethod
264
     def _init_datasources(cls):
268
     def _init_datasources(cls):
266
             rw_ds = ro_ds = cls._datasource_name
270
             rw_ds = ro_ds = cls._datasource_name
267
         else:
271
         else:
268
             ro_ds, rw_ds = cls._datasource_name
272
             ro_ds, rw_ds = cls._datasource_name
269
-        #Read only datasource initialisation
273
+        # Read only datasource initialisation
270
         cls._ro_datasource = DatasourcePlugin.init_datasource(ro_ds, True)
274
         cls._ro_datasource = DatasourcePlugin.init_datasource(ro_ds, True)
271
         if cls._ro_datasource is None:
275
         if cls._ro_datasource is None:
272
             log_msg = "No read only datasource set for LeObject %s"
276
             log_msg = "No read only datasource set for LeObject %s"
276
             log_msg = "Read only datasource '%s' initialized for LeObject %s"
280
             log_msg = "Read only datasource '%s' initialized for LeObject %s"
277
             log_msg %= (ro_ds, cls.__name__)
281
             log_msg %= (ro_ds, cls.__name__)
278
             logger.debug(log_msg)
282
             logger.debug(log_msg)
279
-        #Read write datasource initialisation
283
+        # Read write datasource initialisation
280
         cls._rw_datasource = DatasourcePlugin.init_datasource(rw_ds, False)
284
         cls._rw_datasource = DatasourcePlugin.init_datasource(rw_ds, False)
281
         if cls._ro_datasource is None:
285
         if cls._ro_datasource is None:
282
             log_msg = "No read/write datasource set for LeObject %s"
286
             log_msg = "No read/write datasource set for LeObject %s"
286
             log_msg = "Read/write datasource '%s' initialized for LeObject %s"
290
             log_msg = "Read/write datasource '%s' initialized for LeObject %s"
287
             log_msg %= (ro_ds, cls.__name__)
291
             log_msg %= (ro_ds, cls.__name__)
288
             logger.debug(log_msg)
292
             logger.debug(log_msg)
289
-        
290
-    ##@brief Return the uid of the current LeObject instance
293
+
294
+    # @brief Return the uid of the current LeObject instance
291
     #@return the uid value
295
     #@return the uid value
292
     #@warning Broke multiple uid capabilities
296
     #@warning Broke multiple uid capabilities
293
     def uid(self):
297
     def uid(self):
294
         return self.data(self._uid[0])
298
         return self.data(self._uid[0])
295
 
299
 
296
-    ##@brief Read only access to all datas
300
+    # @brief Read only access to all datas
297
     # @note for fancy data accessor use @ref LeObject.g attribute @ref LeObjectValues instance
301
     # @note for fancy data accessor use @ref LeObject.g attribute @ref LeObjectValues instance
298
     # @param field_name str : field name
302
     # @param field_name str : field name
299
     # @return the Value
303
     # @return the Value
303
         if field_name not in self._fields.keys():
307
         if field_name not in self._fields.keys():
304
             raise NameError("No such field in %s : %s" % (self.__class__.__name__, field_name))
308
             raise NameError("No such field in %s : %s" % (self.__class__.__name__, field_name))
305
         if not self.initialized and field_name not in self.__initialized:
309
         if not self.initialized and field_name not in self.__initialized:
306
-            raise RuntimeError("The field %s is not initialized yet (and have no value)" % field_name)
310
+            raise RuntimeError(
311
+                "The field %s is not initialized yet (and have no value)" % field_name)
307
         return self.__datas[field_name]
312
         return self.__datas[field_name]
308
-    
309
-    ##@brief Read only access to all datas
313
+
314
+    # @brief Read only access to all datas
310
     #@return a dict representing datas of current instance
315
     #@return a dict representing datas of current instance
311
-    def datas(self, internal = False):
312
-        return {fname:self.data(fname) for fname in self.fieldnames(internal)}
313
-        
314
-    
315
-    ##@brief Datas setter
316
+    def datas(self, internal=False):
317
+        return {fname: self.data(fname) for fname in self.fieldnames(internal)}
318
+
319
+    # @brief Datas setter
316
     # @note for fancy data accessor use @ref LeObject.g attribute @ref LeObjectValues instance
320
     # @note for fancy data accessor use @ref LeObject.g attribute @ref LeObjectValues instance
317
     # @param fname str : field name
321
     # @param fname str : field name
318
     # @param fval * : field value
322
     # @param fval * : field value
320
     # @throw NameError if fname is not valid
324
     # @throw NameError if fname is not valid
321
     # @throw AttributeError if the field is not writtable
325
     # @throw AttributeError if the field is not writtable
322
     def set_data(self, fname, fval):
326
     def set_data(self, fname, fval):
323
-        if fname not in self.fieldnames(include_ro = False):
327
+        if fname not in self.fieldnames(include_ro=False):
324
             if fname not in self._fields.keys():
328
             if fname not in self._fields.keys():
325
                 raise NameError("No such field in %s : %s" % (self.__class__.__name__, fname))
329
                 raise NameError("No such field in %s : %s" % (self.__class__.__name__, fname))
326
             else:
330
             else:
342
             # We skip full validation here because the LeObject is not fully initialized yet
346
             # We skip full validation here because the LeObject is not fully initialized yet
343
             val, err = self._fields[fname].check_data_value(fval)
347
             val, err = self._fields[fname].check_data_value(fval)
344
             if isinstance(err, Exception):
348
             if isinstance(err, Exception):
345
-                #Revert change to be in valid state
349
+                # Revert change to be in valid state
346
                 del(self.__datas[fname])
350
                 del(self.__datas[fname])
347
                 del(self.__initialized[-1])
351
                 del(self.__initialized[-1])
348
-                raise LeApiErrors("Data check error", {fname:err})
352
+                raise LeApiErrors("Data check error", {fname: err})
349
             else:
353
             else:
350
                 self.__datas[fname] = val
354
                 self.__datas[fname] = val
351
-    
352
-    ##@brief Update the __initialized attribute according to LeObject internal state
355
+
356
+    # @brief Update the __initialized attribute according to LeObject internal state
353
     #
357
     #
354
     # Check the list of initialized fields and set __initialized to True if all fields initialized
358
     # Check the list of initialized fields and set __initialized to True if all fields initialized
355
     def __set_initialized(self):
359
     def __set_initialized(self):
356
         if isinstance(self.__initialized, list):
360
         if isinstance(self.__initialized, list):
357
-            expected_fields = self.fieldnames(include_ro = False) + self._uid
361
+            expected_fields = self.fieldnames(include_ro=False) + self._uid
358
             if set(expected_fields) == set(self.__initialized):
362
             if set(expected_fields) == set(self.__initialized):
359
                 self.__is_initialized = True
363
                 self.__is_initialized = True
360
 
364
 
361
-    ##@brief Designed to be called when datas are modified
365
+    # @brief Designed to be called when datas are modified
362
     #
366
     #
363
     # Make different checks on the LeObject given it's state (fully initialized or not)
367
     # Make different checks on the LeObject given it's state (fully initialized or not)
364
     # @return None if checks succeded else return an exception list
368
     # @return None if checks succeded else return an exception list
366
         err_list = dict()
370
         err_list = dict()
367
         if self.__initialized is True:
371
         if self.__initialized is True:
368
             # Data value check
372
             # Data value check
369
-            for fname in self.fieldnames(include_ro = False):
373
+            for fname in self.fieldnames(include_ro=False):
370
                 val, err = self._fields[fname].check_data_value(self.__datas[fname])
374
                 val, err = self._fields[fname].check_data_value(self.__datas[fname])
371
                 if err is not None:
375
                 if err is not None:
372
                     err_list[fname] = err
376
                     err_list[fname] = err
374
                     self.__datas[fname] = val
378
                     self.__datas[fname] = val
375
             # Data construction
379
             # Data construction
376
             if len(err_list) == 0:
380
             if len(err_list) == 0:
377
-                for fname in self.fieldnames(include_ro = True):
381
+                for fname in self.fieldnames(include_ro=True):
378
                     try:
382
                     try:
379
                         field = self._fields[fname]
383
                         field = self._fields[fname]
380
-                        self.__datas[fname] = field.construct_data(    self,
381
-                                                                        fname,
382
-                                                                        self.__datas,
383
-                                                                        self.__datas[fname]
384
-                        )
384
+                        self.__datas[fname] = field.construct_data(self,
385
+                                                                   fname,
386
+                                                                   self.__datas,
387
+                                                                   self.__datas[fname]
388
+                                                                   )
385
                     except Exception as exp:
389
                     except Exception as exp:
386
                         err_list[fname] = exp
390
                         err_list[fname] = exp
387
             # Datas consistency check
391
             # Datas consistency check
388
             if len(err_list) == 0:
392
             if len(err_list) == 0:
389
-                for fname in self.fieldnames(include_ro = True):
393
+                for fname in self.fieldnames(include_ro=True):
390
                     field = self._fields[fname]
394
                     field = self._fields[fname]
391
                     ret = field.check_data_consistency(self, fname, self.__datas)
395
                     ret = field.check_data_consistency(self, fname, self.__datas)
392
                     if isinstance(ret, Exception):
396
                     if isinstance(ret, Exception):
404
     #--------------------#
408
     #--------------------#
405
     #   Other methods    #
409
     #   Other methods    #
406
     #--------------------#
410
     #--------------------#
407
-    
408
-    ##@brief Temporary method to set private fields attribute at dynamic code generation
411
+
412
+    # @brief Temporary method to set private fields attribute at dynamic code generation
409
     #
413
     #
410
     # This method is used in the generated dynamic code to set the _fields attribute
414
     # This method is used in the generated dynamic code to set the _fields attribute
411
     # at the end of the dyncode parse
415
     # at the end of the dyncode parse
415
     @classmethod
419
     @classmethod
416
     def _set__fields(cls, field_list):
420
     def _set__fields(cls, field_list):
417
         cls._fields = field_list
421
         cls._fields = field_list
418
-        
419
-    ## @brief Check that datas are valid for this type
422
+
423
+    # @brief Check that datas are valid for this type
420
     # @param datas dict : key == field name value are field values
424
     # @param datas dict : key == field name value are field values
421
     # @param complete bool : if True expect that datas provide values for all non internal fields
425
     # @param complete bool : if True expect that datas provide values for all non internal fields
422
     # @param allow_internal bool : if True don't raise an error if a field is internal
426
     # @param allow_internal bool : if True don't raise an error if a field is internal
424
     # @return Checked datas
428
     # @return Checked datas
425
     # @throw LeApiDataCheckError if errors reported during check
429
     # @throw LeApiDataCheckError if errors reported during check
426
     @classmethod
430
     @classmethod
427
-    def check_datas_value(cls, datas, complete = False, allow_internal = True):
428
-        err_l = dict() #Error storing
429
-        correct = set() #valid fields name
430
-        mandatory = set() #mandatory fields name
431
+    def check_datas_value(cls, datas, complete=False, allow_internal=True):
432
+        err_l = dict()  # Error storing
433
+        correct = set()  # valid fields name
434
+        mandatory = set()  # mandatory fields name
431
         for fname, datahandler in cls._fields.items():
435
         for fname, datahandler in cls._fields.items():
432
             if allow_internal or not datahandler.is_internal():
436
             if allow_internal or not datahandler.is_internal():
433
                 correct.add(fname)
437
                 correct.add(fname)
436
         provided = set(datas.keys())
440
         provided = set(datas.keys())
437
         # searching for unknow fields
441
         # searching for unknow fields
438
         for u_f in provided - correct:
442
         for u_f in provided - correct:
439
-            #Here we can check if the field is invalid or rejected because
443
+            # Here we can check if the field is invalid or rejected because
440
             # it is internel
444
             # it is internel
441
             err_l[u_f] = AttributeError("Unknown or unauthorized field '%s'" % u_f)
445
             err_l[u_f] = AttributeError("Unknown or unauthorized field '%s'" % u_f)
442
         # searching for missing mandatory fieldsa
446
         # searching for missing mandatory fieldsa
443
         for missing in mandatory - provided:
447
         for missing in mandatory - provided:
444
             err_l[missing] = AttributeError("The data for field '%s' is missing" % missing)
448
             err_l[missing] = AttributeError("The data for field '%s' is missing" % missing)
445
-        #Checks datas
449
+        # Checks datas
446
         checked_datas = dict()
450
         checked_datas = dict()
447
-        for name, value in [ (name, value) for name, value in datas.items() if name in correct ]:
451
+        for name, value in [(name, value) for name, value in datas.items() if name in correct]:
448
             dh = cls._fields[name]
452
             dh = cls._fields[name]
449
             res = dh.check_data_value(value)
453
             res = dh.check_data_value(value)
450
             checked_datas[name], err = res
454
             checked_datas[name], err = res
455
             raise LeApiDataCheckErrors("Error while checking datas", err_l)
459
             raise LeApiDataCheckErrors("Error while checking datas", err_l)
456
         return checked_datas
460
         return checked_datas
457
 
461
 
458
-    ##@brief Check and prepare datas
459
-    # 
462
+    # @brief Check and prepare datas
463
+    #
460
     # @warning when complete = False we are not able to make construct_datas() and _check_data_consistency()
464
     # @warning when complete = False we are not able to make construct_datas() and _check_data_consistency()
461
-    # 
465
+    #
462
     # @param datas dict : {fieldname : fieldvalue, ...}
466
     # @param datas dict : {fieldname : fieldvalue, ...}
463
     # @param complete bool : If True you MUST give all the datas
467
     # @param complete bool : If True you MUST give all the datas
464
     # @param allow_internal : Wether or not interal fields are expected in datas
468
     # @param allow_internal : Wether or not interal fields are expected in datas
478
             cls._check_datas_consistency(ret_datas)
482
             cls._check_datas_consistency(ret_datas)
479
         return ret_datas
483
         return ret_datas
480
 
484
 
481
-    ## @brief Construct datas values
485
+    # @brief Construct datas values
482
     #
486
     #
483
     # @param cls
487
     # @param cls
484
     # @param datas dict : Datas that have been returned by LeCrud.check_datas_value() methods
488
     # @param datas dict : Datas that have been returned by LeCrud.check_datas_value() methods
488
     def _construct_datas(cls, datas):
492
     def _construct_datas(cls, datas):
489
         constructor = DatasConstructor(cls, datas, cls._fields)
493
         constructor = DatasConstructor(cls, datas, cls._fields)
490
         ret = {
494
         ret = {
491
-                fname:constructor[fname]
492
-                for fname, ftype in cls._fields.items()
493
-                if not ftype.is_internal() or ftype.internal != 'autosql'
495
+            fname: constructor[fname]
496
+            for fname, ftype in cls._fields.items()
497
+            if not ftype.is_internal() or ftype.internal != 'autosql'
494
         }
498
         }
495
         return ret
499
         return ret
496
-    
497
-    ## @brief Check datas consistency
500
+
501
+    # @brief Check datas consistency
498
502
499
     # @warning assert that datas is complete
503
     # @warning assert that datas is complete
500
     # @param cls
504
     # @param cls
511
 
515
 
512
         if len(err_l) > 0:
516
         if len(err_l) > 0:
513
             raise LeApiDataCheckError("Datas consistency checks fails", err_l)
517
             raise LeApiDataCheckError("Datas consistency checks fails", err_l)
514
-    
515
-    ## @brief Check datas consistency
518
+
519
+    # @brief Check datas consistency
516
520
517
     # @warning assert that datas is complete
521
     # @warning assert that datas is complete
518
     # @param cls
522
     # @param cls
519
     # @param datas dict : Datas that have been returned by LeCrud.prepare_datas() method
523
     # @param datas dict : Datas that have been returned by LeCrud.prepare_datas() method
520
     # @param type_query str : Type of query to be performed , default value : insert
524
     # @param type_query str : Type of query to be performed , default value : insert
521
     @classmethod
525
     @classmethod
522
-    def make_consistency(cls, datas, type_query = 'insert'):
526
+    def make_consistency(cls, datas, type_query='insert'):
523
         for fname, dh in cls._fields.items():
527
         for fname, dh in cls._fields.items():
524
             ret = dh.make_consistency(fname, datas, type_query)
528
             ret = dh.make_consistency(fname, datas, type_query)
525
-            
526
-    ## @brief Add a new instance of LeObject
529
+
530
+    # @brief Add a new instance of LeObject
527
     # @return a new uid en case of success, False otherwise
531
     # @return a new uid en case of success, False otherwise
528
     @classmethod
532
     @classmethod
529
     def insert(cls, datas):
533
     def insert(cls, datas):
530
         query = LeInsertQuery(cls)
534
         query = LeInsertQuery(cls)
531
         return query.execute(datas)
535
         return query.execute(datas)
532
 
536
 
533
-    ## @brief Update an instance of LeObject
537
+    # @brief Update an instance of LeObject
534
     #
538
     #
535
-    #@param datas : list of new datas 
536
-    def update(self, datas = None):
539
+    #@param datas : list of new datas
540
+    def update(self, datas=None):
537
         datas = self.datas(internal=False) if datas is None else datas
541
         datas = self.datas(internal=False) if datas is None else datas
538
         uids = self._uid
542
         uids = self._uid
539
         query_filter = list()
543
         query_filter = list()
543
             query = LeUpdateQuery(self.__class__, query_filter)
547
             query = LeUpdateQuery(self.__class__, query_filter)
544
         except Exception as err:
548
         except Exception as err:
545
             raise err
549
             raise err
546
-            
550
+
547
         try:
551
         try:
548
             result = query.execute(datas)
552
             result = query.execute(datas)
549
         except Exception as err:
553
         except Exception as err:
550
             raise err
554
             raise err
551
 
555
 
552
         return result
556
         return result
553
-    
554
-    ## @brief Delete an instance of LeObject
557
+
558
+    # @brief Delete an instance of LeObject
555
     #
559
     #
556
     #@return 1 if the objet has been deleted
560
     #@return 1 if the objet has been deleted
557
     def delete(self):
561
     def delete(self):
565
         result = query.execute()
569
         result = query.execute()
566
 
570
 
567
         return result
571
         return result
568
-    
569
-    ## @brief Delete instances of LeObject
572
+
573
+    # @brief Delete instances of LeObject
570
     #@param query_filters list
574
     #@param query_filters list
571
     #@returns the number of deleted items
575
     #@returns the number of deleted items
572
     @classmethod
576
     @classmethod
576
             query = LeDeleteQuery(cls, query_filters)
580
             query = LeDeleteQuery(cls, query_filters)
577
         except Exception as err:
581
         except Exception as err:
578
             raise err
582
             raise err
579
-                
583
+
580
         try:
584
         try:
581
             result = query.execute()
585
             result = query.execute()
582
         except Exception as err:
586
         except Exception as err:
584
         if not result is None:
588
         if not result is None:
585
             deleted += result
589
             deleted += result
586
         return deleted
590
         return deleted
587
-            
588
-    ## @brief Get instances of LeObject
591
+
592
+    # @brief Get instances of LeObject
589
     #
593
     #
590
     #@param query_filters dict : (filters, relational filters), with filters is a list of tuples : (FIELD, OPERATOR, VALUE) )
594
     #@param query_filters dict : (filters, relational filters), with filters is a list of tuples : (FIELD, OPERATOR, VALUE) )
591
-    #@param field_list list|None : list of string representing fields see 
595
+    #@param field_list list|None : list of string representing fields see
592
     #@ref leobject_filters
596
     #@ref leobject_filters
593
     #@param order list : A list of field names or tuple (FIELDNAME,[ASC | DESC])
597
     #@param order list : A list of field names or tuple (FIELDNAME,[ASC | DESC])
594
     #@param group list : A list of field names or tuple (FIELDNAME,[ASC | DESC])
598
     #@param group list : A list of field names or tuple (FIELDNAME,[ASC | DESC])
598
     @classmethod
602
     @classmethod
599
     def get(cls, query_filters, field_list=None, order=None, group=None, limit=None, offset=0):
603
     def get(cls, query_filters, field_list=None, order=None, group=None, limit=None, offset=0):
600
         if field_list is not None:
604
         if field_list is not None:
601
-            for uid in [ uidname
602
-                for uidname in cls.uid_fieldname()
603
-                if uidname not in field_list ]:
605
+            for uid in [uidname
606
+                        for uidname in cls.uid_fieldname()
607
+                        if uidname not in field_list]:
604
                 field_list.append(uid)
608
                 field_list.append(uid)
605
             if CLASS_ID_FIELDNAME not in field_list:
609
             if CLASS_ID_FIELDNAME not in field_list:
606
                 field_list.append(CLASS_ID_FIELDNAME)
610
                 field_list.append(CLASS_ID_FIELDNAME)
607
         try:
611
         try:
608
             query = LeGetQuery(
612
             query = LeGetQuery(
609
-                cls, query_filters = query_filters, field_list = field_list,
610
-                order = order, group = group, limit = limit, offset = offset)
613
+                cls, query_filters=query_filters, field_list=field_list,
614
+                order=order, group=group, limit=limit, offset=offset)
611
         except ValueError as err:
615
         except ValueError as err:
612
             raise err
616
             raise err
613
-            
617
+
614
         try:
618
         try:
615
             result = query.execute()
619
             result = query.execute()
616
         except Exception as err:
620
         except Exception as err:
617
             raise err
621
             raise err
618
-        
622
+
619
         objects = list()
623
         objects = list()
620
         for res in result:
624
         for res in result:
621
             res_cls = cls.name2class(res[CLASS_ID_FIELDNAME])
625
             res_cls = cls.name2class(res[CLASS_ID_FIELDNAME])
622
-            inst = res_cls.__new__(res_cls,**res)
626
+            inst = res_cls.__new__(res_cls, **res)
623
             objects.append(inst)
627
             objects.append(inst)
624
-        
628
+
625
         return objects
629
         return objects
626
-    
627
-    ##@brief Retrieve an object given an UID
630
+
631
+    # @brief Retrieve an object given an UID
628
     #@todo broken multiple UID
632
     #@todo broken multiple UID
629
     @classmethod
633
     @classmethod
630
     def get_from_uid(cls, uid):
634
     def get_from_uid(cls, uid):
631
         if cls.uid_fieldname() is None:
635
         if cls.uid_fieldname() is None:
632
             raise LodelFatalError(
636
             raise LodelFatalError(
633
                 "No uid defined for class %s" % cls.__name__)
637
                 "No uid defined for class %s" % cls.__name__)
634
-        uidname = cls.uid_fieldname()[0] #Brokes composed UID
635
-        res = cls.get([(uidname,'=', uid)])
636
-        
637
-        #dedoublonnage vu que query ou la datasource est bugué
638
+        uidname = cls.uid_fieldname()[0]  # Brokes composed UID
639
+        res = cls.get([(uidname, '=', uid)])
640
+
641
+        # dedoublonnage vu que query ou la datasource est bugué
638
         if len(res) > 1:
642
         if len(res) > 1:
639
             res_cp = res
643
             res_cp = res
640
             res = []
644
             res = []
641
             while len(res_cp) > 0:
645
             while len(res_cp) > 0:
642
                 cur_res = res_cp.pop()
646
                 cur_res = res_cp.pop()
643
-                if cur_res.uid() in [ r.uid() for r in res_cp]:
647
+                if cur_res.uid() in [r.uid() for r in res_cp]:
644
                     logger.error("DOUBLON detected in query results !!!")
648
                     logger.error("DOUBLON detected in query results !!!")
645
                 else:
649
                 else:
646
                     res.append(cur_res)
650
                     res.append(cur_res)
651
             return None
655
             return None
652
         return res[0]
656
         return res[0]
653
 
657
 
654
-    ##@brief Checks if an object exists
658
+    # @brief Checks if an object exists
655
     @classmethod
659
     @classmethod
656
     def is_exist(cls, uid):
660
     def is_exist(cls, uid):
657
         if cls.uid_fieldname() is None:
661
         if cls.uid_fieldname() is None:
659
                 "No uid defined for class %s" % cls.__name__)
663
                 "No uid defined for class %s" % cls.__name__)
660
         from .query import is_exist
664
         from .query import is_exist
661
         return is_exist(cls, uid)
665
         return is_exist(cls, uid)
662
-

+ 12
- 10
nocontext_tests.py View File

1
 #-*- coding: utf-8 -*-
1
 #-*- coding: utf-8 -*-
2
 
2
 
3
-##@brief Loader for tests which do not need an lodel installation
3
+# @brief Loader for tests which do not need an lodel installation
4
 #
4
 #
5
 # Options
5
 # Options
6
 ################
6
 ################
7
-# 
7
+#
8
 # @note We can pass the path to a directory to write results file, nocontext_tests.log
8
 # @note We can pass the path to a directory to write results file, nocontext_tests.log
9
-# It has to be at first, otherwise it will not be taken 
9
+# It has to be at first, otherwise it will not be taken
10
 # and the default one, current directory, will be used.
10
 # and the default one, current directory, will be used.
11
 # The results are not displayed, only stored in nocontext_tests.log
11
 # The results are not displayed, only stored in nocontext_tests.log
12
 #
12
 #
19
 #
19
 #
20
 #
20
 #
21
 
21
 
22
-import sys, os, os.path
22
+import sys
23
+import os
24
+import os.path
23
 import unittest
25
 import unittest
24
 
26
 
25
 
27
 
26
 loader = unittest.TestLoader()
28
 loader = unittest.TestLoader()
27
 
29
 
28
 if ((len(sys.argv) > 1) and (sys.argv[1].startswith('-')) is False):
30
 if ((len(sys.argv) > 1) and (sys.argv[1].startswith('-')) is False):
29
-	dpath = sys.argv[1]
31
+    dpath = sys.argv[1]
30
 else:
32
 else:
31
-	dpath = '.'
33
+    dpath = '.'
32
 
34
 
33
 suite = loader.discover('tests', pattern='nc_test*.py')
35
 suite = loader.discover('tests', pattern='nc_test*.py')
34
-with open(dpath+'/nocontext_tests.log', 'w') as logfile:
36
+with open(dpath + '/nocontext_tests.log', 'w') as logfile:
35
     unittest.TextTestRunner(
37
     unittest.TextTestRunner(
36
-    	logfile,
37
-        failfast = '-f' in sys.argv,
38
-        verbosity = 2 if '-v' in sys.argv else 1).run(suite)
38
+        logfile,
39
+        failfast='-f' in sys.argv,
40
+        verbosity=2 if '-v' in sys.argv else 1).run(suite)

Loading…
Cancel
Save