title: Mock the `fileno` method of a Python 2 `file` object
body: <p>How can I use <code>mock.patch</code> to wrap the <code>file.fileno</code> method on a <a href="https://docs.python.org/2/library/stdtypes.html#bltin-file-objects" rel="nofollow noreferrer">Python 2 file object</a>?</p>
  
  <p>When I attempt to use the normal <code>mock.patch.object</code> on the <code>file</code> instance:</p>
  
  <pre class="lang-python prettyprint-override"><code># file-fileno-mock.py
  
  import sys
  import tempfile
  
  if sys.version_info &lt; (3, 0):
      import mock
  else:
      from unittest import mock
  
  
  (foo_fileno, foo_file_path) = tempfile.mkstemp()
  
  # Open the temporary file path and get a real file object.
  with open(foo_file_path) as foo_file:
      # Patch a single attribute on the real `foo_file` object.
      with mock.patch.object(foo_file, 'fileno'):
          # Access the `fileno` method and call it,
          # which because of the mock wrapper will call a mock method instead.
          fake_foo_fileno = foo_file.fileno()
          assert fake_foo_fileno != foo_fileno
  </code></pre>
  
  <p>That works in Python 3, but in Python 2 it raises an <code>AttributeError</code>:</p>
  
  <pre class="lang-none prettyprint-override"><code>Traceback (most recent call last):
    File "file-fileno-mock.py", line 15, in &lt;module&gt;
      with mock.patch.object(foo_file, 'fileno'):
    File "[…]/mock/mock.py", line 1460, in __enter__
      setattr(self.target, self.attribute, new_attr)
  AttributeError: 'file' object attribute 'fileno' is read-only
  </code></pre>
  
  <p>Evidently <code>mock.patch</code> is attempting to write the <code>foo_file.fileno</code>
  attribute; the Python 2 <code>file</code> type disallows that, the <a href="http://file:///usr/share/doc/python3/html/library/io.html#io.FileIO" rel="nofollow noreferrer">Python 3
  equivalent</a> allows it.</p>
  
  <p>How can I <a href="https://docs.python.org/3/library/unittest.mock.html#patch-object" rel="nofollow noreferrer">use <code>mock.patch</code> as intended</a>, on a Python 2 <code>file</code> object,
  without running afoul of this special limitation in Python 2 <code>file</code>?</p>