Reputation: 109
I have an issue with testing and I was hoping for some help.
A colleague of mine pointed me towards unittest.mock and patch and they seem to be exactly what I need, but I am unable to get this working correctly.
Problem written: I have my test case which calls and tests a function (foo) in a python file (fooFile) which calls another function (bar) in another python file (barFile). The bar function is what I need to mock from the test file.
Example code:
barFile.py
#homedir.lib.barFile.py
def bar(object2):
return False
fooFile.py
#homedir.api.fooFile.py
from homedir.lib.barFile import bar
def foo(object1):
result = bar(object1['item1'])
if result:
return 200
else:
return 400
testFooFile.py -- no mocking
#homedir.tests.testFooFile.py
from homedir.api.fooFile import foo
def testFoo():
payload = {"item1": "nothing"}
result = foo(payload)
assert result == 200
Basically, from the testFooFile.py file, I need to mock the bar function and get that to return True. I can only call bar through foo and this is where my issue lies. I can mock the bar function fine, but only when I call it directly from the testFile, not when it is called by the foo function. Here is somewhat along the lines of what I currently have.
testFooFile.py -- current idea
#homedir.tests.testFooFile.py
from unittest.mock import patch
from homedir.api.fooFile import foo
@patch('homedir.lib.barFile.bar')
def testFoo(mock_bar):
mock_bar.return_value = True
payload = {"item1": "nothing"}
result = foo(payload)
assert result == 200
Upvotes: 1
Views: 61
Reputation: 439
I believe that the path you are patching should be homedir.api.fooFile.bar
. You need to patch the instance of bar()
that foo()
is using, which is located in fooFile.py
.
Upvotes: 1