2

Im pretty new at mocking in Python. I searched pretty deeply for any post that answered this question, but i failed to do so. I want to mock a function that is called within a while statement. Is there anyway to do this?

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 Answers 2

1

I want to mock a function that is called within a while statement

Define a side effect function if you want to play with the parameters

def func_tbm_side_effect(first, second):
    return 'whatever'

Now with the testing

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')
Sign up to request clarification or add additional context in comments.

1 Comment

I see, where I was making my mistake, thanks for the help!
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"""

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.