2017-11-05 10 views
0

는 내가 worker_functions 사전에서 fun_1 기능을 패치하려고 내가 어려움을 겪고 것 같다 :기능 맵/사전에서 함수 모의 방법?

cli.py :
import sys 

from worker_functions import (
    fun_1, 
    fun_2, 
    fun_3, 
) 

FUNCTION_MAP = { 
    'run_1': fun_1, 
    'run_2': fun_2, 
    'run_3': fun_3, 
} 

def main(): 
    command = sys.argv[1] 
    tag = sys.argv[2] 
    action = FUNCTION_MAP[command] 

    action(tag) 

내가 cli.fun_1cli.main.actioncli.action을 조롱 시도했지만이 실패 선도 .

test_cli.py :
from mock import patch 

from cli import main 


def make_test_args(tup): 
    sample_args = ['cli.py'] 
    sample_args.extend(tup) 
    return sample_args 


def test_fun_1_command(): 
    test_args = make_test_args(['run_1', 'fake_tag']) 
    with patch('sys.argv', test_args),\ 
     patch('cli.fun_1') as mock_action: 
     main() 

     mock_action.assert_called_once() 

가 나는 것 마십시오 뭔가가있다?

답변

1

FUNCTION_MAP 사전 자체에있는 참조를 패치해야합니다. 그렇게 할 수있는 patch.dict() callable 사용 : FUNCTION_MAP 사전 기능 참조가 조회되는 위치이기 때문이다

from unittest.mock import patch, MagicMock 

mock_action = MagicMock() 
with patch('sys.argv', test_args),\ 
    patch.dict('cli.FUNCTION_MAP', {'run_1': mock_action}): 
    # ... 

합니다.

+0

이것은 잠재적으로 훌륭하게 보입니다. – GiantsLoveDeathMetal

+0

mock에서'MagicMock'을 가져 옵니까? – GiantsLoveDeathMetal

+1

예, 가져 오기를 추가했습니다. –