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

+ 12
- 10
nocontext_tests.py View File

@@ -1,12 +1,12 @@
1 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 5
 # Options
6 6
 ################
7
-# 
7
+#
8 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 10
 # and the default one, current directory, will be used.
11 11
 # The results are not displayed, only stored in nocontext_tests.log
12 12
 #
@@ -19,20 +19,22 @@
19 19
 #
20 20
 #
21 21
 
22
-import sys, os, os.path
22
+import sys
23
+import os
24
+import os.path
23 25
 import unittest
24 26
 
25 27
 
26 28
 loader = unittest.TestLoader()
27 29
 
28 30
 if ((len(sys.argv) > 1) and (sys.argv[1].startswith('-')) is False):
29
-	dpath = sys.argv[1]
31
+    dpath = sys.argv[1]
30 32
 else:
31
-	dpath = '.'
33
+    dpath = '.'
32 34
 
33 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 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