title: Mock open() function used in a class method
body: <p>I tried to mock the open function used in a method of my class.
  I found this thread <a href="https://stackoverflow.com/questions/1289894/how-do-i-mock-an-open-used-in-a-with-statement-using-the-mock-framework-in-pyth">How do I mock an open used in a with statement (using the Mock framework in Python)?</a> but could not solve my issue. Also the unittest documention shows a solution which also didn't mock my open <a href="https://docs.python.org/3/library/unittest.mock-examples.html#patch-decorators" rel="noreferrer">https://docs.python.org/3/library/unittest.mock-examples.html#patch-decorators</a></p>
  
  <p>This is my class with the method where the open function is used:</p>
  
  <pre><code>#__init.py__
  
  import json
  
  class MyClass:
  
      def save_data_to_file(self, data):
          with open('/tmp/data.json', 'w') as file:
              json.dump(data, file)
  ...
  mc = MyClass()
  </code></pre>
  
  <p>Now I found a little different solution. This is my test:</p>
  
  <pre><code>#save_to_file_test.py
  
  from mymodule import MyClass
  from mock import mock_open, patch
  import ast
  
  class SaveToFileTest(unittest.TestCase):
  
      def setUp(self):
          self.mc = MyClass()
          self.data = [
              {'id': 5414470, 'name': 'peter'},
              {'id': 5414472, 'name': 'tom'},
              {'id': 5414232, 'name': 'pit'},
          ]
  
      def test_save_data_to_file(self):
          m = mock_open()
          with patch('mymodule.open', m, create=True):
              self.mc.save_data_to_file(self.data)
              string = ''
              for call in m.return_value.write.mock_calls:
                  string += (call[1][0])
              list = ast.literal_eval(string)
              assertEquals = (list, self.data)
  </code></pre>
  
  <p>I'm not sure if this is the best way to test the content which should be written to a file.
  When I test the mock_calls (call_args_list is the same) this are the arguments which are passed to the file handle.
  Any advice, improvements and suggestions are welcome.</p>