7

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__
ShadowRanger
  • 143,180
  • 12
  • 188
  • 271
John Smith
  • 153
  • 1
  • 7
  • If that worked in Python 2 the comparison is faulty making the test faulty as well. Python 2 was less strict and comparison results were surprising sometimes. So, what are actually testing with that? – Klaus D. Jan 22 '19 at 04:35
  • It's where the code handling web requests, the response has a field which should be a timestamp. To avoid network communication I send a `MagicMock` as the response. The error occurs where comparing the timestamp with another. – John Smith Jan 22 '19 at 04:55
  • `a.value` is undefined unless explicitly set. You should set it (to a number), and then the comparison will be possible. – DYZ Jan 22 '19 at 05:18
  • No, it's not undefined. It's an instance of `MagicMock` – John Smith Jan 22 '19 at 07:55

1 Answers1

1

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
Cropse
  • 11
  • 2