mocking python class dictionary

246 views Asked by At

I am fairly new to python. I am trying to use mock to write a unit test. Here is the pattern of the code.

# mod3.py
import mod1.class1
import mod2.class2

d = {
"c1": class1
"c2": class2
} 

def func1(c, v):
   cl = d[c]
   o = cl().meth1(v)
   return o

I want to write an unit test for func1.

def test_func1(c, v):
   c, v = mock.Mock(), mock.Mock()
   r = mod3.func1(c,v)
   e = {"key1": "value1"}
   #want to check if the ret val is as expected

How would I use mock to essentially mock cl().meth1(v)

1

There are 1 answers

1
lxyscls On
# cat class1.py
def func(v):
    return v
# cat class2.py
def func(v):
    return v
#cat mock.py
import class1, class2
d = { "c1": class1, "c2": class2 }
def func1(c, v):
    cl = d[c]
    o = cl.func(v)
    return o

class1 and class2 are modules in python. Do you want this?