Browse Source

Code factorization on EmComponent.modify_rank()

Changed beahvior : when a 'non-change' is asked (like +0 -0 or set ranke to actual rank) don't raise an Error
Yann Weber 9 years ago
parent
commit
49dfe9ad03
2 changed files with 65 additions and 133 deletions
  1. 65
    129
      EditorialModel/components.py
  2. 0
    4
      EditorialModel/test/test_component.py

+ 65
- 129
EditorialModel/components.py View File

@@ -281,138 +281,74 @@ class EmComponent(object):
281 281
         else:
282 282
             return -1
283 283
 
284
-    ## modify_rank
285
-    #
286
-    # Permet de changer le rank d'un component, soit en lui donnant un rank précis, soit en augmentant ou reduisant sont rank actuelle d'une valleur donné.
287
-    #
288
-    # @param new_rank int: le rank ou modificateur de rank
289
-    # @param sign str: Un charactère qui peut être : '=' pour afecter un rank, '+' pour ajouter le modificateur de rank ou '-' pour soustraire le modificateur de rank.
290
-    #
291
-    # @return bool: True en cas de réussite False en cas d'echec.
292
-    # @throw TypeError if an argument isn't from the expected type
293
-    # @thrown ValueError if an argument as a wrong value but is of the good type
294
-    def modify_rank(self, new_rank, sign='='):
284
+    ## Set a new rank for this component
285
+    # @param new_rank int: The new rank
286
+    # @return True if success False if not
287
+    # @throw TypeError If bad argument type
288
+    # @throw ValueError if out of bound value
289
+    def set_rank(self, new_rank):
290
+        if not isinstance(new_rank, int):
291
+            raise TypeError("Excepted <class int> but got "+str(type(new_rank)))
292
+        if new_rank < 0 or new_rank > self.get_max_rank(getattr(self, self.ranked_in)):
293
+            raise ValueError("Invalid new rank : "+str(new_rank))
294
+        #more checks to be done here
295
+        mod = new_rank - self.rank
296
+
297
+        if mod == 0:
298
+            return True
299
+
300
+        limits = [ self.rank + ( 1 if mod > 0 else -1), new_rank ]
301
+        limits.sort()
302
+
303
+        dbe = self.db_engine()
304
+        conn = dbe.connect()
305
+        table = sqlutils.get_table(self.__class__)
306
+
307
+        #Selecting the components that will be modified
308
+        req = table.select().where( getattr(table.c, self.ranked_in) == getattr(self, self.ranked_in)).where(table.c.rank >= limits[0]).where(table.c.rank <= limits[1])
309
+
310
+        res = conn.execute(req)
311
+        if not res:
312
+            return False
313
+
314
+        rows = res.fetchall()
315
+
316
+        updated_ranks = [{'b_uid': self.uid, 'b_rank': new_rank}]
317
+
318
+        for row in rows:
319
+            updated_ranks.append({'b_uid': row['uid'], 'b_rank': row['rank'] + (-1 if mod > 0 else 1)})
320
+        req = table.update().where(table.c.uid == sql.bindparam('b_uid')).values(rank=sql.bindparam('b_rank'))
321
+        res = conn.execute(req, updated_ranks)
322
+        conn.close()
295 323
         
