Romanzo Criminale
Romanzo Criminale

Reputation: 1349

Python mocking global variable

I'm using the sys.modules['cv2'] = Mock() to mock the OpenCV module but I'm having trouble to use the assertEqual to test if a variable has been set up correctly with a global variable. I've simplified the code a bit. I'm not sure if my mocking is right.

Here is my unit test file:

from mock import patch, Mock
sys.modules['cv2'] = Mock()
from MyClass import MyClass
del sys.modules['cv2']

....

def testFunction()
    myObject = MyClass()
    self.assertEqual(myObject.val, ?) # here i don't know how to test the equality

and the file MyClass.py:

import module

val1 = cv2.function(1)
val2 = cv2.function(2)

class MyClass():
    def _init_(self)
        self.val = val1

Upvotes: 1

Views: 8121

Answers (2)

Michele d'Amico
Michele d'Amico

Reputation: 23711

Maybe the best way to do what you want to do is patch var1. Anyway, because I'm not sure about what you want to do I'm proposing to you some solutions:

from mock import patch

@patch("cv2.function")
def testfunction(mfun):
    mfun.return_value = 200
    import MyClass
    MyObject = MyClass.MyClass()
    assert MyObject.var == 200


import MyClass
print(MyClass.MyClass().var) #my cv2.function(1) stub return -1... but here you can see the real value

@patch("MyClass.var1")
def testfunction(mvar1):
    mvar1 = 300
    MyObject = MyClass.MyClass()
    assert MyObject.var == 300

Note that in the first case you MUST import MyClass in patch context. The second example just the variable on your module will be patched.

If you must write lot of methods that use a patch like in first example you can use patch as class decorator of unittest class: you will patch cv2 function in all tests.

Upvotes: 2

user1415946
user1415946

Reputation:

class Chameleon(Mock):
    def __eq__(self, other):
        return True

Also have a look at MagicMock.

Upvotes: 0

Related Questions