Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can `MagicMock` compare with int in python3?

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__
like image 864
John Smith Avatar asked Jan 22 '19 04:01

John Smith


People also ask

What's the difference between mock and MagicMock?

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.

What is MagicMock in Python?

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.

What is MagicMock Pytest?

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.


1 Answers

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
like image 157
Cropse Avatar answered Sep 28 '22 10:09

Cropse