Python mock 启动整个程序而不是将输入替换为特定方法

Python mock launches whole program instead of substituting input to specific method

我有一个程序,例如:

模块"Main":

import SymbolCalculator as sc


# Defining constants:
TEXT_INTRO = sc.TEXT_INTRO
TEXT_INVITE = "Please print any sentence below:\n"
sentence = ""
# Printing introduction to the program:
print TEXT_INTRO

def getting_result():
    # Getting input string from console
    sentence = sc.get_input_from_prompt(TEXT_INVITE)
    # Forming result list via methods defined in SymbolCalculator module
    return sc.characters_calculator(sentence)
result_list = getting_result()
# Computing summary via method defined in SymbolCalculator module
sc.printing_summary(sentence, result_list)
# Printing tuples with characters and their occurrences raw-by-raw
sc.printing_list(result_list)
raw_input("Please press any button to quit the program.")
print 'Bye!!!'

我正在尝试使用模拟 raw_input(更新)创建一个简单的单元测试:

from unittest import TestCase, main
from mock import patch
from Ex_41_42_SymbolCalculatorMain import getting_result


class Ex_4a1_SymbolCalculatorUnitTestWMock(TestCase):
    #@patch ('Ex_41_42_SymbolCalculator.get_input_from_prompt', return_value = 'aabc')
    def test_valid_input(self):
        with patch('__builtin__.raw_input', return_value = 'aaabbc') as _raw_input:
            self.assertEqual(getting_result(), [('a', 3), ('b', 2), ('c', 1)])
            _raw_input.assert_called_once_with('Please print any sentence below:\n')

    @patch ('Ex_41_42_SymbolCalculator.get_input_from_prompt', return_value = '')
    def test_empty_input(self, mock):
        self.assertEqual(getting_result(), [])

if __name__ == "__main__":
    main()

此外,我还尝试通过自己对测试方法进行装饰,例如:

...
@patch ('Ex_41_42_SymbolCalculator.get_input_from_prompt', return_value = 'aabc')
...

我的问题是,当我启动测试时,所有 "Main" 模块都在 getting_result 方法调用时运行。所以它从一开始就开始,要求我通过命令提示符等进行输入。因此不仅是测试,而且整个常规程序都是 运行.

虽然我期望只有 getting_result 方法被调用 return_value

请指教

导入模块时,模块中的所有代码都是运行。使用 from Ex_41_42_SymbolCalculatorMain import getting_result 而不是 import Ex_41_42_SymbolCalculatorMain 并不重要;您仍在导入模块。没有办法只 "get" 一个函数而不执行模块中的其余代码。

相反,您应该将该代码放在一个函数中,然后从 if __name__ == "__main__" 块中调用它,如下所示:

def getting_result():
    # Getting input string from console
    sentence = sc.get_input_from_prompt(TEXT_INVITE)
    # Forming result list via methods defined in SymbolCalculator module
    return sc.characters_calculator(sentence)

def do_stuff():
    print TEXT_INTRO
    result_list = getting_result()
    # Computing summary via method defined in SymbolCalculator module
    sc.printing_summary(sentence, result_list)
    # Printing tuples with characters and their occurrences raw-by-raw
    sc.printing_list(result_list)
    raw_input("Please press any button to quit the program.")
    print 'Bye!!!'

if __name__ == "__main__":
    do_stuff()

然后 do_stuff() 只会 运行 如果你直接执行那个文件,如果你导入它则不会。这将允许您导入模块而无需 运行ning do_stuff 中的内容。您可以通过搜索此站点的无数问题(例如 this one)来了解有关 __main__ 业务的更多信息。