Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 Unittest: How to compare with MagicMocks Using Operators

Easiest thing is to start with an example...

Example code to put under test:

type1_instance1 = f1()
type1_instance2 = f2()

compareResult = type1_instance1 < type1_intstance2

if compareResult:
    print(type1_instance1.generate_value())

Instance 1 and 2 are instances of some custom class.

When under test f1 and f2 are mocked to return MagicMocks. So that methods of the custom class can be called on those returned values.

When the compare code is executed I get the error

'<' not supported between instances of 'MagicMock' and 'MagicMock'

What's the best way to enable MagicMocks to work with overloaded operators?

Here was my solution:

def __lt__(self, other):
    return mock.MagicMock

compareable_MagicMock_Instance = MagicMock()
setattr(compareable_MagicMock_Instance, '__lt__', __lt__)

f1.return_value = compareable_MagicMock_Instance
f2.return_value = another_compareable_MagicMock_Instance
like image 679
Jerinaw Avatar asked Oct 19 '25 05:10

Jerinaw


1 Answers

You should override the return_value attribute of the __lt__ attribute of the MagicMock object instead, and use patch to make f1 and f2 return the customized MagicMock instance:

from unittest.mock import patch, MagicMock
def f1():
    pass
def f2():
    pass
compareable_MagicMock_Instance = MagicMock()
compareable_MagicMock_Instance.__lt__.return_value = True
with patch('__main__.f1', return_value=compareable_MagicMock_Instance), patch('__main__.f2', return_value=compareable_MagicMock_Instance):
    type1_instance1 = f1()
    type1_instance2 = f2()
    compareResult = type1_instance1 < type1_instance2
    if compareResult:
        print('type1_instance1 is less than type1_instance2')

This outputs:

type1_instance1 is less than type1_instance2
like image 83
blhsing Avatar answered Oct 21 '25 18:10

blhsing



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!