OLD | NEW |
1 # Copyright 2013 The Chromium Authors. All rights reserved. | 1 # Copyright 2013 The Chromium Authors. All rights reserved. |
2 # Use of this source code is governed by a BSD-style license that can be | 2 # Use of this source code is governed by a BSD-style license that can be |
3 # found in the LICENSE file. | 3 # found in the LICENSE file. |
4 | 4 |
5 from future import Future | 5 from future import Future |
6 from object_store import ObjectStore | 6 from object_store import ObjectStore |
7 | 7 |
8 class TestObjectStore(ObjectStore): | 8 class TestObjectStore(ObjectStore): |
9 '''An object store which records its namespace and behaves like a dict, for | 9 '''An object store which records its namespace and behaves like a dict. |
10 testing. | 10 Specify |init| with an initial object for the object store. |
| 11 Use CheckAndReset to assert how many times Get/Set/Del have been called. Get |
| 12 is a special case; it is only incremented once the future has had Get called. |
11 ''' | 13 ''' |
12 def __init__(self, namespace): | 14 def __init__(self, namespace, init=None): |
13 self.namespace = namespace | 15 self.namespace = namespace |
14 self._store = {} | 16 self._store = init or {} |
| 17 self._get_count = 0 |
| 18 self._set_count = 0 |
| 19 self._del_count = 0 |
15 | 20 |
16 def SetMulti(self, mapping, **optarg): | 21 # |
| 22 # ObjectStore implementation. |
| 23 # |
| 24 |
| 25 def GetMulti(self, keys): |
| 26 class FutureImpl(object): |
| 27 def Get(self2): |
| 28 self._get_count += 1 |
| 29 return dict((k, self._store.get(k)) for k in keys if k in self._store) |
| 30 return Future(delegate=FutureImpl()) |
| 31 |
| 32 def SetMulti(self, mapping): |
| 33 self._set_count += 1 |
17 self._store.update(mapping) | 34 self._store.update(mapping) |
18 | 35 |
19 def GetMulti(self, keys, **optargs): | 36 def DelMulti(self, keys): |
20 return Future(value=dict((k, v) for k, v in self._store.items() | 37 self._del_count += 1 |
21 if k in keys)) | 38 for k in keys: |
| 39 self._store.pop(k, None) |
22 | 40 |
23 def Delete(self, key): | 41 # |
24 del self._store[key] | 42 # Testing methods. |
| 43 # |
| 44 |
| 45 def CheckAndReset(self, get_count=0, set_count=0, del_count=0): |
| 46 '''Returns a tuple (success, error). Use in tests like: |
| 47 self.assertTrue(*object_store.CheckAndReset(...)) |
| 48 ''' |
| 49 errors = [] |
| 50 for desc, expected, actual in (('get_count', get_count, self._get_count), |
| 51 ('set_count', set_count, self._set_count), |
| 52 ('del_count', del_count, self._del_count)): |
| 53 if actual != expected: |
| 54 errors.append('%s: expected %s got %s' % (desc, expected, actual)) |
| 55 try: |
| 56 return (len(errors) == 0, ','.join(errors)) |
| 57 finally: |
| 58 self.Reset() |
| 59 |
| 60 def Reset(self): |
| 61 self._get_count = 0 |
| 62 self._set_count = 0 |
| 63 self._del_count = 0 |
OLD | NEW |