title: Python Unit testing with mock and patch a foreign modul
body: <p>I would like to test a class which uses the Serial class from serial modul.
  I know i have to mock them, but i don't get it up and running:</p>
  
  <pre><code>from serial import Serial
  
  import unittest
  from mock import patch, MagicMock
  
  class MyClass(object):
      def __init__(self):
          self.ser = Serial('/dev', 123)
  
      def write(self, message):
          if self.ser:
              self.ser.write(message)
              return True
  
      def read(self):
          if self.ser.inWaiting():
              return self.ser.read(1)
          return None
  
  
  class MyClassTest(unittest.TestCase):
  
      def setUp(self):
  
          self.mc = MyClass()
  
      def test_init(self):
          self.mc = MyClass()
  
          #Check if...
          mock.assert_called_with('/dev', 123)
  
      def test_write(self):
          self.mc.write('lala')
  
          #Check if...
          mock.write.assert_called_with('lala')
  
      def test_read(self):
  
          #patch inWaiting function...
          mock.inWaiting.retval = 4
  
          #patch inWaiting function...
          mock.read.retval = 'lulu'
  
          x = self.mc.read()
  
          self.assertEqual('lulu')
  
          #Check if...
          mock.read.assert_called_with(1)
  </code></pre>
  
  <ul>
  <li><p>For the complete TestClass: How do i mock the Serial class so that it won't use the real one?</p></li>
  <li><p>For some tests: How do i mock the Serial.read(x) with parameter x and return value? (just like Serial.inWaiting())</p></li>
  <li><p>For some tests: How do i mock the Serial.write(message) with parameter and then test it for calling with parameter message?</p></li>
  <li><p>One bonus question: should i use unittest2 ?</p></li>
  </ul>