[英]How to mock the module import of a class in pytest
我正在嘗試測試從其他模塊導入 function 的 class 。 我想模擬 function 調用。 我不知道怎么做。
please_configure.py
from src.messages.create import create_please
class PleaseConfigure():
def __init__():
self._call = { "create_please": create_please }
def handle_call(msg):
self._call[msg["method"]](msg["args"])
創建.py
def create_please(args):
# does something not so important
test_please_configure.py
from src.consumers.please_configure import PleaseConfigure
@patch.object(PleaseConfigure, "_call")
def test_please_configure_success(mocked_call):
cf = PleaseConfigure()
# want to test cf.handle_call()
我已將上述類簡化到它們顯然不再做太多事情的程度,但這是 3 個文件之間的正確導入層次結構。 在 PleaseConfigure 的實例中,_call 字典中的 mocking 和 function 應該如何?
在 test_please_configure_success 我嘗試了以下變化:
@patch.object(PleaseConfigure, "_call")
@patch.object(PleaseConfigure, "create_please")
@patch.object(PleaseConfigure, "src.messages.create")
@patch.object(PleaseConfigure, "src.messages.create.create")
我也嘗試過使用上下文管理器做類似的事情。 它似乎不起作用,並且變得非常令人沮喪。 感謝任何幫助 mocking 這個 function 以便我可以測試 PleaseConfigure class。
所以以下工作。
@patch('src.consumers.please_configure.create_please')
def test_handle_message(mocked_create):
cf = PleaseConfigure()
cf 實例有 dict _call { "create_please": create_please } ,它現在是 MagicMock 的一個實例,並且有一個引用 mocked_create 作為參數傳入。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.