Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mock call to write()

I have a logger class that needs to write strings to file. So, I have a method like so:

def write_to_file(self, string):
  self.__file_handle.write(string)

Note that error handling has been edited out. Clearly I want to test this without writing to a file. Thus mocks via Mock. I have seen this which explains how to mock open but it does not help me here -- I open the file_handle in __init__. Now, I can do that in setUp() but the mock_open seems to go out of scope after setUp and thus is of no use in the test case.

How would you write a test method to test the write_to_file method using Mock?

like image 566
Sardathrion - against SE abuse Avatar asked Nov 11 '11 14:11

Sardathrion - against SE abuse


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 does @patch do 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 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.


2 Answers

I reached here from google, only to realize after a while that this has been builtin in mock since 1.0 using mock_open

like image 139
lonetwin Avatar answered Sep 30 '22 18:09

lonetwin


Simple really...

from mock import patch

def setUp(self):
    [...]
    mock_file_handle = Mock()
    with patch('__builtin__.open') as mock_file_handle:
        self.sut = Logger()
    [...]

def test_write(self):
    [...]
    self.sut.write_message_to_file("ook?")
    self.assertTrue(self.sut.file_handle.write.called)
    self.assertTrue(self.sut.file_handle.flush.called)
    [...]

If anyone has a better solution, please let me know...

like image 45
Sardathrion - against SE abuse Avatar answered Sep 30 '22 17:09

Sardathrion - against SE abuse