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?
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.
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.
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.
I reached here from google, only to realize after a while that this has been builtin in mock since 1.0 using mock_open
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...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With