title: How do I override imports of other files for unit testing
body: <p>I am currently attempting to write unit tests for my Main.py's <code>main()</code> function</p>
  
  <p>Here is a simplified version of my Main.py:</p>
  
  <pre><code>from Configuration import Configuration # Configuration.py is a file in the same dir
  
  def main():
    try:
      Configuration('settings.ini')
    except:
      sys.exit(1) # Test path1
    sys.exit(0) # Test path2
  
  if __name__ == '__main__':
      main()
  </code></pre>
  
  <p>In my <code>Unit Tests\MainUnitTests.py</code> I want to import <code>..\Main.py</code> and fake the <code>Configuration</code> class in such a way that I can hit <code>Test path1</code> and <code>Test path2</code></p>
  
  <p>I found that i can assert <code>sys.exit()</code> with the following:</p>
  
  <pre><code>with self.assertRaises(SystemExit) as cm:
    main()
  self.assertEqual(cm.exception.code, 1)
  </code></pre>
  
  <p>but I am having trouble overriding the <code>from Configuration import Configuration</code></p>
  
  <p>Thoughts?</p>
  
  <p>So far I have tried the following within <code>Unit Tests\MainUnitTests.py</code>:</p>
  
  <pre><code>class FakeFactory(object):
    def __init__(self, *a):
      pass
  
  sys.modules['Configuration'] = __import__('FakeFactory')
  
  class Configuration(FakeFactory):
    pass
  </code></pre>
  
  <p>Another example for demonstration:</p>
  
  <p>foo.py:</p>
  
  <pre><code>from bar import a,b
  
  x = a()
  
  class a(object):
    def __init__(self):
      self.q = 2
  
  y = a()
  
  print x.q, y.q # prints '1 2' as intended
  
  b() # I want this to print 2 without modifying bar.py
  </code></pre>
  
  <p>bar.py:</p>
  
  <pre><code>class a(object):
    def __init__(self):
      self.q = 1
  
  def b():
    t = a()
    print t.q
  </code></pre>