title: Mocking out methods on any instance of a python class
body: <p>I want to mock out methods on any instance of some class in the production code in order to facilitate testing. Is there any library in Python which could facilitate this?</p>
  
  <p>Basically, I want to do the following, but in Python (the following code is Ruby, using the Mocha library):</p>
  
  <pre><code>  def test_stubbing_an_instance_method_on_all_instances_of_a_class
      Product.any_instance.stubs(:name).returns('stubbed_name')
      assert_equal 'stubbed_name', SomeClassThatUsesProduct.get_new_product_name
    end
  </code></pre>
  
  <p>The important thing to note from above is that I need to mock it out on the class level, since I'm actually need to mock out methods on an instance created by the thing I'm testing.</p>
  
  <p>Use Case:</p>
  
  <p>I have a class <code>QueryMaker</code> which calls a method on an instance of <code>RemoteAPI</code>. I want to mock out the <code>RemoteAPI.get_data_from_remote_server</code> method to return some constant. How do I do this inside a test without having to put a special case within the <code>RemoteAPI</code> code to check for what environment it's running in.</p>
  
  <p>Example of what I wanted in action:</p>
  
  <pre><code># a.py
  class A(object):
      def foo(self):
          return "A's foo"
  
  # b.py
  from a import A
  
  class B(object):
      def bar(self):
          x = A()
          return x.foo()
  
  # test.py
  from a import A
  from b import B
  
  def new_foo(self):
      return "New foo"
  
  A.foo = new_foo
  
  y = B()
  if y.bar() == "New foo":
      print "Success!"
  </code></pre>