I'm having some trouble mocking a function. Said function is imported and used in run_parsers.py
and I'm getting
ImportError: 'No module named run_parsers'
When I'm attempting to mock.patch
run_parsers.py
.
Here's my test code in test_run_parsers.py
from .. import run_parsers # Used in all my other tests.
def test_node_data_parser_throws_exception(self):
def parser():
return NotImplementedError()
with mock.patch("run_parsers.get_node_paths") as node_paths:
node_paths.return_value = "node_1"
run_parsers.get_node_data(parser, "/a/path")
Here's my repository structure
control_scripts
├── __init__.py
├── README.md
├── run_all_parsers.py
├── run_parsers.py
└── tests
├── __init__.py
├── test_run_parsers.py
According to this tutorial I'm supposed to mock where the function is imported. This is why I'm attempting to mock the calling module rather than the module that defines get_node_paths
I'm not sure if this duplicates your setup exactly, but here is a simple test case that worked for me.
The directory setup is:
c:\work
\control
__init__.py
scripts.py
\tests
__inti__.py
mytests.py
and c:\work is on sys.path
In the module scripts.py:
def identity(x):
return x
def do_identity(x):
return identity(x)
In mytests.py:
import unittest
from unittest.mock import patch
from control import scripts
class MyTest(unittest.TestCase):
def test_patch(self):
with patch('control.scripts.identity') as mymock:
mymock.return_value = 99
self.assertEqual(scripts.do_identity(1), 99)
def test_no_patch(self):
self.assertEqual(scripts.do_identity(1), 1)
if __name__ == "__main__":
unittest.main()
So what I am trying to do here is to mock the function 'identity' which is called by the function 'do_identity'. Both functions are in the 'scripts' module. This test runs with no errors or failures.
And I can run this from any directory as:
c:\any_directory> python c:\work\control\tests\mytests.py
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With