嘲笑一段时间的Python语句

时间:2018-05-12 05:27:45

标签: python-3.x unit-testing mocking

我非常擅长用Python嘲笑。我非常深入地搜索了回答这个问题的任何帖子,但我没有这样做。我想模拟在while语句中调用的函数。反正有吗?

def some_function(self, some_param):

    some_counter = 0
    while self.func_i_want_to_mock(mock_param, mock_param2) is False:
        some_counter += 1

    return some_counter

2 个答案:

答案 0 :(得分:1)

  

我想模拟在while语句中调用的函数

如果要使用参数

,请定义副作用功能
def func_tbm_side_effect(first, second):
    return 'whatever'

现在进行测试

import unittest
import mock
import ClassWithSomeFunc

class TestClassWithSomeFunc(unittest.TestCase):
    def test_some_function(self):
        with mock.patch.object(ClassWithSomeFunc, 'some_function') as mocked_sf:
            mocked_sf.side_effect = func_tbm_side_effect
            item = ClassWithSomeFunc()
            value = item.some_function('parameter')
            self.assertEqual(value, 'endless loop')

答案 1 :(得分:0)

def some_function(self, some_param):

    some_counter = 0
    while self.func_i_want_to_mock(mock_param, mock_param) is False:
        some_counter += 1

    return some_counter



def func_i_want_to_mock(mock_param, mock_param):
    if mock_param1 == x and mock_param2 == y:
       return True
   elif """ ...  all cases"""