296
-        if isinstance(new_rank, int):
297
-            if (new_rank >= 0):
298
-                dbe = self.__class__.db_engine()
299
-                component = sql.Table(self.table, sqlutils.meta(dbe))
300
-                req = sql.sql.select([component.c.uid, component.c.rank])
301
-
302
-                if (type(sign) is not str):
303
-                    logger.error("Bad argument")
304
-                    raise TypeError('Excepted a string (\'=\' or \'+\' or \'-\') not a ' + str(type(sign)))
305
-
306
-                if (sign == '='):
307
-                    req = sql.sql.select([component.c.uid, component.c.rank])
308
-                    req = req.where((getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)) & (component.c.rank == new_rank))
309
-                    conn = dbe.connect()
310
-                    res = conn.execute(req)
311
-                    res = res.fetchone()
312
-                    conn.close()
313
-
314
-                    if (res is not None):
315
-                        req = sql.sql.select([component.c.uid, component.c.rank])
316
-                        if(new_rank < self.rank):
317
-                            req = req.where((getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)) & (component.c.rank >= new_rank) & (component.c.rank < self.rank))
318
-                        else:
319
-                            req = req.where((getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)) & (component.c.rank <= new_rank) & (component.c.rank > self.rank))
320
-
321
-                        conn = dbe.connect()
322
-                        res = conn.execute(req)
323
-                        res = res.fetchall()
324
-
325
-                        vals = list()
326
-                        vals.append({'id': self.uid, 'rank': new_rank})
327
-
328
-                        for row in res:
329
-                            if(new_rank < self.rank):
330
-                                vals.append({'id': row.uid, 'rank': row.rank + 1})
331
-                            else:
332
-                                vals.append({'id': row.uid, 'rank': row.rank - 1})
333
-
334
-                        req = component.update().where(component.c.uid == sql.bindparam('id')).values(rank=sql.bindparam('rank'))
335
-                        conn.execute(req, vals)
336
-                        conn.close()
337
-
338
-                        self._fields['rank'].value = new_rank
339
-
340
-                    else:
341
-                        logger.error("Bad argument")
342
-
343
-                        raise ValueError('new_rank to big, new_rank - 1 doesn\'t exist. new_rank = '+str((new_rank)))
344
-                elif(sign == '+' and self.rank + new_rank <= self.__class__.get_max_rank(getattr(self, self.__class__.ranked_in))):
345
-                    req = sql.sql.select([component.c.uid, component.c.rank])
346
-                    req = req.where((getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)) & (component.c.rank == self.rank + new_rank))
347
-                    conn = dbe.connect()
348
-                    res = conn.execute(req)
349
-                    res = res.fetchone()
350
-                    conn.close()
351
-
352
-                    if (res is not None):
353
-                        if (new_rank != 0):
354
-                            req = sql.sql.select([component.c.uid, component.c.rank])
355
-                            req = req.where((getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)) & (component.c.rank <= self.rank + new_rank) & (component.c.rank > self.rank))
356
-
357
-                            conn = dbe.connect()
358
-                            res = conn.execute(req)
359
-                            res = res.fetchall()
360
-
361
-                            vals = list()
362
-                            vals.append({'id': self.uid, 'rank': self.rank + new_rank})
363
-
364
-                            for row in res:
365
-                                vals.append({'id': row.uid, 'rank': row.rank - 1})
366
-
367
-                            req = component.update().where(component.c.uid == sql.bindparam('id')).values(rank=sql.bindparam('rank'))
368
-                            conn.execute(req, vals)
369
-                            conn.close()
370
-
371
-                            self._fields['rank'] += new_rank
372
-                        else:
373
-                            logger.error("Bad argument")
374
-                            raise ValueError('Excepted a positive int not a null. new_rank = ' + str((new_rank)))
375
-                    else:
376
-                        logger.error("Bad argument")
377
-                        raise ValueError('new_rank to big, rank + new rank doesn\'t exist. new_rank = ' + str((new_rank)))
378
-                elif (sign == '-' and self.rank - new_rank >= 0):
379
-                    if ((self.rank + new_rank) > 0):
380
-                        if (new_rank != 0):
381
-                            req = sql.sql.select([component.c.uid, component.c.rank])
382
-                            req = req.where((getattr(component.c, self.ranked_in) == getattr(self, self.ranked_in)) & (component.c.rank >= self.rank - new_rank) & (component.c.rank < self.rank))
383
-
384
-                            conn = dbe.connect()
385
-                            res = conn.execute(req)
386
-                            res = res.fetchall()
387
-
388
-                            vals = list()
389
-                            vals.append({'id': self.uid, 'rank': self.rank - new_rank})
390
-
391
-                            for row in res:
392
-                                vals.append({'id': row.uid, 'rank': row.rank + 1})
393
-
394
-                            req = component.update().where(component.c.uid == sql.bindparam('id')).values(rank=sql.bindparam('rank'))
395
-                            conn.execute(req, vals)
396
-                            conn.close()
397
-
398
-                            self._fields['rank'] -= new_rank
399
-                        else:
400
-                            logger.error("Bad argument")
401
-                            raise ValueError('Excepted a positive int not a null. new_rank = ' + str((new_rank)))
402
-                    else:
403
-                        logger.error("Bad argument")
404
-                        raise ValueError('new_rank to big, rank - new rank is negative. new_rank = ' + str((new_rank)))
405
-                else:
406
-                    logger.error("Bad argument")
407
-                    raise ValueError('Excepted a string (\'=\' or \'+\' or \'-\') not a ' + str((sign)))
408
-
409
-            else:
410
-                logger.error("Bad argument")
411
-                raise ValueError('Excepted a positive int not a negative. new_rank = ' + str((new_rank)))
324
+        if res:
325
+            self._fields['rank'].value = new_rank
326
+        return bool(res)
327
+    
328
+    ## @brief Modify a rank given a sign and a new_rank
329
+    # - If sign is '=' set the rank to new_rank
330
+    # - If sign is '-' set the rank to cur_rank - new_rank
331
+    # - If sign is '+' set the rank to cur_rank + new_rank
332
+    # @param new_rank int: The new_rank or rank modifier
333
+    # @param sign str: Can be one of '=', '+', '-'
334
+    # @return True if success False if fails
335
+    # @throw TypeError If bad argument type
336
+    # @throw ValueError if out of bound value
337
+    def modify_rank(self,new_rank, sign='='):
338
+        if not isinstance(new_rank, int) or not isinstance(sign, str):
339
+            raise TypeError("Excepted <class int>, <class str>. But got "+str(type(new_rank))+", "+str(type(sign)))
340
+
341
+        if sign == '+':
342
+            return self.set_rank(self.rank + new_rank)
343
+        elif sign == '-':
344
+            return self.set_rank(self.rank - new_rank)
345
+        elif sign == '=':
346
+            return self.set_rank(new_rank)
412 347
         else:
413
-            logger.error("Bad argument")
414
-            raise TypeError('Excepted a int not a ' + str(type(new_rank)))
348
+            raise ValueError("Excepted one of '=', '+', '-' for sign argument, but got "+sign)
415 349
 
350
+    ## @brief Return a string representation of the component
351
+    # @return A string representation of the component
416 352
     def __repr__(self):
417 353
         if self.name is None:
418 354
             return "<%s #%s, 'non populated'>" % (type(self).__name__, self.uid)

+ 0
- 4
EditorialModel/test/test_component.py View File

@@ -629,10 +629,6 @@ class TestModifyRank(ComponentTestCase):
629 629
             ((0.0, '='), TypeError),
630 630
             
631 631
             #Bad new_rank
632
-            ((0,'+'), ValueError),
633
-            ((0,'-'), ValueError),
634
-            ((-1, '+'), ValueError),
635
-            ((-1,'-'), ValueError),
636 632
             ((-1, '='), ValueError),
637 633
             ((-1,), ValueError),
638 634
             

Loading…
Cancel
Save