title: How can I mock a module that is imported from a function and not present in sys.path?
body: <p>I am <code>unittest</code>ing code which contains a method that does a local import.</p>
  
  <pre><code>def function_under_test():
      import unknown.dependency
  </code></pre>
  
  <p>(I'm not using an import at the top of the <code>.py</code> file because it may or may not be present when the function is called.)</p>
  
  <p>Mocking <code>unknown.dependency</code> in the usual way only works if it can be found somewhere in <code>sys.path</code>.  Otherwise, the call to <code>patch</code> fails (it refuses to mock something it cannot look at):</p>
  
  <pre><code>with mock.patch('unknown.dependency'):
      function_under_test()
  &gt;&gt;&gt; ImportError: No module named 'unknown'
  </code></pre>
  
  <p>The docs suggest that I should patch to the namespace where the module is used -- in this case, <code>function_under_test</code>.  However, when that namespace is a function, this doesn't cut it.  The call to <code>patch</code> succeeds, but the actual import statement is still referencing the original, non-existing <code>unknown</code> module, which cannot be found.</p>
  
  <pre><code>with mock.patch('method_under_test.unknown'):
      print("fails")
  &gt;&gt;&gt; ImportError: No module named 'unknown'
  </code></pre>
  
  <p>So, how do I replace the dependency module with a mock, if the module itself does not exist <em>and</em> it is imported from a function?</p>