title: Mocking two functions with patch for a unit test
body: <p>I have a function I want to unit test contains calls two other functions. I am unsure how can I mock both functions at the same time properly using patch. I have provided an example of what I mean below. When I run nosetests, the tests pass but I feel that there must be a cleaner way to do this and I do not really Understand the piece regarding f.close()...</p>
  
  <p>The directory structure looks like this:</p>
  
  <pre><code>program/
    program/
      data.py
    tests/
      data_test.py
  </code></pre>
  
  <p>data.py:</p>
  
  <pre><code>import cPickle
  
  def write_out(file_path, data):
      f = open(file_path, 'wb')
      cPickle.dump(data, f)
      f.close()
  </code></pre>
  
  <p>data_test.py:</p>
  
  <pre><code>from mock import MagicMock, patch
  
  def test_write_out():
      path = '~/collection'
      mock_open = MagicMock()
      mock_pickle = MagicMock()
      f_mock = MagicMock()
      with patch('__builtin__.open', mock_open):
          f = mock_open.return_value
          f.method.return_value = path
          with patch('cPickle.dump', mock_pickle):
              write_out(path, 'data')
              mock_open.assert_called_once_with('~/collection', 'wb')
              f.close.assert_any_call()
              mock_pickle.assert_called_once_with('data', f)
  </code></pre>
  
  <p>Results:</p>
  
  <pre><code>$ nosetests
  .
  ----------------------------------------------------------------------
  Ran 1 test in 0.008s
  OK
  </code></pre>