• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
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
3# found in the LICENSE file.
4
5from future import Future
6from object_store import ObjectStore
7
8class TestObjectStore(ObjectStore):
9  '''An object store which records its namespace and behaves like a dict.
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.
13  '''
14  def __init__(self, namespace, start_empty=False, init=None):
15    self.namespace = namespace
16    self.start_empty = start_empty
17    self._store = {} if init is None else init
18    if start_empty:
19      assert not self._store
20    self._get_count = 0
21    self._set_count = 0
22    self._del_count = 0
23
24  #
25  # ObjectStore implementation.
26  #
27
28  def GetMulti(self, keys):
29    class FutureImpl(object):
30      def Get(self2):
31        self._get_count += 1
32        return dict((k, self._store.get(k)) for k in keys if k in self._store)
33    return Future(delegate=FutureImpl())
34
35  def SetMulti(self, mapping):
36    self._set_count += 1
37    self._store.update(mapping)
38
39  def DelMulti(self, keys):
40    self._del_count += 1
41    for k in keys:
42      self._store.pop(k, None)
43
44  #
45  # Testing methods.
46  #
47
48  def CheckAndReset(self, get_count=0, set_count=0, del_count=0):
49    '''Returns a tuple (success, error). Use in tests like:
50    self.assertTrue(*object_store.CheckAndReset(...))
51    '''
52    errors = []
53    for desc, expected, actual in (('get_count', get_count, self._get_count),
54                                   ('set_count', set_count, self._set_count),
55                                   ('del_count', del_count, self._del_count)):
56      if actual != expected:
57        errors.append('%s: expected %s got %s' % (desc, expected, actual))
58    try:
59      return (len(errors) == 0, ', '.join(errors))
60    finally:
61      self.Reset()
62
63  def Reset(self):
64    self._get_count = 0
65    self._set_count = 0
66    self._del_count = 0
67