Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

test a function called twice in python

I have the following function which is called twice

def func():     i=2     while i        call_me("abc")        i-=1 

I need to test this function whether it is called twice. Below test case test's if it called at all/many times with given arguments.

@patch('call_me') def test_func(self,mock_call_me):     self.val="abc"     self.assertEqual(func(),None)     mock_call_me.assert_called_with(self.val) 

I want to write a test case where "mock_call_me.assert_called_once_with("abc")" raises an assertion error so that i can show it is called twice.

I don't know whether it is possible or not.Can anyone tell me how to do this?

Thanks

like image 462
Ksc Avatar asked Nov 14 '14 16:11

Ksc


People also ask

What is the difference between mock and MagicMock?

So what is the difference between them? MagicMock is a subclass of Mock . It contains all magic methods pre-created and ready to use (e.g. __str__ , __len__ , etc.). Therefore, you should use MagicMock when you need magic methods, and Mock if you don't need them.

What is @patch in Python?

This, along with its subclasses, will meet most Python mocking needs that you will face in your tests. The library also provides a function, called patch() , which replaces the real objects in your code with Mock instances.

What is mocking in Python?

Mocking is simply the act of replacing the part of the application you are testing with a dummy version of that part called a mock. Instead of calling the actual implementation, you would call the mock, and then make assertions about what you expect to happen.

What is Side_effect in mock Python?

side_effect: A function to be called whenever the Mock is called. See the side_effect attribute. Useful for raising exceptions or dynamically changing return values. The function is called with the same arguments as the mock, and unless it returns DEFAULT , the return value of this function is used as the return value.


1 Answers

@patch('call_me') def test_func(self,mock_call_me):   self.assertEqual(func(),None)   self.assertEqual(mock_call_me.call_count, 2) 
like image 170
coldmind Avatar answered Sep 18 '22 13:09

coldmind