• 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    def callback():
30      self._get_count += 1
31      return dict((k, self._store.get(k)) for k in keys if k in self._store)
32    return Future(callback=callback)
33
34  def SetMulti(self, mapping):
35    self._set_count += 1
36    self._store.update(mapping)
37
38  def DelMulti(self, keys):
39    self._del_count += 1
40    for k in keys:
41      self._store.pop(k, None)
42
43  #
44  # Testing methods.
45  #
46
47  def CheckAndReset(self, get_count=0, set_count=0, del_count=0):
48    '''Returns a tuple (success, error). Use in tests like:
49    self.assertTrue(*object_store.CheckAndReset(...))
50    '''
51    errors = []
52    for desc, expected, actual in (('get_count', get_count, self._get_count),
53                                   ('set_count', set_count, self._set_count),
54                                   ('del_count', del_count, self._del_count)):
55      if actual != expected:
56        errors.append('%s: expected %s got %s' % (desc, expected, actual))
57    try:
58      return (len(errors) == 0, ', '.join(errors))
59    finally:
60      self.Reset()
61
62  def Reset(self):
63    self._get_count = 0
64    self._set_count = 0
65    self._del_count = 0
66