Code:
from unittest.mock import Mock
mock = Mock()
print('mock.f():', id(mock.f()))
print('mock.f().g().h():', id(mock.f().g().h()))
print('mock():', id(mock()))
print('mock().f():', id(mock().f()))
print()
print('mock.f():', id(mock.f()))
print('mock.f().g().h():', id(mock.f().g().h()))
print('mock():', id(mock()))
print('mock().f():', id(mock().f()))
print()
print('mock.f(1):', id(mock.f(1)))
print('mock.f(2).g(3).h(4):', id(mock.f(2).g(3).h(4)))
print('mock(5):', id(mock(5)))
print('mock(6).f(7):', id(mock(6).f(7)))
print()
Output:
mock.f(): 4483288208
mock.f().g().h(): 4483354192
mock(): 4483368976
mock().f(): 4483708880
mock.f(): 4483288208
mock.f().g().h(): 4483354192
mock(): 4483368976
mock().f(): 4483708880
mock.f(1): 4483288208
mock.f(2).g(3).h(4): 4483354192
mock(5): 4483368976
mock(6).f(7): 4483708880
Observation:
The output shows that a specified chained function call on a mock always returns the same object within the lifetime of a program regardless of how many times we make that call.
For example, the first call to mock.f().g().h(), the second call to mock.f().g().h(), and even the third call with different arguments mock.f(2).g(3).h(4) return the exact same object.
Question:
- Can we rely on this behavior? Is it guaranteed that within the lifetime of a program,
mock.f().g().h()would return the exact same mock object? - Is it guaranteed that even the same chain of calls with different arguments, e.g.,
mock.f(2).g(3).h(4)would also return the same object as amock.f().g().h()? - Are both these things documented somewhere?
Background:
The reason why I am asking this is so that instead of writing code like this:
from urllib import request
from unittest.mock import Mock, patch
with patch('urllib.request.urlopen') as mock_urlopen:
mock_urlopen.return_value = Mock()
mock_urlopen().getcode.return_value = 200
assert request.urlopen('').getcode() == 200
I can write code like this insted:
from urllib import request
from unittest.mock import Mock, patch
with patch('urllib.request.urlopen') as mock_urlopen:
mock_urlopen().getcode.return_value = 200
assert request.urlopen('').getcode() == 200
The examples above are too simple only for demo purpose. I wanted to keep self-contained examples. But if I could rely on this feature, it would become very convenient when the chain of function calls are long. That's why I am looking for some sort of reference or documentation that shows that I can rely on this behavior.
from Would the same chain of calls on a mock always return the exact same mock object?
No comments:
Post a Comment