pytest-dev / pytest-dev/pytest-mock
Make spy a context manager
Open
Nobody has claimed this yet.
enhancement
- Dominant language
- Python
- Stars
- 2k
- Forks
- 173
- Avg merge
- 1d 10h
- Merged PRs (30d)
- 6
Description
Capture return value
NOTE: already implemented in 1.11
class SomeClass:
def method(self, a):
return a * 2
def facade(self):
self.method(4)
return 'Done'
def test_some_class(mocker):
spy = mocker.spy(SomeClass, 'method')
o = SomeClass()
o.facade()
assert spy.called
assert spy.call_count == 1
print(spy.mock_calls[0])
# nicely outputs method arguments
# call(<m.SomeClass object at 0x7febfed74518>, 4)
print(spy.return_value)
# just tells us we have mock object here
# <MagicMock name='method()' id='140651569552856'>
# it would be much better to have there
# assert spy.return_value == 8
# or, rather
# assert spy.mock_calls[0].return_value == 8
Spy as context manager
That's probably kind of misusing mocker object, but in my case there's a quite long test and I want to restrict fragment of code where particular spy object is applied.
def test_context_mgr(mocker):
o = SomeClass()
with mocker.spy(SomeClass, 'method') as spy: # AttributeError: __enter__ here
o.facade()
assert spy.call_count == 1
o.facade()
Currently I can only find arguments
Contributor guide
First steps
- Read the whole issue, then the project's contributing guide.
- Comment on the issue to say you are picking it up — it saves two people doing the same work.
- Fork the repository and make your change on a branch.
- Open a pull request that references the issue number.
Research direction
The issue names no implementation file or test; start by reading the spy entry point and existing spy tests, then compare them with the context-manager example. Done means the spy can be used in a with block for the selected code fragment and the example's call-count assertions remain valid after exiting it.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- python
- Domain
- testing
- Issue type
- Feature
- Difficulty
- 3/5
- Estimated time
- 1-2 days
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100