[英]Patch over a function imported inside another function
為了避免循環導入,我被迫定義一個看起來像這樣的函數:
# do_something.py
def do_it():
from .helpers import do_it_helper
# do stuff
現在我希望能夠測試這個函數,並do_it_helper
。 如果導入是頂級導入,
class Test_do_it(unittest.TestCase):
def test_do_it(self):
with patch('do_something.do_it_helper') as helper_mock:
helper_mock.return_value = 12
# test things
會工作得很好。 但是,上面的代碼給了我:
AttributeError: <module 'do_something'> does not have the attribute 'do_it_helper'
一時興起,我也嘗試將補丁語句更改為:
with patch('do_something.do_it.do_it_helper') as helper_mock:
但這產生了類似的錯誤。 有沒有辦法模擬這個函數,因為我被迫在它使用的函數中導入它?
你應該嘲笑helpers.do_it_helper
:
class Test_do_it(unittest.TestCase):
def test_do_it(self):
with patch('helpers.do_it_helper') as helper_mock:
helper_mock.return_value = 12
# test things
這是在os.getcwd()
上使用mock的示例:
import unittest
from mock import patch
def get_cwd():
from os import getcwd
return getcwd()
class MyTestCase(unittest.TestCase):
@patch('os.getcwd')
def test_mocked(self, mock_function):
mock_function.return_value = 'test'
self.assertEqual(get_cwd(), 'test')
希望有所幫助。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.