title: Python – How to mock a single function
body: <p>From the Mock docs, I wasn't able to understand how to implement the following type of pattern successfully. <code>fetch_url</code> does not exist inside of a class.</p>
  
  <p>My function in the <code>auth.py</code> file:</p>
  
  <pre><code>def fetch_url(url, method=urlfetch.GET, data=''):
      """Send a HTTP request"""
  
      result = urlfetch.fetch(url=url, method=method, payload=data,
                              headers={'Access-Control-Allow-Origin': '*'})
  
      return result.content
  </code></pre>
  
  <p>My test:</p>
  
  <pre><code>import unittest
  from mock import Mock
  
  class TestUrlFetch(unittest.TestCase):
  
      def test_fetch_url(self):
          from console.auth import fetch_url
  
          # Create a mock object based on the fetch_url function
          mock = Mock(spec=fetch_url)
  
          # Mock the fetch_url function
          content = mock.fetch_url('https://google.com')
  
          # Test that content is not empty
          self.assertIsNotNone(content)
  </code></pre>
  
  <p>If what I'm doing is completely in the wrong direction, please shed some light on the correct solution.</p>
  
  <p>The test is not working, and is producing the following error:</p>
  
  <pre><code>======================================================================
  ERROR: test_fetch_url (console.tests.test_auth.TestUrlFetch)
  ----------------------------------------------------------------------
  Traceback (most recent call last):
    File "/Users/bengrunfeld/Desktop/Work/code/wf-ghconsole/console/tests/test_auth.py", line 34, in test_fetch_url
      content = mock.fetch_url('https://google.com')
    File "/Users/bengrunfeld/.virtualenvs/env2/lib/python2.7/site-packages/mock.py", line 658, in __getattr__
      raise AttributeError("Mock object has no attribute %r" % name)
  AttributeError: Mock object has no attribute 'fetch_url'
  -------------------- &gt;&gt; begin captured logging &lt;&lt; --------------------
  root: DEBUG: Using threading.local
  --------------------- &gt;&gt; end captured logging &lt;&lt; ---------------------
  
  ----------------------------------------------------------------------
  Ran 1 test in 0.277s
  
  FAILED (errors=1)
  </code></pre>