title: How to mock RPi.GPIO in python
body: <p>I'm attempting to mock <code>RPi.GPIO</code> in python code to do some unit testing.</p>
  
  <p>The problem I have is that my import of <code>RPi.GPIO</code> fails when called in my unit tests which do not run on the actual Raspberry Pi.</p>
  
  <p>e.g.</p>
  
  <p><strong>tests.py</strong></p>
  
  <pre><code>import iohandler
  ...
  ...
  </code></pre>
  
  <p><strong>iohandler.py</strong></p>
  
  <pre><code>import RPi.GPIO
  
  def function_to_test():
      pass
  </code></pre>
  
  <p>The problem here is that for tests to run it must import <code>iohandler</code> which in turn must import <code>RPi.GPIO</code>. This fails as <code>RPi.GPIO</code> is not installed on the machine which will run the tests.</p>
  
  <p>I've attempted to try and trick the modules after looking at another answer on this site as follows:</p>
  
  <p><strong>tests.py</strong></p>
  
  <pre><code>import sys
  import gpiomock # this is a file on the file system
  sys.modules["RPi.GPIO"] = gpiomock.GPIO()
  
  import iohandler # the .py file that contains the actual GPIO import
  </code></pre>
  
  <p><strong>gpiomock.py</strong></p>
  
  <pre><code>class GPIO():
      ...
      ...
  </code></pre>
  
  <p>As <code>sys.modules</code> is just a dictionary I would have thought this would work as I am providing a key for lookup of <code>RPi.GPIO</code> and also what I want to replace it with. However I get the following error message.</p>
  
  <p><code>ImportError: No module named RPi.GPIO</code></p>
  
  <p>It feels like the <em>nested</em> structure of the actual <code>RPi.GPIO</code> library is causing this not to work.</p>
  
  <p>Any suggestions on how I can make this work?</p>