How to unit test this code with pymox?

903 views Asked by At

So I have installed pymox and I would like to test this method:

class HttpStorage():

    def download(self, input, output):
        try:
            file_to_download = urllib2.urlopen(input)
        except URLError:
            raise IOError("Opening input URL failed")

        f = open(output, "wb")
        f.write(file_to_download.read())
        f.close()
        return True

I am reading through the pymox documentation but I cannot figure out how to do it. Could you help me with some example code?

1

There are 1 answers

0
chapter09 On BEST ANSWER
import unittest
import mox

class HttpStorageTest(mox.MoxTestBase):

  def setUp(self):
    self.httpstorage = HttpStorage()

  def test_download(self):
    self.mox.StubOutWithMock(urllib2, "urlopen")
    test_file = open("testfile")
    urllib2.urlopen(mox.IgnoreArg()).AndReturn(test_file)

    self.mox.ReplayAll()
    feedback = self.httpstorage.download(test_input, test_output)
    self.assertEqual(feedback, True)

You could try this format to test your download funciton, as the urllib2.openurl() has been mocked to do unit test.