Skip to content

Commit 20bf1ef

Browse files
committed
Enable FakeResource to fake methods.
Use MagicMock to fake a method in FakeResource. A new function: add_method(name, return_value) is added to FakeResource. The caller specifies method @name and @return_value, the function will add an attribute with @name, which is a callable MagicMock object whose return value is @return_value. When user access the attribute with a (), @return_value will be returned by MagicMock, which looks like a function call. Change-Id: I12eb876cbebab064773df7b5dd612de69bbf3f01 Implements: blueprint osc-unit-test-framework-improvement
1 parent 5f6f456 commit 20bf1ef

1 file changed

Lines changed: 26 additions & 1 deletion

File tree

openstackclient/tests/fakes.py

Lines changed: 26 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414
#
1515

1616
import json
17+
import mock
1718
import six
1819
import sys
1920

@@ -122,17 +123,41 @@ def __init__(self, name, version):
122123

123124

124125
class FakeResource(object):
125-
def __init__(self, manager, info, loaded=False):
126+
def __init__(self, manager=None, info={}, loaded=False, methods={}):
127+
"""Set attributes and methods for a resource.
128+
129+
:param manager:
130+
The resource manager
131+
:param Dictionary info:
132+
A dictionary with all attributes
133+
:param bool loaded:
134+
True if the resource is loaded in memory
135+
:param Dictionary methods:
136+
A dictionary with all methods
137+
"""
126138
self.__name__ = type(self).__name__
127139
self.manager = manager
128140
self._info = info
129141
self._add_details(info)
142+
self._add_methods(methods)
130143
self._loaded = loaded
131144

132145
def _add_details(self, info):
133146
for (k, v) in six.iteritems(info):
134147
setattr(self, k, v)
135148

149+
def _add_methods(self, methods):
150+
"""Fake methods with MagicMock objects.
151+
152+
For each <@key, @value> pairs in methods, add an callable MagicMock
153+
object named @key as an attribute, and set the mock's return_value to
154+
@value. When users access the attribute with (), @value will be
155+
returned, which looks like a function call.
156+
"""
157+
for (name, ret) in six.iteritems(methods):
158+
method = mock.MagicMock(return_value=ret)
159+
setattr(self, name, method)
160+
136161
def __repr__(self):
137162
reprkeys = sorted(k for k in self.__dict__.keys() if k[0] != '_' and
138163
k != 'manager')

0 commit comments

Comments
 (0)