I am migrating python's version (2->3) of my project. The tests works fine for python2, but complains for python3, the error is like
TypeError: '>' not supported between instances of 'MagicMock' and 'int'
here is a minimal case
# test_mock.py
try:
from mock import MagicMock
except:
from unittest.mock import MagicMock
def test_mock_func():
a = MagicMock()
b = a.value
if b > 100:
assert True
else:
assert True
just run py.test .
These hacks not work
MagicMock.__le__ = some_le_method # just not working
MagicMock.__le__.__func__.__code = some_le_method.__func__.__code__ # wrapper_descriptor does not have attribute __func__
So what is the difference between them? MagicMock is a subclass of Mock . It contains all magic methods pre-created and ready to use (e.g. __str__ , __len__ , etc.). Therefore, you should use MagicMock when you need magic methods, and Mock if you don't need them.
MagicMock. MagicMock objects provide a simple mocking interface that allows you to set the return value or other behavior of the function or object creation call that you patched. This allows you to fully define the behavior of the call and avoid creating real objects, which can be onerous.
The workhorse: MagicMock The basic idea is that MagicMock a placeholder object with placeholder attributes that can be passed into any function. I can. mock a constant, mock an object with attributes, or mock a function, because a function is an object in Python and the attribute in this case is its return value.
You should assign the __gt__
inside b
or a.value
# self is MagicMock itself
b.__gt__ = lambda self, compare: True
# or
a.value.__gt__ = lambda self, compare: True
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With