Reputation: 16469
In my test function, my mocks are not behaving properly because when I mock
my get_config
function, I only know how to mock it to return one value. How can I add some logic to my mock
in order for the mock to return a different value only when get_config
is passed the argument of "restricted"
def func():
conf1 = get_config("conf1")
conf2 = get_config("conf2")
conf3 = get_config("conf3")
restricted_datasets = get_config("restricted")
dataset = get_config("dataset")
if dataset not in restricted_datas:
return run_code()
Upvotes: 3
Views: 10735
Reputation: 76
class Ctx():
def get_config(confName):
return confName
def mock_get_config(value):
if value == "conf1":
return "confA"
elif value == "conf2":
return "confB"
else:
return "UnknownValue"
class CtxSourceFileTrial(unittest.TestCase):
def test(self):
mockCtx = Mock()
mockCtx.get_config.side_effect = mock_get_config
self.assertEqual("confA", mockCtx.get_config("conf1"))
self.assertEqual("confB", mockCtx.get_config("conf2"))
#
# By the way I think Python is EXTREMELY screwy, Adligo
#
Upvotes: 2
Reputation: 6560
You can assign a function to side_effect
as described in official doc
from unittest.mock import Mock
def side_effect(value):
return value
m = Mock(side_effect=side_effect)
m('restricted')
'restricted'
Upvotes: 3