При следующей структуре каталогов:
Код: Выделить всё
|-- mypackage
| |-- mymodule
| | |-- __init__.py
| | \-- somefile.py
| \-- myothermodule
| |-- tests
| | |-- __init__.py
| | \-- test_func_to_test.py
| \-- __init__.py
\-- __init__.py
Код: Выделить всё
#mypackage/mymodule/somefile.py
def some_function():
return 'A'
Код: Выделить всё
#mypackage/myothermodule/__init__.py
from mypackage.mymodule.somefile import some_function
def func_to_test():
return some_function()
Код: Выделить всё
#mypackage/myothermodule/tests/test_func_to_test.py
from unittest import TestCase
from mock import patch
class TestFunc_to_test(TestCase):
def test_func_to_test(self):
from mypackage.myothermodule import func_to_test
self.assertEqual('A', func_to_test())
@patch('mypackage.mymodule.somefile.some_function')
def test_func_to_test_mocked(self, some_mock_function):
from mypackage.myothermodule import func_to_test
some_mock_function.return_value = 'B'
self.assertEqual('B', func_to_test())
Мне удалось имитировать функцию из «встроенных» модулей (например, Requests.get), используя тот же подход, однако я не могу заставить @patch работать при попытке исправить функцию из одного из моих модулей.