mardi 4 août 2015

How to mock python's read()

I'm trying to test the read() method in the following class:

class Channel(sam.Sam):
  def __open(self):
    try:
      self.__channel = open('%s/channel.ini' % os.path.dirname(os.path.realpath(__file__)), 'r+')
    except Exception as e:
      traceback.print_exc(file = sys.stdout)
      raise e

  def read(self):
    try:
      self.__open()
      return JSONEncoder().encode({
        "status": True,
        "channel": self.__channel.read().strip()
      })
    except Exception as e:
      traceback.print_exc(file = sys.stdout)
      return JSONEncoder().encode({
        "status": False
      })
    finally:
      self.__close()

As I understand it, I should be mocking the file.read() method (in self.__channel.read(), or maybe the os.open() method, but none of the examples I've found have the call to os.open() or file.read() deep inside a class.

I already tried __builtin__.read = MagicMock(return_value="something"), and many variations thereof, but not one of them even make sense. I'm kind of lost as to how to even start this.

Is this even the right way?

Aucun commentaire:

Enregistrer un commentaire