我正在尝试对一个函数在另一个函数中调用进行单元测试。
def run_this_function(something):
'FOLD', {}
def go_to_the_right_street(action):
if street_we_are_on == 'pre_flop_play':
action, extra_information = run_this_function(something)
我的单元测试看起来像:
def test_go_to_the_right_street(street_we_are_on):
with patch('pb.app.run_this_function') as mocked_function:
actual = go_to_the_right_street('some_value')
# mocked_function.return_value = 'FOLD', {} tried this too but I get the same error
mocked_function.assert_called_once()
当我运行上面的代码时,我得到:
ValueError: not enough values to unpack (expected 2, got 0)
我在我的文件系统上创建了以下结构:
project
|-pb
| |-app.py
|-test_app.py
文件
app.py
:
def run_this_function(something):
return 'FOLD', {}
def go_to_the_right_street(street_we_are_on):
if street_we_are_on == 'pre_flop_play':
action, extra_information = run_this_function('something') <--- added the string definition for 'something' instead something as variable
此文件中仅存在修改(请参阅其中的注释)。
** 文件
test_app.py
**
import unittest
from unittest.mock import patch
from pb.app import go_to_the_right_street
# I have defined this function to substitute your function run_this_function()
def run_this_function_patch(something):
return 'FOLD', {}
class MyTestCase(unittest.TestCase):
def test_go_to_the_right_street(self):
with patch('pb.app.run_this_function') as mocked_function:
mocked_function.side_effect = [run_this_function_patch('something')] # <--- added this side_effect to return 'FOLD', {}
actual = go_to_the_right_street('pre_flop_play')
# mocked_function.return_value = 'FOLD', {} tried this too but I get the same error
mocked_function.assert_called_once()
if __name__ == '__main__':
unittest.main()
两个最重要的变化:
run_this_function_patch()
,用于定义side_effect
;请注意括号 []
和 ()
mocked_function.side_effect = [run_this_function_patch('something')]
在函数调用之前定义go_to_the_right_street()
这段代码的执行输出如下:
.
----------------------------------------------------------------------
Ran 1 test in 0.001s
OK