Skip to content

Commit d0199bd

Browse files
committed
Added methods spy and stub to mocker fixture
1 parent 9c8c3d4 commit d0199bd

File tree

2 files changed

+48
-0
lines changed

2 files changed

+48
-0
lines changed

pytest_mock.py

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,31 @@ def stopall(self):
3131
p.stop()
3232
self._patches[:] = []
3333

34+
def spy(self, obj, method_name):
35+
"""
36+
Creates a spy of method. It will run method normally, but it is now possible to use `mock`
37+
call features with it, like call count.
38+
39+
:param object obj:
40+
An object.
41+
42+
:param unicode method_name:
43+
A method in object.
44+
45+
:return: mock.MagicMock
46+
Spy object.
47+
"""
48+
return self.patch.object(obj, method_name, side_effect=getattr(obj, method_name))
49+
50+
def stub(self):
51+
"""
52+
Creates a stub method. It accepts any arguments. Ideal to register to callbacks in tests.
53+
54+
:return: mock.MagicMock
55+
Stub object.
56+
"""
57+
return mock_module.MagicMock(spec=lambda *args, **kwargs: None)
58+
3459
class _Patcher(object):
3560
"""
3661
Object to provide the same interface as mock.patch, mock.patch.object,

test_pytest_mock.py

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -136,3 +136,26 @@ def test_mocker_has_mock_class_as_attribute_for_instantiation():
136136

137137
mocker = MockFixture()
138138
assert isinstance(mocker.Mock(), mock_module.Mock)
139+
140+
141+
def test_mocker_spy(mocker):
142+
class Foo(object):
143+
144+
def bar(self, arg):
145+
return arg * 2
146+
147+
foo = Foo()
148+
spy = mocker.spy(foo, 'Bar')
149+
150+
assert foo.Bar(arg=10) == 20
151+
spy.assert_called_once_with(arg=10)
152+
153+
154+
def test_mocker_stub(mocker):
155+
def Foo(on_something):
156+
on_something('foo', 'bar')
157+
158+
stub = mocker.stub()
159+
160+
Foo(stub)
161+
stub.assert_called_once_with('foo', 'bar')

0 commit comments

Comments
 (0)