8

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?

Cédric Julien
  • 78,516
  • 15
  • 127
  • 132
Sardathrion - against SE abuse
  • 17,269
  • 27
  • 101
  • 156

3 Answers3

8

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

Noam Hacker
  • 4,671
  • 7
  • 34
  • 55
lonetwin
  • 971
  • 10
  • 17
4

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...

Gabriel Jordão
  • 758
  • 5
  • 10
Sardathrion - against SE abuse
  • 17,269
  • 27
  • 101
  • 156
1

I would start with the ability to change __file_handle in the __init__. As if you replace this with any mock / fake object that has the .write signature you can test what is written to it.

Maybe by creating a method that sets up the __file_handle and then overwriting the method for this test?

Andrew Cox
  • 10,672
  • 3
  • 33
  • 38